Merge branch '2.0.x' into 2.1.x
Closes gh-17078
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -53,9 +53,7 @@ public class FindMainClass extends Task {
|
||||
if (!StringUtils.hasText(mainClass)) {
|
||||
mainClass = findMainClass();
|
||||
if (!StringUtils.hasText(mainClass)) {
|
||||
throw new BuildException(
|
||||
"Could not determine main class given @classesRoot "
|
||||
+ this.classesRoot);
|
||||
throw new BuildException("Could not determine main class given @classesRoot " + this.classesRoot);
|
||||
}
|
||||
}
|
||||
handle(mainClass);
|
||||
@@ -63,17 +61,14 @@ public class FindMainClass extends Task {
|
||||
|
||||
private String findMainClass() {
|
||||
if (this.classesRoot == null) {
|
||||
throw new BuildException(
|
||||
"one of @mainClass or @classesRoot must be specified");
|
||||
throw new BuildException("one of @mainClass or @classesRoot must be specified");
|
||||
}
|
||||
if (!this.classesRoot.exists()) {
|
||||
throw new BuildException(
|
||||
"@classesRoot " + this.classesRoot + " does not exist");
|
||||
throw new BuildException("@classesRoot " + this.classesRoot + " does not exist");
|
||||
}
|
||||
try {
|
||||
if (this.classesRoot.isDirectory()) {
|
||||
return MainClassFinder.findSingleMainClass(this.classesRoot,
|
||||
SPRING_BOOT_APPLICATION_CLASS_NAME);
|
||||
return MainClassFinder.findSingleMainClass(this.classesRoot, SPRING_BOOT_APPLICATION_CLASS_NAME);
|
||||
}
|
||||
return MainClassFinder.findSingleMainClass(new JarFile(this.classesRoot), "/",
|
||||
SPRING_BOOT_APPLICATION_CLASS_NAME);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -60,8 +60,7 @@ import javax.tools.StandardLocation;
|
||||
"org.springframework.boot.autoconfigure.AutoConfigureOrder" })
|
||||
public class AutoConfigureAnnotationProcessor extends AbstractProcessor {
|
||||
|
||||
protected static final String PROPERTIES_PATH = "META-INF/"
|
||||
+ "spring-autoconfigure-metadata.properties";
|
||||
protected static final String PROPERTIES_PATH = "META-INF/" + "spring-autoconfigure-metadata.properties";
|
||||
|
||||
private final Map<String, String> annotations;
|
||||
|
||||
@@ -79,30 +78,23 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor {
|
||||
}
|
||||
|
||||
protected void addAnnotations(Map<String, String> annotations) {
|
||||
annotations.put("Configuration",
|
||||
"org.springframework.context.annotation.Configuration");
|
||||
annotations.put("ConditionalOnClass",
|
||||
"org.springframework.boot.autoconfigure.condition.ConditionalOnClass");
|
||||
annotations.put("ConditionalOnBean",
|
||||
"org.springframework.boot.autoconfigure.condition.ConditionalOnBean");
|
||||
annotations.put("Configuration", "org.springframework.context.annotation.Configuration");
|
||||
annotations.put("ConditionalOnClass", "org.springframework.boot.autoconfigure.condition.ConditionalOnClass");
|
||||
annotations.put("ConditionalOnBean", "org.springframework.boot.autoconfigure.condition.ConditionalOnBean");
|
||||
annotations.put("ConditionalOnSingleCandidate",
|
||||
"org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate");
|
||||
annotations.put("ConditionalOnWebApplication",
|
||||
"org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication");
|
||||
annotations.put("AutoConfigureBefore",
|
||||
"org.springframework.boot.autoconfigure.AutoConfigureBefore");
|
||||
annotations.put("AutoConfigureAfter",
|
||||
"org.springframework.boot.autoconfigure.AutoConfigureAfter");
|
||||
annotations.put("AutoConfigureOrder",
|
||||
"org.springframework.boot.autoconfigure.AutoConfigureOrder");
|
||||
annotations.put("AutoConfigureBefore", "org.springframework.boot.autoconfigure.AutoConfigureBefore");
|
||||
annotations.put("AutoConfigureAfter", "org.springframework.boot.autoconfigure.AutoConfigureAfter");
|
||||
annotations.put("AutoConfigureOrder", "org.springframework.boot.autoconfigure.AutoConfigureOrder");
|
||||
}
|
||||
|
||||
private void addValueExtractors(Map<String, ValueExtractor> attributes) {
|
||||
attributes.put("Configuration", ValueExtractor.allFrom("value"));
|
||||
attributes.put("ConditionalOnClass", new OnClassConditionValueExtractor());
|
||||
attributes.put("ConditionalOnBean", new OnBeanConditionValueExtractor());
|
||||
attributes.put("ConditionalOnSingleCandidate",
|
||||
new OnBeanConditionValueExtractor());
|
||||
attributes.put("ConditionalOnSingleCandidate", new OnBeanConditionValueExtractor());
|
||||
attributes.put("ConditionalOnWebApplication", ValueExtractor.allFrom("type"));
|
||||
attributes.put("AutoConfigureBefore", ValueExtractor.allFrom("value", "name"));
|
||||
attributes.put("AutoConfigureAfter", ValueExtractor.allFrom("value", "name"));
|
||||
@@ -115,8 +107,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean process(Set<? extends TypeElement> annotations,
|
||||
RoundEnvironment roundEnv) {
|
||||
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
|
||||
for (Map.Entry<String, String> entry : this.annotations.entrySet()) {
|
||||
process(roundEnv, entry.getKey(), entry.getValue());
|
||||
}
|
||||
@@ -131,36 +122,30 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor {
|
||||
return false;
|
||||
}
|
||||
|
||||
private void process(RoundEnvironment roundEnv, String propertyKey,
|
||||
String annotationName) {
|
||||
TypeElement annotationType = this.processingEnv.getElementUtils()
|
||||
.getTypeElement(annotationName);
|
||||
private void process(RoundEnvironment roundEnv, String propertyKey, String annotationName) {
|
||||
TypeElement annotationType = this.processingEnv.getElementUtils().getTypeElement(annotationName);
|
||||
if (annotationType != null) {
|
||||
for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) {
|
||||
Element enclosingElement = element.getEnclosingElement();
|
||||
if (enclosingElement != null
|
||||
&& enclosingElement.getKind() == ElementKind.PACKAGE) {
|
||||
if (enclosingElement != null && enclosingElement.getKind() == ElementKind.PACKAGE) {
|
||||
processElement(element, propertyKey, annotationName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processElement(Element element, String propertyKey,
|
||||
String annotationName) {
|
||||
private void processElement(Element element, String propertyKey, String annotationName) {
|
||||
try {
|
||||
String qualifiedName = Elements.getQualifiedName(element);
|
||||
AnnotationMirror annotation = getAnnotation(element, annotationName);
|
||||
if (qualifiedName != null && annotation != null) {
|
||||
List<Object> values = getValues(propertyKey, annotation);
|
||||
this.properties.put(qualifiedName + "." + propertyKey,
|
||||
toCommaDelimitedString(values));
|
||||
this.properties.put(qualifiedName + "." + propertyKey, toCommaDelimitedString(values));
|
||||
this.properties.put(qualifiedName, "");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(
|
||||
"Error processing configuration meta-data on " + element, ex);
|
||||
throw new IllegalStateException("Error processing configuration meta-data on " + element, ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,8 +179,8 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor {
|
||||
|
||||
private void writeProperties() throws IOException {
|
||||
if (!this.properties.isEmpty()) {
|
||||
FileObject file = this.processingEnv.getFiler()
|
||||
.createResource(StandardLocation.CLASS_OUTPUT, "", PROPERTIES_PATH);
|
||||
FileObject file = this.processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "",
|
||||
PROPERTIES_PATH);
|
||||
try (OutputStream outputStream = file.openOutputStream()) {
|
||||
this.properties.store(outputStream, null);
|
||||
}
|
||||
@@ -263,8 +248,8 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor {
|
||||
@Override
|
||||
public List<Object> getValues(AnnotationMirror annotation) {
|
||||
Map<String, AnnotationValue> attributes = new LinkedHashMap<>();
|
||||
annotation.getElementValues().forEach((key, value) -> attributes
|
||||
.put(key.getSimpleName().toString(), value));
|
||||
annotation.getElementValues()
|
||||
.forEach((key, value) -> attributes.put(key.getSimpleName().toString(), value));
|
||||
if (attributes.containsKey("name")) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
@@ -290,8 +275,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor {
|
||||
}
|
||||
|
||||
private int compare(Object o1, Object o2) {
|
||||
return Comparator.comparing(this::isSpringClass)
|
||||
.thenComparing(String.CASE_INSENSITIVE_ORDER)
|
||||
return Comparator.comparing(this::isSpringClass).thenComparing(String.CASE_INSENSITIVE_ORDER)
|
||||
.compare(o1.toString(), o2.toString());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -36,8 +36,7 @@ final class Elements {
|
||||
TypeElement enclosingElement = getEnclosingTypeElement(element.asType());
|
||||
if (enclosingElement != null) {
|
||||
return getQualifiedName(enclosingElement) + "$"
|
||||
+ ((DeclaredType) element.asType()).asElement().getSimpleName()
|
||||
.toString();
|
||||
+ ((DeclaredType) element.asType()).asElement().getSimpleName().toString();
|
||||
}
|
||||
if (element instanceof TypeElement) {
|
||||
return ((TypeElement) element).getQualifiedName().toString();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -52,31 +52,22 @@ public class AutoConfigureAnnotationProcessorTests {
|
||||
Properties properties = compile(TestClassConfiguration.class);
|
||||
assertThat(properties).hasSize(6);
|
||||
assertThat(properties).containsEntry(
|
||||
"org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration.ConditionalOnClass",
|
||||
"org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration.ConditionalOnClass",
|
||||
"java.io.InputStream,org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration$Nested,org.springframework.foo");
|
||||
assertThat(properties)
|
||||
.containsKey("org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration");
|
||||
assertThat(properties)
|
||||
.containsKey("org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration.Configuration");
|
||||
assertThat(properties)
|
||||
.doesNotContainKey("org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration$Nested");
|
||||
.containsKey("org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration");
|
||||
assertThat(properties).containsKey(
|
||||
"org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration.Configuration");
|
||||
assertThat(properties).doesNotContainKey(
|
||||
"org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration$Nested");
|
||||
assertThat(properties).containsEntry(
|
||||
"org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration.ConditionalOnBean",
|
||||
"org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration.ConditionalOnBean",
|
||||
"java.io.OutputStream");
|
||||
assertThat(properties).containsEntry(
|
||||
"org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration.ConditionalOnSingleCandidate",
|
||||
"java.io.OutputStream");
|
||||
assertThat(properties).containsEntry(
|
||||
"org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration.ConditionalOnWebApplication",
|
||||
"SERVLET");
|
||||
assertThat(properties).containsEntry("org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration.ConditionalOnSingleCandidate", "java.io.OutputStream");
|
||||
assertThat(properties).containsEntry("org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration.ConditionalOnWebApplication", "SERVLET");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -93,38 +84,29 @@ public class AutoConfigureAnnotationProcessorTests {
|
||||
Properties properties = compile(TestMethodConfiguration.class);
|
||||
List<String> matching = new ArrayList<>();
|
||||
for (Object key : properties.keySet()) {
|
||||
if (key.toString().startsWith(
|
||||
"org.springframework.boot.autoconfigureprocessor.TestMethodConfiguration")) {
|
||||
if (key.toString().startsWith("org.springframework.boot.autoconfigureprocessor.TestMethodConfiguration")) {
|
||||
matching.add(key.toString());
|
||||
}
|
||||
}
|
||||
assertThat(matching).hasSize(2)
|
||||
.contains("org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestMethodConfiguration")
|
||||
.contains("org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestMethodConfiguration.Configuration");
|
||||
.contains("org.springframework.boot.autoconfigureprocessor." + "TestMethodConfiguration")
|
||||
.contains("org.springframework.boot.autoconfigureprocessor." + "TestMethodConfiguration.Configuration");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void annotatedClassWithOrder() throws Exception {
|
||||
Properties properties = compile(TestOrderedClassConfiguration.class);
|
||||
assertThat(properties).containsEntry(
|
||||
"org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestOrderedClassConfiguration.ConditionalOnClass",
|
||||
"org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.ConditionalOnClass",
|
||||
"java.io.InputStream,java.io.OutputStream");
|
||||
assertThat(properties).containsEntry("org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestOrderedClassConfiguration.AutoConfigureBefore", "test.before1,test.before2");
|
||||
assertThat(properties).containsEntry(
|
||||
"org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestOrderedClassConfiguration.AutoConfigureBefore",
|
||||
"test.before1,test.before2");
|
||||
assertThat(properties).containsEntry(
|
||||
"org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestOrderedClassConfiguration.AutoConfigureAfter",
|
||||
"org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.AutoConfigureAfter",
|
||||
"java.io.ObjectInputStream");
|
||||
assertThat(properties)
|
||||
.containsEntry(
|
||||
"org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestOrderedClassConfiguration.AutoConfigureOrder",
|
||||
"123");
|
||||
assertThat(properties).containsEntry(
|
||||
"org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.AutoConfigureOrder",
|
||||
"123");
|
||||
}
|
||||
|
||||
private Properties compile(Class<?>... types) throws IOException {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -29,8 +29,7 @@ import javax.annotation.processing.SupportedAnnotationTypes;
|
||||
*
|
||||
* @author Madhura Bhave
|
||||
*/
|
||||
@SupportedAnnotationTypes({
|
||||
"org.springframework.boot.autoconfigureprocessor.TestConfiguration",
|
||||
@SupportedAnnotationTypes({ "org.springframework.boot.autoconfigureprocessor.TestConfiguration",
|
||||
"org.springframework.boot.autoconfigureprocessor.TestConditionalOnClass",
|
||||
"org.springframework.boot.autoconfigure.condition.TestConditionalOnBean",
|
||||
"org.springframework.boot.autoconfigure.condition.TestConditionalOnSingleCandidate",
|
||||
@@ -38,8 +37,7 @@ import javax.annotation.processing.SupportedAnnotationTypes;
|
||||
"org.springframework.boot.autoconfigureprocessor.TestAutoConfigureBefore",
|
||||
"org.springframework.boot.autoconfigureprocessor.TestAutoConfigureAfter",
|
||||
"org.springframework.boot.autoconfigureprocessor.TestAutoConfigureOrder" })
|
||||
public class TestAutoConfigureAnnotationProcessor
|
||||
extends AutoConfigureAnnotationProcessor {
|
||||
public class TestAutoConfigureAnnotationProcessor extends AutoConfigureAnnotationProcessor {
|
||||
|
||||
private final File outputLocation;
|
||||
|
||||
@@ -52,10 +50,8 @@ public class TestAutoConfigureAnnotationProcessor
|
||||
put(annotations, "Configuration", TestConfiguration.class);
|
||||
put(annotations, "ConditionalOnClass", TestConditionalOnClass.class);
|
||||
put(annotations, "ConditionalOnBean", TestConditionalOnBean.class);
|
||||
put(annotations, "ConditionalOnSingleCandidate",
|
||||
TestConditionalOnSingleCandidate.class);
|
||||
put(annotations, "ConditionalOnWebApplication",
|
||||
TestConditionalOnWebApplication.class);
|
||||
put(annotations, "ConditionalOnSingleCandidate", TestConditionalOnSingleCandidate.class);
|
||||
put(annotations, "ConditionalOnWebApplication", TestConditionalOnWebApplication.class);
|
||||
put(annotations, "AutoConfigureBefore", TestAutoConfigureBefore.class);
|
||||
put(annotations, "AutoConfigureAfter", TestAutoConfigureAfter.class);
|
||||
put(annotations, "AutoConfigureOrder", TestAutoConfigureOrder.class);
|
||||
|
||||
@@ -53,8 +53,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder {
|
||||
* @return this builder
|
||||
* @throws IOException in case of I/O errors
|
||||
*/
|
||||
public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(
|
||||
InputStream inputStream) throws IOException {
|
||||
public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(InputStream inputStream) throws IOException {
|
||||
return withJsonResource(inputStream, this.defaultCharset);
|
||||
}
|
||||
|
||||
@@ -70,8 +69,8 @@ public final class ConfigurationMetadataRepositoryJsonBuilder {
|
||||
* @return this builder
|
||||
* @throws IOException in case of I/O errors
|
||||
*/
|
||||
public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(
|
||||
InputStream inputStream, Charset charset) throws IOException {
|
||||
public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(InputStream inputStream, Charset charset)
|
||||
throws IOException {
|
||||
if (inputStream == null) {
|
||||
throw new IllegalArgumentException("InputStream must not be null.");
|
||||
}
|
||||
@@ -92,8 +91,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder {
|
||||
return result;
|
||||
}
|
||||
|
||||
private SimpleConfigurationMetadataRepository add(InputStream in, Charset charset)
|
||||
throws IOException {
|
||||
private SimpleConfigurationMetadataRepository add(InputStream in, Charset charset) throws IOException {
|
||||
try {
|
||||
RawConfigurationMetadata metadata = this.reader.read(in, charset);
|
||||
return create(metadata);
|
||||
@@ -103,16 +101,14 @@ public final class ConfigurationMetadataRepositoryJsonBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
private SimpleConfigurationMetadataRepository create(
|
||||
RawConfigurationMetadata metadata) {
|
||||
private SimpleConfigurationMetadataRepository create(RawConfigurationMetadata metadata) {
|
||||
SimpleConfigurationMetadataRepository repository = new SimpleConfigurationMetadataRepository();
|
||||
repository.add(metadata.getSources());
|
||||
for (ConfigurationMetadataItem item : metadata.getItems()) {
|
||||
ConfigurationMetadataSource source = metadata.getSource(item);
|
||||
repository.add(item, source);
|
||||
}
|
||||
Map<String, ConfigurationMetadataProperty> allProperties = repository
|
||||
.getAllProperties();
|
||||
Map<String, ConfigurationMetadataProperty> allProperties = repository.getAllProperties();
|
||||
for (ConfigurationMetadataHint hint : metadata.getHints()) {
|
||||
ConfigurationMetadataProperty property = allProperties.get(hint.getId());
|
||||
if (property != null) {
|
||||
@@ -134,14 +130,12 @@ public final class ConfigurationMetadataRepositoryJsonBuilder {
|
||||
return repository;
|
||||
}
|
||||
|
||||
private void addValueHints(ConfigurationMetadataProperty property,
|
||||
ConfigurationMetadataHint hint) {
|
||||
private void addValueHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) {
|
||||
property.getHints().getValueHints().addAll(hint.getValueHints());
|
||||
property.getHints().getValueProviders().addAll(hint.getValueProviders());
|
||||
}
|
||||
|
||||
private void addMapHints(ConfigurationMetadataProperty property,
|
||||
ConfigurationMetadataHint hint) {
|
||||
private void addMapHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) {
|
||||
property.getHints().getKeyHints().addAll(hint.getValueHints());
|
||||
property.getHints().getKeyProviders().addAll(hint.getValueProviders());
|
||||
}
|
||||
@@ -153,8 +147,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder {
|
||||
* @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance.
|
||||
* @throws IOException on error
|
||||
*/
|
||||
public static ConfigurationMetadataRepositoryJsonBuilder create(
|
||||
InputStream... inputStreams) throws IOException {
|
||||
public static ConfigurationMetadataRepositoryJsonBuilder create(InputStream... inputStreams) throws IOException {
|
||||
ConfigurationMetadataRepositoryJsonBuilder builder = create();
|
||||
for (InputStream inputStream : inputStreams) {
|
||||
builder = builder.withJsonResource(inputStream);
|
||||
@@ -176,8 +169,7 @@ public final class ConfigurationMetadataRepositoryJsonBuilder {
|
||||
* @param defaultCharset the default charset to use
|
||||
* @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance.
|
||||
*/
|
||||
public static ConfigurationMetadataRepositoryJsonBuilder create(
|
||||
Charset defaultCharset) {
|
||||
public static ConfigurationMetadataRepositoryJsonBuilder create(Charset defaultCharset) {
|
||||
return new ConfigurationMetadataRepositoryJsonBuilder(defaultCharset);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -90,8 +90,8 @@ public class Deprecation implements Serializable {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Deprecation{" + "level='" + this.level + '\'' + ", reason='" + this.reason
|
||||
+ '\'' + ", replacement='" + this.replacement + '\'' + '}';
|
||||
return "Deprecation{" + "level='" + this.level + '\'' + ", reason='" + this.reason + '\'' + ", replacement='"
|
||||
+ this.replacement + '\'' + '}';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -40,8 +40,7 @@ class JsonReader {
|
||||
|
||||
private final SentenceExtractor sentenceExtractor = new SentenceExtractor();
|
||||
|
||||
public RawConfigurationMetadata read(InputStream in, Charset charset)
|
||||
throws IOException {
|
||||
public RawConfigurationMetadata read(InputStream in, Charset charset) throws IOException {
|
||||
try {
|
||||
JSONObject json = readJson(in, charset);
|
||||
List<ConfigurationMetadataSource> groups = parseAllSources(json);
|
||||
@@ -60,8 +59,7 @@ class JsonReader {
|
||||
}
|
||||
}
|
||||
|
||||
private List<ConfigurationMetadataSource> parseAllSources(JSONObject root)
|
||||
throws Exception {
|
||||
private List<ConfigurationMetadataSource> parseAllSources(JSONObject root) throws Exception {
|
||||
List<ConfigurationMetadataSource> result = new ArrayList<>();
|
||||
if (!root.has("groups")) {
|
||||
return result;
|
||||
@@ -74,8 +72,7 @@ class JsonReader {
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<ConfigurationMetadataItem> parseAllItems(JSONObject root)
|
||||
throws Exception {
|
||||
private List<ConfigurationMetadataItem> parseAllItems(JSONObject root) throws Exception {
|
||||
List<ConfigurationMetadataItem> result = new ArrayList<>();
|
||||
if (!root.has("properties")) {
|
||||
return result;
|
||||
@@ -88,8 +85,7 @@ class JsonReader {
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<ConfigurationMetadataHint> parseAllHints(JSONObject root)
|
||||
throws Exception {
|
||||
private List<ConfigurationMetadataHint> parseAllHints(JSONObject root) throws Exception {
|
||||
List<ConfigurationMetadataHint> result = new ArrayList<>();
|
||||
if (!root.has("hints")) {
|
||||
return result;
|
||||
@@ -139,8 +135,7 @@ class JsonReader {
|
||||
valueHint.setValue(readItemValue(value.get("value")));
|
||||
String description = value.optString("description", null);
|
||||
valueHint.setDescription(description);
|
||||
valueHint.setShortDescription(
|
||||
this.sentenceExtractor.getFirstSentence(description));
|
||||
valueHint.setShortDescription(this.sentenceExtractor.getFirstSentence(description));
|
||||
hint.getValueHints().add(valueHint);
|
||||
}
|
||||
}
|
||||
@@ -155,8 +150,7 @@ class JsonReader {
|
||||
Iterator<?> keys = parameters.keys();
|
||||
while (keys.hasNext()) {
|
||||
String key = (String) keys.next();
|
||||
valueProvider.getParameters().put(key,
|
||||
readItemValue(parameters.get(key)));
|
||||
valueProvider.getParameters().put(key, readItemValue(parameters.get(key)));
|
||||
}
|
||||
}
|
||||
hint.getValueProviders().add(valueProvider);
|
||||
@@ -169,13 +163,11 @@ class JsonReader {
|
||||
if (object.has("deprecation")) {
|
||||
JSONObject deprecationJsonObject = object.getJSONObject("deprecation");
|
||||
Deprecation deprecation = new Deprecation();
|
||||
deprecation.setLevel(parseDeprecationLevel(
|
||||
deprecationJsonObject.optString("level", null)));
|
||||
deprecation.setLevel(parseDeprecationLevel(deprecationJsonObject.optString("level", null)));
|
||||
String reason = deprecationJsonObject.optString("reason", null);
|
||||
deprecation.setReason(reason);
|
||||
deprecation.setShortReason(this.sentenceExtractor.getFirstSentence(reason));
|
||||
deprecation
|
||||
.setReplacement(deprecationJsonObject.optString("replacement", null));
|
||||
deprecation.setReplacement(deprecationJsonObject.optString("replacement", null));
|
||||
return deprecation;
|
||||
}
|
||||
return object.optBoolean("deprecated") ? new Deprecation() : null;
|
||||
|
||||
@@ -34,8 +34,7 @@ class RawConfigurationMetadata {
|
||||
|
||||
private final List<ConfigurationMetadataHint> hints;
|
||||
|
||||
RawConfigurationMetadata(List<ConfigurationMetadataSource> sources,
|
||||
List<ConfigurationMetadataItem> items,
|
||||
RawConfigurationMetadata(List<ConfigurationMetadataSource> sources, List<ConfigurationMetadataItem> items,
|
||||
List<ConfigurationMetadataHint> hints) {
|
||||
this.sources = new ArrayList<>(sources);
|
||||
this.items = new ArrayList<>(items);
|
||||
@@ -56,9 +55,7 @@ class RawConfigurationMetadata {
|
||||
return this.sources.stream()
|
||||
.filter((candidate) -> item.getSourceType().equals(candidate.getType())
|
||||
&& item.getId().startsWith(candidate.getGroupId()))
|
||||
.max(Comparator
|
||||
.comparingInt((candidate) -> candidate.getGroupId().length()))
|
||||
.orElse(null);
|
||||
.max(Comparator.comparingInt((candidate) -> candidate.getGroupId().length())).orElse(null);
|
||||
}
|
||||
|
||||
public List<ConfigurationMetadataItem> getItems() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -29,8 +29,7 @@ import java.util.Map;
|
||||
* @since 1.3.0
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class SimpleConfigurationMetadataRepository
|
||||
implements ConfigurationMetadataRepository, Serializable {
|
||||
public class SimpleConfigurationMetadataRepository implements ConfigurationMetadataRepository, Serializable {
|
||||
|
||||
private final Map<String, ConfigurationMetadataGroup> allGroups = new HashMap<>();
|
||||
|
||||
@@ -73,8 +72,7 @@ public class SimpleConfigurationMetadataRepository
|
||||
* @param property the property to add
|
||||
* @param source the source
|
||||
*/
|
||||
public void add(ConfigurationMetadataProperty property,
|
||||
ConfigurationMetadataSource source) {
|
||||
public void add(ConfigurationMetadataProperty property, ConfigurationMetadataSource source) {
|
||||
if (source != null) {
|
||||
putIfAbsent(source.getProperties(), property.getId(), property);
|
||||
}
|
||||
@@ -93,11 +91,9 @@ public class SimpleConfigurationMetadataRepository
|
||||
}
|
||||
else {
|
||||
// Merge properties
|
||||
group.getProperties().forEach((name, value) -> putIfAbsent(
|
||||
existingGroup.getProperties(), name, value));
|
||||
group.getProperties().forEach((name, value) -> putIfAbsent(existingGroup.getProperties(), name, value));
|
||||
// Merge sources
|
||||
group.getSources().forEach((name,
|
||||
value) -> putIfAbsent(existingGroup.getSources(), name, value));
|
||||
group.getSources().forEach((name, value) -> putIfAbsent(existingGroup.getSources(), name, value));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -74,8 +74,7 @@ public class ValueHint implements Serializable {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ValueHint{" + "value=" + this.value + ", description='" + this.description
|
||||
+ '\'' + '}';
|
||||
return "ValueHint{" + "value=" + this.value + ", description='" + this.description + '\'' + '}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -59,8 +59,7 @@ public class ValueProvider implements Serializable {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ValueProvider{" + "name='" + this.name + ", parameters=" + this.parameters
|
||||
+ '}';
|
||||
return "ValueProvider{" + "name='" + this.name + ", parameters=" + this.parameters + '}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -31,16 +31,15 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
public abstract class AbstractConfigurationMetadataTests {
|
||||
|
||||
protected void assertSource(ConfigurationMetadataSource actual, String groupId,
|
||||
String type, String sourceType) {
|
||||
protected void assertSource(ConfigurationMetadataSource actual, String groupId, String type, String sourceType) {
|
||||
assertThat(actual).isNotNull();
|
||||
assertThat(actual.getGroupId()).isEqualTo(groupId);
|
||||
assertThat(actual.getType()).isEqualTo(type);
|
||||
assertThat(actual.getSourceType()).isEqualTo(sourceType);
|
||||
}
|
||||
|
||||
protected void assertProperty(ConfigurationMetadataProperty actual, String id,
|
||||
String name, Class<?> type, Object defaultValue) {
|
||||
protected void assertProperty(ConfigurationMetadataProperty actual, String id, String name, Class<?> type,
|
||||
Object defaultValue) {
|
||||
assertThat(actual).isNotNull();
|
||||
assertThat(actual.getId()).isEqualTo(id);
|
||||
assertThat(actual.getName()).isEqualTo(name);
|
||||
@@ -55,8 +54,7 @@ public abstract class AbstractConfigurationMetadataTests {
|
||||
}
|
||||
|
||||
protected InputStream getInputStreamFor(String name) throws IOException {
|
||||
Resource r = new ClassPathResource(
|
||||
"metadata/configuration-metadata-" + name + ".json");
|
||||
Resource r = new ClassPathResource("metadata/configuration-metadata-" + name + ".json");
|
||||
return r.getInputStream();
|
||||
}
|
||||
|
||||
|
||||
@@ -30,25 +30,21 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
extends AbstractConfigurationMetadataTests {
|
||||
public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurationMetadataTests {
|
||||
|
||||
@Test
|
||||
public void nullResource() throws IOException {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create()
|
||||
.withJsonResource(null));
|
||||
.isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void simpleRepository() throws IOException {
|
||||
try (InputStream foo = getInputStreamFor("foo")) {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(foo).build();
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo).build();
|
||||
validateFoo(repo);
|
||||
assertThat(repo.getAllGroups()).hasSize(1);
|
||||
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description",
|
||||
"spring.foo.counter");
|
||||
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter");
|
||||
assertThat(repo.getAllProperties()).hasSize(3);
|
||||
}
|
||||
}
|
||||
@@ -56,63 +52,54 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
@Test
|
||||
public void hintsOnMaps() throws IOException {
|
||||
try (InputStream map = getInputStreamFor("map")) {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(map).build();
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(map).build();
|
||||
validateMap(repo);
|
||||
assertThat(repo.getAllGroups()).hasSize(1);
|
||||
contains(repo.getAllProperties(), "spring.map.first", "spring.map.second",
|
||||
"spring.map.keys", "spring.map.values");
|
||||
contains(repo.getAllProperties(), "spring.map.first", "spring.map.second", "spring.map.keys",
|
||||
"spring.map.values");
|
||||
assertThat(repo.getAllProperties()).hasSize(4);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void severalRepositoriesNoConflict() throws IOException {
|
||||
try (InputStream foo = getInputStreamFor("foo");
|
||||
InputStream bar = getInputStreamFor("bar")) {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(foo, bar).build();
|
||||
try (InputStream foo = getInputStreamFor("foo"); InputStream bar = getInputStreamFor("bar")) {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, bar).build();
|
||||
validateFoo(repo);
|
||||
validateBar(repo);
|
||||
assertThat(repo.getAllGroups()).hasSize(2);
|
||||
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description",
|
||||
"spring.foo.counter", "spring.bar.name", "spring.bar.description",
|
||||
"spring.bar.counter");
|
||||
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter",
|
||||
"spring.bar.name", "spring.bar.description", "spring.bar.counter");
|
||||
assertThat(repo.getAllProperties()).hasSize(6);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void repositoryWithRoot() throws IOException {
|
||||
try (InputStream foo = getInputStreamFor("foo");
|
||||
InputStream root = getInputStreamFor("root")) {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(foo, root).build();
|
||||
try (InputStream foo = getInputStreamFor("foo"); InputStream root = getInputStreamFor("root")) {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, root).build();
|
||||
validateFoo(repo);
|
||||
assertThat(repo.getAllGroups()).hasSize(2);
|
||||
|
||||
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description",
|
||||
"spring.foo.counter", "spring.root.name", "spring.root2.name");
|
||||
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter",
|
||||
"spring.root.name", "spring.root2.name");
|
||||
assertThat(repo.getAllProperties()).hasSize(5);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void severalRepositoriesIdenticalGroups() throws IOException {
|
||||
try (InputStream foo = getInputStreamFor("foo");
|
||||
InputStream foo2 = getInputStreamFor("foo2")) {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(foo, foo2).build();
|
||||
try (InputStream foo = getInputStreamFor("foo"); InputStream foo2 = getInputStreamFor("foo2")) {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, foo2).build();
|
||||
assertThat(repo.getAllGroups()).hasSize(1);
|
||||
ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.foo");
|
||||
contains(group.getSources(), "org.acme.Foo", "org.acme.Foo2",
|
||||
"org.springframework.boot.FooProperties");
|
||||
contains(group.getSources(), "org.acme.Foo", "org.acme.Foo2", "org.springframework.boot.FooProperties");
|
||||
assertThat(group.getSources()).hasSize(3);
|
||||
contains(group.getProperties(), "spring.foo.name", "spring.foo.description",
|
||||
"spring.foo.counter", "spring.foo.enabled", "spring.foo.type");
|
||||
contains(group.getProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter",
|
||||
"spring.foo.enabled", "spring.foo.type");
|
||||
assertThat(group.getProperties()).hasSize(5);
|
||||
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description",
|
||||
"spring.foo.counter", "spring.foo.enabled", "spring.foo.type");
|
||||
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter",
|
||||
"spring.foo.enabled", "spring.foo.type");
|
||||
assertThat(repo.getAllProperties()).hasSize(5);
|
||||
}
|
||||
}
|
||||
@@ -120,8 +107,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
@Test
|
||||
public void emptyGroups() throws IOException {
|
||||
try (InputStream in = getInputStreamFor("empty-groups")) {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(in).build();
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(in).build();
|
||||
validateEmptyGroup(repo);
|
||||
assertThat(repo.getAllGroups()).hasSize(1);
|
||||
contains(repo.getAllProperties(), "name", "title");
|
||||
@@ -132,39 +118,28 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
@Test
|
||||
public void multiGroups() throws IOException {
|
||||
try (InputStream in = getInputStreamFor("multi-groups")) {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(in).build();
|
||||
assertThat(repo.getAllGroups()).containsOnlyKeys("test.group.one.retry",
|
||||
"test.group.two.retry", "test.group.one.retry.specific");
|
||||
ConfigurationMetadataGroup one = repo.getAllGroups()
|
||||
.get("test.group.one.retry");
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(in).build();
|
||||
assertThat(repo.getAllGroups()).containsOnlyKeys("test.group.one.retry", "test.group.two.retry",
|
||||
"test.group.one.retry.specific");
|
||||
ConfigurationMetadataGroup one = repo.getAllGroups().get("test.group.one.retry");
|
||||
assertThat(one.getSources()).containsOnlyKeys("com.example.Retry");
|
||||
assertThat(one.getProperties())
|
||||
.containsOnlyKeys("test.group.one.retry.enabled");
|
||||
ConfigurationMetadataGroup two = repo.getAllGroups()
|
||||
.get("test.group.two.retry");
|
||||
assertThat(one.getProperties()).containsOnlyKeys("test.group.one.retry.enabled");
|
||||
ConfigurationMetadataGroup two = repo.getAllGroups().get("test.group.two.retry");
|
||||
assertThat(two.getSources()).containsOnlyKeys("com.example.Retry");
|
||||
assertThat(two.getProperties())
|
||||
.containsOnlyKeys("test.group.two.retry.enabled");
|
||||
ConfigurationMetadataGroup oneSpecific = repo.getAllGroups()
|
||||
.get("test.group.one.retry.specific");
|
||||
assertThat(two.getProperties()).containsOnlyKeys("test.group.two.retry.enabled");
|
||||
ConfigurationMetadataGroup oneSpecific = repo.getAllGroups().get("test.group.one.retry.specific");
|
||||
assertThat(oneSpecific.getSources()).containsOnlyKeys("com.example.Retry");
|
||||
assertThat(oneSpecific.getProperties())
|
||||
.containsOnlyKeys("test.group.one.retry.specific.enabled");
|
||||
assertThat(oneSpecific.getProperties()).containsOnlyKeys("test.group.one.retry.specific.enabled");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void builderInstancesAreIsolated() throws IOException {
|
||||
try (InputStream foo = getInputStreamFor("foo");
|
||||
InputStream bar = getInputStreamFor("bar")) {
|
||||
ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create();
|
||||
ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo)
|
||||
.build();
|
||||
try (InputStream foo = getInputStreamFor("foo"); InputStream bar = getInputStreamFor("bar")) {
|
||||
ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder.create();
|
||||
ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo).build();
|
||||
validateFoo(firstRepo);
|
||||
ConfigurationMetadataRepository secondRepo = builder.withJsonResource(bar)
|
||||
.build();
|
||||
ConfigurationMetadataRepository secondRepo = builder.withJsonResource(bar).build();
|
||||
validateFoo(secondRepo);
|
||||
validateBar(secondRepo);
|
||||
// first repo not impacted by second build
|
||||
@@ -178,78 +153,63 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
|
||||
private void validateFoo(ConfigurationMetadataRepository repo) {
|
||||
ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.foo");
|
||||
contains(group.getSources(), "org.acme.Foo",
|
||||
"org.springframework.boot.FooProperties");
|
||||
contains(group.getSources(), "org.acme.Foo", "org.springframework.boot.FooProperties");
|
||||
ConfigurationMetadataSource source = group.getSources().get("org.acme.Foo");
|
||||
contains(source.getProperties(), "spring.foo.name", "spring.foo.description");
|
||||
assertThat(source.getProperties()).hasSize(2);
|
||||
ConfigurationMetadataSource source2 = group.getSources()
|
||||
.get("org.springframework.boot.FooProperties");
|
||||
ConfigurationMetadataSource source2 = group.getSources().get("org.springframework.boot.FooProperties");
|
||||
contains(source2.getProperties(), "spring.foo.name", "spring.foo.counter");
|
||||
assertThat(source2.getProperties()).hasSize(2);
|
||||
validatePropertyHints(repo.getAllProperties().get("spring.foo.name"), 0, 0);
|
||||
validatePropertyHints(repo.getAllProperties().get("spring.foo.description"), 0,
|
||||
0);
|
||||
validatePropertyHints(repo.getAllProperties().get("spring.foo.description"), 0, 0);
|
||||
validatePropertyHints(repo.getAllProperties().get("spring.foo.counter"), 1, 1);
|
||||
}
|
||||
|
||||
private void validateBar(ConfigurationMetadataRepository repo) {
|
||||
ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.bar");
|
||||
contains(group.getSources(), "org.acme.Bar",
|
||||
"org.springframework.boot.BarProperties");
|
||||
contains(group.getSources(), "org.acme.Bar", "org.springframework.boot.BarProperties");
|
||||
ConfigurationMetadataSource source = group.getSources().get("org.acme.Bar");
|
||||
contains(source.getProperties(), "spring.bar.name", "spring.bar.description");
|
||||
assertThat(source.getProperties()).hasSize(2);
|
||||
ConfigurationMetadataSource source2 = group.getSources()
|
||||
.get("org.springframework.boot.BarProperties");
|
||||
ConfigurationMetadataSource source2 = group.getSources().get("org.springframework.boot.BarProperties");
|
||||
contains(source2.getProperties(), "spring.bar.name", "spring.bar.counter");
|
||||
assertThat(source2.getProperties()).hasSize(2);
|
||||
validatePropertyHints(repo.getAllProperties().get("spring.bar.name"), 0, 0);
|
||||
validatePropertyHints(repo.getAllProperties().get("spring.bar.description"), 2,
|
||||
2);
|
||||
validatePropertyHints(repo.getAllProperties().get("spring.bar.description"), 2, 2);
|
||||
validatePropertyHints(repo.getAllProperties().get("spring.bar.counter"), 0, 0);
|
||||
}
|
||||
|
||||
private void validateMap(ConfigurationMetadataRepository repo) {
|
||||
ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.map");
|
||||
ConfigurationMetadataSource source = group.getSources().get("org.acme.Map");
|
||||
contains(source.getProperties(), "spring.map.first", "spring.map.second",
|
||||
"spring.map.keys", "spring.map.values");
|
||||
contains(source.getProperties(), "spring.map.first", "spring.map.second", "spring.map.keys",
|
||||
"spring.map.values");
|
||||
assertThat(source.getProperties()).hasSize(4);
|
||||
ConfigurationMetadataProperty first = repo.getAllProperties()
|
||||
.get("spring.map.first");
|
||||
ConfigurationMetadataProperty first = repo.getAllProperties().get("spring.map.first");
|
||||
assertThat(first.getHints().getKeyHints()).hasSize(2);
|
||||
assertThat(first.getHints().getValueProviders()).hasSize(0);
|
||||
assertThat(first.getHints().getKeyHints().get(0).getValue()).isEqualTo("one");
|
||||
assertThat(first.getHints().getKeyHints().get(0).getDescription())
|
||||
.isEqualTo("First.");
|
||||
assertThat(first.getHints().getKeyHints().get(0).getDescription()).isEqualTo("First.");
|
||||
assertThat(first.getHints().getKeyHints().get(1).getValue()).isEqualTo("two");
|
||||
assertThat(first.getHints().getKeyHints().get(1).getDescription())
|
||||
.isEqualTo("Second.");
|
||||
ConfigurationMetadataProperty second = repo.getAllProperties()
|
||||
.get("spring.map.second");
|
||||
assertThat(first.getHints().getKeyHints().get(1).getDescription()).isEqualTo("Second.");
|
||||
ConfigurationMetadataProperty second = repo.getAllProperties().get("spring.map.second");
|
||||
assertThat(second.getHints().getValueHints()).hasSize(2);
|
||||
assertThat(second.getHints().getValueProviders()).hasSize(0);
|
||||
assertThat(second.getHints().getValueHints().get(0).getValue()).isEqualTo("42");
|
||||
assertThat(second.getHints().getValueHints().get(0).getDescription())
|
||||
.isEqualTo("Choose me.");
|
||||
assertThat(second.getHints().getValueHints().get(0).getDescription()).isEqualTo("Choose me.");
|
||||
assertThat(second.getHints().getValueHints().get(1).getValue()).isEqualTo("24");
|
||||
assertThat(second.getHints().getValueHints().get(1).getDescription()).isNull();
|
||||
ConfigurationMetadataProperty keys = repo.getAllProperties()
|
||||
.get("spring.map.keys");
|
||||
ConfigurationMetadataProperty keys = repo.getAllProperties().get("spring.map.keys");
|
||||
assertThat(keys.getHints().getValueHints()).hasSize(0);
|
||||
assertThat(keys.getHints().getValueProviders()).hasSize(1);
|
||||
assertThat(keys.getHints().getValueProviders().get(0).getName()).isEqualTo("any");
|
||||
ConfigurationMetadataProperty values = repo.getAllProperties()
|
||||
.get("spring.map.values");
|
||||
ConfigurationMetadataProperty values = repo.getAllProperties().get("spring.map.values");
|
||||
assertThat(values.getHints().getValueHints()).hasSize(0);
|
||||
assertThat(values.getHints().getValueProviders()).hasSize(1);
|
||||
assertThat(values.getHints().getValueProviders().get(0).getName())
|
||||
.isEqualTo("handle-as");
|
||||
assertThat(values.getHints().getValueProviders().get(0).getParameters())
|
||||
.hasSize(1);
|
||||
assertThat(values.getHints().getValueProviders().get(0).getParameters()
|
||||
.get("target")).isEqualTo("java.lang.Integer");
|
||||
assertThat(values.getHints().getValueProviders().get(0).getName()).isEqualTo("handle-as");
|
||||
assertThat(values.getHints().getValueProviders().get(0).getParameters()).hasSize(1);
|
||||
assertThat(values.getHints().getValueProviders().get(0).getParameters().get("target"))
|
||||
.isEqualTo("java.lang.Integer");
|
||||
}
|
||||
|
||||
private void validateEmptyGroup(ConfigurationMetadataRepository repo) {
|
||||
@@ -265,11 +225,9 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
validatePropertyHints(repo.getAllProperties().get("title"), 0, 0);
|
||||
}
|
||||
|
||||
private void validatePropertyHints(ConfigurationMetadataProperty property,
|
||||
int valueHints, int valueProviders) {
|
||||
private void validatePropertyHints(ConfigurationMetadataProperty property, int valueHints, int valueProviders) {
|
||||
assertThat(property.getHints().getValueHints().size()).isEqualTo(valueHints);
|
||||
assertThat(property.getHints().getValueProviders().size())
|
||||
.isEqualTo(valueProviders);
|
||||
assertThat(property.getHints().getValueProviders().size()).isEqualTo(valueProviders);
|
||||
}
|
||||
|
||||
private void contains(Map<String, ?> source, String... keys) {
|
||||
|
||||
@@ -47,8 +47,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
|
||||
|
||||
@Test
|
||||
public void invalidMetadata() throws IOException {
|
||||
assertThatIllegalStateException().isThrownBy(() -> readFor("invalid"))
|
||||
.withCauseInstanceOf(JSONException.class);
|
||||
assertThatIllegalStateException().isThrownBy(() -> readFor("invalid")).withCauseInstanceOf(JSONException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -83,8 +82,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
|
||||
assertProperty(item, "spring.foo.name", "name", String.class, null);
|
||||
assertItem(item, "org.acme.Foo");
|
||||
ConfigurationMetadataItem item2 = items.get(1);
|
||||
assertProperty(item2, "spring.foo.description", "description", String.class,
|
||||
"FooBar");
|
||||
assertProperty(item2, "spring.foo.description", "description", String.class, "FooBar");
|
||||
assertThat(item2.getDescription()).isEqualTo("Foo description.");
|
||||
assertThat(item2.getShortDescription()).isEqualTo("Foo description.");
|
||||
assertThat(item2.getSourceMethod()).isNull();
|
||||
@@ -95,16 +93,14 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
|
||||
assertThat(hint.getValueHints()).hasSize(1);
|
||||
ValueHint valueHint = hint.getValueHints().get(0);
|
||||
assertThat(valueHint.getValue()).isEqualTo(42);
|
||||
assertThat(valueHint.getDescription()).isEqualTo(
|
||||
"Because that's the answer to any question, choose it. \nReally.");
|
||||
assertThat(valueHint.getShortDescription())
|
||||
.isEqualTo("Because that's the answer to any question, choose it.");
|
||||
assertThat(valueHint.getDescription())
|
||||
.isEqualTo("Because that's the answer to any question, choose it. \nReally.");
|
||||
assertThat(valueHint.getShortDescription()).isEqualTo("Because that's the answer to any question, choose it.");
|
||||
assertThat(hint.getValueProviders()).hasSize(1);
|
||||
ValueProvider valueProvider = hint.getValueProviders().get(0);
|
||||
assertThat(valueProvider.getName()).isEqualTo("handle-as");
|
||||
assertThat(valueProvider.getParameters()).hasSize(1);
|
||||
assertThat(valueProvider.getParameters().get("target"))
|
||||
.isEqualTo(Integer.class.getName());
|
||||
assertThat(valueProvider.getParameters().get("target")).isEqualTo(Integer.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -127,8 +123,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
|
||||
ValueProvider valueProvider = hint.getValueProviders().get(0);
|
||||
assertThat(valueProvider.getName()).isEqualTo("handle-as");
|
||||
assertThat(valueProvider.getParameters()).hasSize(1);
|
||||
assertThat(valueProvider.getParameters().get("target"))
|
||||
.isEqualTo(String.class.getName());
|
||||
assertThat(valueProvider.getParameters().get("target")).isEqualTo(String.class.getName());
|
||||
ValueProvider valueProvider2 = hint.getValueProviders().get(1);
|
||||
assertThat(valueProvider2.getName()).isEqualTo("any");
|
||||
assertThat(valueProvider2.getParameters()).isEmpty();
|
||||
@@ -154,17 +149,13 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
|
||||
ConfigurationMetadataItem item = items.get(0);
|
||||
assertProperty(item, "server.port", "server.port", Integer.class, null);
|
||||
assertThat(item.isDeprecated()).isTrue();
|
||||
assertThat(item.getDeprecation().getReason())
|
||||
.isEqualTo("Server namespace has moved to spring.server");
|
||||
assertThat(item.getDeprecation().getShortReason())
|
||||
.isEqualTo("Server namespace has moved to spring.server");
|
||||
assertThat(item.getDeprecation().getReplacement())
|
||||
.isEqualTo("server.spring.port");
|
||||
assertThat(item.getDeprecation().getReason()).isEqualTo("Server namespace has moved to spring.server");
|
||||
assertThat(item.getDeprecation().getShortReason()).isEqualTo("Server namespace has moved to spring.server");
|
||||
assertThat(item.getDeprecation().getReplacement()).isEqualTo("server.spring.port");
|
||||
assertThat(item.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.WARNING);
|
||||
|
||||
ConfigurationMetadataItem item2 = items.get(1);
|
||||
assertProperty(item2, "server.cluster-name", "server.cluster-name", String.class,
|
||||
null);
|
||||
assertProperty(item2, "server.cluster-name", "server.cluster-name", String.class, null);
|
||||
assertThat(item2.isDeprecated()).isTrue();
|
||||
assertThat(item2.getDeprecation().getReason()).isNull();
|
||||
assertThat(item2.getDeprecation().getShortReason()).isNull();
|
||||
@@ -172,31 +163,25 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
|
||||
assertThat(item.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.WARNING);
|
||||
|
||||
ConfigurationMetadataItem item3 = items.get(2);
|
||||
assertProperty(item3, "spring.server.name", "spring.server.name", String.class,
|
||||
null);
|
||||
assertProperty(item3, "spring.server.name", "spring.server.name", String.class, null);
|
||||
assertThat(item3.isDeprecated()).isFalse();
|
||||
assertThat(item3.getDeprecation()).isNull();
|
||||
|
||||
ConfigurationMetadataItem item4 = items.get(3);
|
||||
assertProperty(item4, "spring.server-name", "spring.server-name", String.class,
|
||||
null);
|
||||
assertProperty(item4, "spring.server-name", "spring.server-name", String.class, null);
|
||||
assertThat(item4.isDeprecated()).isTrue();
|
||||
assertThat(item4.getDeprecation().getReason()).isNull();
|
||||
assertThat(item2.getDeprecation().getShortReason()).isNull();
|
||||
assertThat(item4.getDeprecation().getReplacement())
|
||||
.isEqualTo("spring.server.name");
|
||||
assertThat(item4.getDeprecation().getReplacement()).isEqualTo("spring.server.name");
|
||||
assertThat(item4.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.ERROR);
|
||||
|
||||
ConfigurationMetadataItem item5 = items.get(4);
|
||||
assertProperty(item5, "spring.server-name2", "spring.server-name2", String.class,
|
||||
null);
|
||||
assertProperty(item5, "spring.server-name2", "spring.server-name2", String.class, null);
|
||||
assertThat(item5.isDeprecated()).isTrue();
|
||||
assertThat(item5.getDeprecation().getReason()).isNull();
|
||||
assertThat(item2.getDeprecation().getShortReason()).isNull();
|
||||
assertThat(item5.getDeprecation().getReplacement())
|
||||
.isEqualTo("spring.server.name");
|
||||
assertThat(item5.getDeprecation().getLevel())
|
||||
.isEqualTo(Deprecation.Level.WARNING);
|
||||
assertThat(item5.getDeprecation().getReplacement()).isEqualTo("spring.server.name");
|
||||
assertThat(item5.getDeprecation().getLevel()).isEqualTo(Deprecation.Level.WARNING);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -33,22 +33,21 @@ public class SentenceExtractorTests {
|
||||
|
||||
@Test
|
||||
public void extractFirstSentence() {
|
||||
String sentence = this.extractor
|
||||
.getFirstSentence("My short " + "description. More stuff.");
|
||||
String sentence = this.extractor.getFirstSentence("My short " + "description. More stuff.");
|
||||
assertThat(sentence).isEqualTo("My short description.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractFirstSentenceNewLineBeforeDot() {
|
||||
String sentence = this.extractor.getFirstSentence(
|
||||
"My short" + NEW_LINE + "description." + NEW_LINE + "More stuff.");
|
||||
String sentence = this.extractor
|
||||
.getFirstSentence("My short" + NEW_LINE + "description." + NEW_LINE + "More stuff.");
|
||||
assertThat(sentence).isEqualTo("My short description.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractFirstSentenceNewLineBeforeDotWithSpaces() {
|
||||
String sentence = this.extractor.getFirstSentence(
|
||||
"My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff.");
|
||||
String sentence = this.extractor
|
||||
.getFirstSentence("My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff.");
|
||||
assertThat(sentence).isEqualTo("My short description.");
|
||||
}
|
||||
|
||||
@@ -60,8 +59,7 @@ public class SentenceExtractorTests {
|
||||
|
||||
@Test
|
||||
public void extractFirstSentenceNoDotMultipleLines() {
|
||||
String sentence = this.extractor
|
||||
.getFirstSentence("My short description " + NEW_LINE + " More stuff");
|
||||
String sentence = this.extractor.getFirstSentence("My short description " + NEW_LINE + " More stuff");
|
||||
assertThat(sentence).isEqualTo("My short description");
|
||||
}
|
||||
|
||||
|
||||
@@ -79,8 +79,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
static final String DEPRECATED_CONFIGURATION_PROPERTY_ANNOTATION = "org.springframework.boot."
|
||||
+ "context.properties.DeprecatedConfigurationProperty";
|
||||
|
||||
static final String ENDPOINT_ANNOTATION = "org.springframework.boot.actuate."
|
||||
+ "endpoint.annotation.Endpoint";
|
||||
static final String ENDPOINT_ANNOTATION = "org.springframework.boot.actuate." + "endpoint.annotation.Endpoint";
|
||||
|
||||
static final String READ_OPERATION_ANNOTATION = "org.springframework.boot.actuate."
|
||||
+ "endpoint.annotation.ReadOperation";
|
||||
@@ -143,25 +142,21 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
super.init(env);
|
||||
this.typeUtils = new TypeUtils(env);
|
||||
this.metadataStore = new MetadataStore(env);
|
||||
this.metadataCollector = new MetadataCollector(env,
|
||||
this.metadataStore.readMetadata());
|
||||
this.metadataCollector = new MetadataCollector(env, this.metadataStore.readMetadata());
|
||||
try {
|
||||
this.fieldValuesParser = new JavaCompilerFieldValuesParser(env);
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
this.fieldValuesParser = FieldValuesParser.NONE;
|
||||
logWarning("Field value processing of @ConfigurationProperty meta-data is "
|
||||
+ "not supported");
|
||||
logWarning("Field value processing of @ConfigurationProperty meta-data is " + "not supported");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean process(Set<? extends TypeElement> annotations,
|
||||
RoundEnvironment roundEnv) {
|
||||
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
|
||||
this.metadataCollector.processing(roundEnv);
|
||||
Elements elementUtils = this.processingEnv.getElementUtils();
|
||||
TypeElement annotationType = elementUtils
|
||||
.getTypeElement(configurationPropertiesAnnotation());
|
||||
TypeElement annotationType = elementUtils.getTypeElement(configurationPropertiesAnnotation());
|
||||
if (annotationType != null) { // Is @ConfigurationProperties available
|
||||
for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) {
|
||||
processElement(element);
|
||||
@@ -169,8 +164,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
}
|
||||
TypeElement endpointType = elementUtils.getTypeElement(endpointAnnotation());
|
||||
if (endpointType != null) { // Is @Endpoint available
|
||||
getElementsAnnotatedOrMetaAnnotatedWith(roundEnv, endpointType)
|
||||
.forEach(this::processEndpoint);
|
||||
getElementsAnnotatedOrMetaAnnotatedWith(roundEnv, endpointType).forEach(this::processEndpoint);
|
||||
}
|
||||
if (roundEnv.processingOver()) {
|
||||
try {
|
||||
@@ -183,8 +177,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
return false;
|
||||
}
|
||||
|
||||
private Map<Element, List<Element>> getElementsAnnotatedOrMetaAnnotatedWith(
|
||||
RoundEnvironment roundEnv, TypeElement annotation) {
|
||||
private Map<Element, List<Element>> getElementsAnnotatedOrMetaAnnotatedWith(RoundEnvironment roundEnv,
|
||||
TypeElement annotation) {
|
||||
DeclaredType annotationType = (DeclaredType) annotation.asType();
|
||||
Map<Element, List<Element>> result = new LinkedHashMap<>();
|
||||
for (Element element : roundEnv.getRootElements()) {
|
||||
@@ -199,11 +193,10 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean collectElementsAnnotatedOrMetaAnnotatedWith(
|
||||
DeclaredType annotationType, LinkedList<Element> stack) {
|
||||
private boolean collectElementsAnnotatedOrMetaAnnotatedWith(DeclaredType annotationType,
|
||||
LinkedList<Element> stack) {
|
||||
Element element = stack.peekLast();
|
||||
for (AnnotationMirror annotation : this.processingEnv.getElementUtils()
|
||||
.getAllAnnotationMirrors(element)) {
|
||||
for (AnnotationMirror annotation : this.processingEnv.getElementUtils().getAllAnnotationMirrors(element)) {
|
||||
Element annotationElement = annotation.getAnnotationType().asElement();
|
||||
if (!stack.contains(annotationElement)) {
|
||||
stack.addLast(annotationElement);
|
||||
@@ -220,8 +213,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
|
||||
private void processElement(Element element) {
|
||||
try {
|
||||
AnnotationMirror annotation = getAnnotation(element,
|
||||
configurationPropertiesAnnotation());
|
||||
AnnotationMirror annotation = getAnnotation(element, configurationPropertiesAnnotation());
|
||||
if (annotation != null) {
|
||||
String prefix = getPrefix(annotation);
|
||||
if (element instanceof TypeElement) {
|
||||
@@ -233,8 +225,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
}
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(
|
||||
"Error processing configuration meta-data on " + element, ex);
|
||||
throw new IllegalStateException("Error processing configuration meta-data on " + element, ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,20 +236,14 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
}
|
||||
|
||||
private void processExecutableElement(String prefix, ExecutableElement element) {
|
||||
if (element.getModifiers().contains(Modifier.PUBLIC)
|
||||
&& (TypeKind.VOID != element.getReturnType().getKind())) {
|
||||
Element returns = this.processingEnv.getTypeUtils()
|
||||
.asElement(element.getReturnType());
|
||||
if (element.getModifiers().contains(Modifier.PUBLIC) && (TypeKind.VOID != element.getReturnType().getKind())) {
|
||||
Element returns = this.processingEnv.getTypeUtils().asElement(element.getReturnType());
|
||||
if (returns instanceof TypeElement) {
|
||||
ItemMetadata group = ItemMetadata.newGroup(prefix,
|
||||
this.typeUtils.getQualifiedName(returns),
|
||||
this.typeUtils.getQualifiedName(element.getEnclosingElement()),
|
||||
element.toString());
|
||||
ItemMetadata group = ItemMetadata.newGroup(prefix, this.typeUtils.getQualifiedName(returns),
|
||||
this.typeUtils.getQualifiedName(element.getEnclosingElement()), element.toString());
|
||||
if (this.metadataCollector.hasSimilarGroup(group)) {
|
||||
this.processingEnv.getMessager().printMessage(Kind.ERROR,
|
||||
"Duplicate `@ConfigurationProperties` definition for prefix '"
|
||||
+ prefix + "'",
|
||||
element);
|
||||
"Duplicate `@ConfigurationProperties` definition for prefix '" + prefix + "'", element);
|
||||
}
|
||||
else {
|
||||
this.metadataCollector.add(group);
|
||||
@@ -268,10 +253,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
}
|
||||
}
|
||||
|
||||
private void processTypeElement(String prefix, TypeElement element,
|
||||
ExecutableElement source) {
|
||||
TypeElementMembers members = new TypeElementMembers(this.processingEnv,
|
||||
this.fieldValuesParser, element);
|
||||
private void processTypeElement(String prefix, TypeElement element, ExecutableElement source) {
|
||||
TypeElementMembers members = new TypeElementMembers(this.processingEnv, this.fieldValuesParser, element);
|
||||
Map<String, Object> fieldValues = members.getFieldValues();
|
||||
processSimpleTypes(prefix, element, source, members, fieldValues);
|
||||
processSimpleLombokTypes(prefix, element, source, members, fieldValues);
|
||||
@@ -279,15 +262,13 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
processNestedLombokTypes(prefix, element, source, members);
|
||||
}
|
||||
|
||||
private void processSimpleTypes(String prefix, TypeElement element,
|
||||
ExecutableElement source, TypeElementMembers members,
|
||||
Map<String, Object> fieldValues) {
|
||||
private void processSimpleTypes(String prefix, TypeElement element, ExecutableElement source,
|
||||
TypeElementMembers members, Map<String, Object> fieldValues) {
|
||||
members.getPublicGetters().forEach((name, getter) -> {
|
||||
TypeMirror returnType = getter.getReturnType();
|
||||
ExecutableElement setter = members.getPublicSetter(name, returnType);
|
||||
VariableElement field = members.getFields().get(name);
|
||||
Element returnTypeElement = this.processingEnv.getTypeUtils()
|
||||
.asElement(returnType);
|
||||
Element returnTypeElement = this.processingEnv.getTypeUtils().asElement(returnType);
|
||||
boolean isExcluded = this.typeExcludeFilter.isExcluded(returnType);
|
||||
boolean isNested = isNested(returnTypeElement, field, element);
|
||||
boolean isCollection = this.typeUtils.isCollectionOrMap(returnType);
|
||||
@@ -296,18 +277,15 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
String sourceType = this.typeUtils.getQualifiedName(element);
|
||||
String description = this.typeUtils.getJavaDoc(field);
|
||||
Object defaultValue = fieldValues.get(name);
|
||||
boolean deprecated = isDeprecated(getter) || isDeprecated(setter)
|
||||
|| isDeprecated(source);
|
||||
this.metadataCollector.add(ItemMetadata.newProperty(prefix, name,
|
||||
dataType, sourceType, null, description, defaultValue,
|
||||
deprecated ? getItemDeprecation(getter) : null));
|
||||
boolean deprecated = isDeprecated(getter) || isDeprecated(setter) || isDeprecated(source);
|
||||
this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, dataType, sourceType, null,
|
||||
description, defaultValue, deprecated ? getItemDeprecation(getter) : null));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ItemDeprecation getItemDeprecation(ExecutableElement getter) {
|
||||
AnnotationMirror annotation = getAnnotation(getter,
|
||||
deprecatedConfigurationPropertyAnnotation());
|
||||
AnnotationMirror annotation = getAnnotation(getter, deprecatedConfigurationPropertyAnnotation());
|
||||
String reason = null;
|
||||
String replacement = null;
|
||||
if (annotation != null) {
|
||||
@@ -320,16 +298,14 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
return new ItemDeprecation(reason, replacement);
|
||||
}
|
||||
|
||||
private void processSimpleLombokTypes(String prefix, TypeElement element,
|
||||
ExecutableElement source, TypeElementMembers members,
|
||||
Map<String, Object> fieldValues) {
|
||||
private void processSimpleLombokTypes(String prefix, TypeElement element, ExecutableElement source,
|
||||
TypeElementMembers members, Map<String, Object> fieldValues) {
|
||||
members.getFields().forEach((name, field) -> {
|
||||
if (!isLombokField(field, element)) {
|
||||
return;
|
||||
}
|
||||
TypeMirror returnType = field.asType();
|
||||
Element returnTypeElement = this.processingEnv.getTypeUtils()
|
||||
.asElement(returnType);
|
||||
Element returnTypeElement = this.processingEnv.getTypeUtils().asElement(returnType);
|
||||
boolean isExcluded = this.typeExcludeFilter.isExcluded(returnType);
|
||||
boolean isNested = isNested(returnTypeElement, field, element);
|
||||
boolean isCollection = this.typeUtils.isCollectionOrMap(returnType);
|
||||
@@ -340,29 +316,26 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
String description = this.typeUtils.getJavaDoc(field);
|
||||
Object defaultValue = fieldValues.get(name);
|
||||
boolean deprecated = isDeprecated(field) || isDeprecated(source);
|
||||
this.metadataCollector.add(ItemMetadata.newProperty(prefix, name,
|
||||
dataType, sourceType, null, description, defaultValue,
|
||||
deprecated ? new ItemDeprecation() : null));
|
||||
this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, dataType, sourceType, null,
|
||||
description, defaultValue, deprecated ? new ItemDeprecation() : null));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void processNestedTypes(String prefix, TypeElement element,
|
||||
ExecutableElement source, TypeElementMembers members) {
|
||||
private void processNestedTypes(String prefix, TypeElement element, ExecutableElement source,
|
||||
TypeElementMembers members) {
|
||||
members.getPublicGetters().forEach((name, getter) -> {
|
||||
VariableElement field = members.getFields().get(name);
|
||||
processNestedType(prefix, element, source, name, getter, field,
|
||||
getter.getReturnType());
|
||||
processNestedType(prefix, element, source, name, getter, field, getter.getReturnType());
|
||||
});
|
||||
}
|
||||
|
||||
private void processNestedLombokTypes(String prefix, TypeElement element,
|
||||
ExecutableElement source, TypeElementMembers members) {
|
||||
private void processNestedLombokTypes(String prefix, TypeElement element, ExecutableElement source,
|
||||
TypeElementMembers members) {
|
||||
members.getFields().forEach((name, field) -> {
|
||||
if (isLombokField(field, element)) {
|
||||
ExecutableElement getter = members.getPublicGetter(name, field.asType());
|
||||
processNestedType(prefix, element, source, name, getter, field,
|
||||
field.asType());
|
||||
processNestedType(prefix, element, source, name, getter, field, field.asType());
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -372,8 +345,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
}
|
||||
|
||||
private boolean hasLombokSetter(VariableElement field, TypeElement element) {
|
||||
return !field.getModifiers().contains(Modifier.FINAL)
|
||||
&& hasLombokPublicAccessor(field, element, false);
|
||||
return !field.getModifiers().contains(Modifier.FINAL) && hasLombokPublicAccessor(field, element, false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -385,16 +357,13 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
* write accessor
|
||||
* @return {@code true} if this field has a public accessor of the specified type
|
||||
*/
|
||||
private boolean hasLombokPublicAccessor(VariableElement field, TypeElement element,
|
||||
boolean getter) {
|
||||
String annotation = (getter ? LOMBOK_GETTER_ANNOTATION
|
||||
: LOMBOK_SETTER_ANNOTATION);
|
||||
private boolean hasLombokPublicAccessor(VariableElement field, TypeElement element, boolean getter) {
|
||||
String annotation = (getter ? LOMBOK_GETTER_ANNOTATION : LOMBOK_SETTER_ANNOTATION);
|
||||
AnnotationMirror lombokMethodAnnotationOnField = getAnnotation(field, annotation);
|
||||
if (lombokMethodAnnotationOnField != null) {
|
||||
return isAccessLevelPublic(lombokMethodAnnotationOnField);
|
||||
}
|
||||
AnnotationMirror lombokMethodAnnotationOnElement = getAnnotation(element,
|
||||
annotation);
|
||||
AnnotationMirror lombokMethodAnnotationOnElement = getAnnotation(element, annotation);
|
||||
if (lombokMethodAnnotationOnElement != null) {
|
||||
return isAccessLevelPublic(lombokMethodAnnotationOnElement);
|
||||
}
|
||||
@@ -407,19 +376,16 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
return (value == null || value.toString().equals(LOMBOK_ACCESS_LEVEL_PUBLIC));
|
||||
}
|
||||
|
||||
private void processNestedType(String prefix, TypeElement element,
|
||||
ExecutableElement source, String name, ExecutableElement getter,
|
||||
VariableElement field, TypeMirror returnType) {
|
||||
private void processNestedType(String prefix, TypeElement element, ExecutableElement source, String name,
|
||||
ExecutableElement getter, VariableElement field, TypeMirror returnType) {
|
||||
Element returnElement = this.processingEnv.getTypeUtils().asElement(returnType);
|
||||
boolean isNested = isNested(returnElement, field, element);
|
||||
AnnotationMirror annotation = getAnnotation(getter,
|
||||
configurationPropertiesAnnotation());
|
||||
AnnotationMirror annotation = getAnnotation(getter, configurationPropertiesAnnotation());
|
||||
if (returnElement instanceof TypeElement && annotation == null && isNested) {
|
||||
String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, name);
|
||||
this.metadataCollector.add(ItemMetadata.newGroup(nestedPrefix,
|
||||
this.typeUtils.getQualifiedName(returnElement),
|
||||
this.typeUtils.getQualifiedName(element),
|
||||
(getter != null) ? getter.toString() : null));
|
||||
this.metadataCollector
|
||||
.add(ItemMetadata.newGroup(nestedPrefix, this.typeUtils.getQualifiedName(returnElement),
|
||||
this.typeUtils.getQualifiedName(element), (getter != null) ? getter.toString() : null));
|
||||
processTypeElement(nestedPrefix, (TypeElement) returnElement, source);
|
||||
}
|
||||
}
|
||||
@@ -433,8 +399,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
}
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(
|
||||
"Error processing configuration meta-data on " + element, ex);
|
||||
throw new IllegalStateException("Error processing configuration meta-data on " + element, ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,27 +409,22 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
if (endpointId == null || "".equals(endpointId)) {
|
||||
return; // Can't process that endpoint
|
||||
}
|
||||
String endpointKey = ItemMetadata.newItemMetadataPrefix("management.endpoint.",
|
||||
endpointId);
|
||||
String endpointKey = ItemMetadata.newItemMetadataPrefix("management.endpoint.", endpointId);
|
||||
Boolean enabledByDefault = (Boolean) elementValues.get("enableByDefault");
|
||||
String type = this.typeUtils.getQualifiedName(element);
|
||||
this.metadataCollector.add(ItemMetadata.newGroup(endpointKey, type, type, null));
|
||||
this.metadataCollector.add(ItemMetadata.newProperty(endpointKey, "enabled",
|
||||
Boolean.class.getName(), type, null,
|
||||
this.metadataCollector.add(ItemMetadata.newProperty(endpointKey, "enabled", Boolean.class.getName(), type, null,
|
||||
String.format("Whether to enable the %s endpoint.", endpointId),
|
||||
(enabledByDefault != null) ? enabledByDefault : true, null));
|
||||
if (hasMainReadOperation(element)) {
|
||||
this.metadataCollector.add(ItemMetadata.newProperty(endpointKey,
|
||||
"cache.time-to-live", Duration.class.getName(), type, null,
|
||||
"Maximum time that a response can be cached.", "0ms", null));
|
||||
this.metadataCollector.add(ItemMetadata.newProperty(endpointKey, "cache.time-to-live",
|
||||
Duration.class.getName(), type, null, "Maximum time that a response can be cached.", "0ms", null));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasMainReadOperation(TypeElement element) {
|
||||
for (ExecutableElement method : ElementFilter
|
||||
.methodsIn(element.getEnclosedElements())) {
|
||||
if (hasAnnotation(method, readOperationAnnotation())
|
||||
&& (TypeKind.VOID != method.getReturnType().getKind())
|
||||
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
|
||||
if (hasAnnotation(method, readOperationAnnotation()) && (TypeKind.VOID != method.getReturnType().getKind())
|
||||
&& hasNoOrOptionalParameters(method)) {
|
||||
return true;
|
||||
}
|
||||
@@ -481,16 +441,14 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isNested(Element returnType, VariableElement field,
|
||||
TypeElement element) {
|
||||
private boolean isNested(Element returnType, VariableElement field, TypeElement element) {
|
||||
if (hasAnnotation(field, nestedConfigurationPropertyAnnotation())) {
|
||||
return true;
|
||||
}
|
||||
if (isCyclePresent(returnType, element)) {
|
||||
return false;
|
||||
}
|
||||
return (isParentTheSame(returnType, element))
|
||||
&& returnType.getKind() != ElementKind.ENUM;
|
||||
return (isParentTheSame(returnType, element)) && returnType.getKind() != ElementKind.ENUM;
|
||||
}
|
||||
|
||||
private boolean isCyclePresent(Element returnType, Element element) {
|
||||
@@ -562,8 +520,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
|
||||
private Map<String, Object> getAnnotationElementValues(AnnotationMirror annotation) {
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
annotation.getElementValues().forEach((name, value) -> values
|
||||
.put(name.getSimpleName().toString(), value.getValue()));
|
||||
annotation.getElementValues()
|
||||
.forEach((name, value) -> values.put(name.getSimpleName().toString(), value.getValue()));
|
||||
return values;
|
||||
}
|
||||
|
||||
@@ -577,8 +535,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
return null;
|
||||
}
|
||||
|
||||
private ConfigurationMetadata mergeAdditionalMetadata(
|
||||
ConfigurationMetadata metadata) {
|
||||
private ConfigurationMetadata mergeAdditionalMetadata(ConfigurationMetadata metadata) {
|
||||
try {
|
||||
ConfigurationMetadata merged = new ConfigurationMetadata(metadata);
|
||||
merged.merge(this.metadataStore.readAdditionalMetadata());
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -54,8 +54,7 @@ public class MetadataCollector {
|
||||
* @param processingEnvironment the processing environment of the build
|
||||
* @param previousMetadata any previous metadata or {@code null}
|
||||
*/
|
||||
public MetadataCollector(ProcessingEnvironment processingEnvironment,
|
||||
ConfigurationMetadata previousMetadata) {
|
||||
public MetadataCollector(ProcessingEnvironment processingEnvironment, ConfigurationMetadata previousMetadata) {
|
||||
this.processingEnvironment = processingEnvironment;
|
||||
this.previousMetadata = previousMetadata;
|
||||
this.typeUtils = new TypeUtils(processingEnvironment);
|
||||
@@ -82,8 +81,7 @@ public class MetadataCollector {
|
||||
throw new IllegalStateException("item " + metadata + " must be a group");
|
||||
}
|
||||
for (ItemMetadata existing : this.metadataItems) {
|
||||
if (existing.isOfItemType(ItemMetadata.ItemType.GROUP)
|
||||
&& existing.getName().equals(metadata.getName())
|
||||
if (existing.isOfItemType(ItemMetadata.ItemType.GROUP) && existing.getName().equals(metadata.getName())
|
||||
&& existing.getType().equals(metadata.getType())) {
|
||||
return true;
|
||||
}
|
||||
@@ -109,13 +107,11 @@ public class MetadataCollector {
|
||||
|
||||
private boolean shouldBeMerged(ItemMetadata itemMetadata) {
|
||||
String sourceType = itemMetadata.getSourceType();
|
||||
return (sourceType != null && !deletedInCurrentBuild(sourceType)
|
||||
&& !processedInCurrentBuild(sourceType));
|
||||
return (sourceType != null && !deletedInCurrentBuild(sourceType) && !processedInCurrentBuild(sourceType));
|
||||
}
|
||||
|
||||
private boolean deletedInCurrentBuild(String sourceType) {
|
||||
return this.processingEnvironment.getElementUtils()
|
||||
.getTypeElement(sourceType) == null;
|
||||
return this.processingEnvironment.getElementUtils().getTypeElement(sourceType) == null;
|
||||
}
|
||||
|
||||
private boolean processedInCurrentBuild(String sourceType) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -65,8 +65,7 @@ public class MetadataStore {
|
||||
|
||||
public void writeMetadata(ConfigurationMetadata metadata) throws IOException {
|
||||
if (!metadata.getItems().isEmpty()) {
|
||||
try (OutputStream outputStream = createMetadataResource()
|
||||
.openOutputStream()) {
|
||||
try (OutputStream outputStream = createMetadataResource().openOutputStream()) {
|
||||
new JsonMarshaller().write(metadata, outputStream);
|
||||
}
|
||||
}
|
||||
@@ -85,8 +84,7 @@ public class MetadataStore {
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new InvalidConfigurationMetadataException(
|
||||
"Invalid additional meta-data in '" + METADATA_PATH + "': "
|
||||
+ ex.getMessage(),
|
||||
"Invalid additional meta-data in '" + METADATA_PATH + "': " + ex.getMessage(),
|
||||
Diagnostic.Kind.ERROR);
|
||||
}
|
||||
finally {
|
||||
@@ -95,30 +93,27 @@ public class MetadataStore {
|
||||
}
|
||||
|
||||
private FileObject getMetadataResource() throws IOException {
|
||||
return this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "",
|
||||
METADATA_PATH);
|
||||
return this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH);
|
||||
}
|
||||
|
||||
private FileObject createMetadataResource() throws IOException {
|
||||
return this.environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT,
|
||||
"", METADATA_PATH);
|
||||
return this.environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH);
|
||||
}
|
||||
|
||||
private InputStream getAdditionalMetadataStream() throws IOException {
|
||||
// Most build systems will have copied the file to the class output location
|
||||
FileObject fileObject = this.environment.getFiler()
|
||||
.getResource(StandardLocation.CLASS_OUTPUT, "", ADDITIONAL_METADATA_PATH);
|
||||
FileObject fileObject = this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "",
|
||||
ADDITIONAL_METADATA_PATH);
|
||||
File file = locateAdditionalMetadataFile(new File(fileObject.toUri()));
|
||||
return (file.exists() ? new FileInputStream(file)
|
||||
: fileObject.toUri().toURL().openStream());
|
||||
return (file.exists() ? new FileInputStream(file) : fileObject.toUri().toURL().openStream());
|
||||
}
|
||||
|
||||
File locateAdditionalMetadataFile(File standardLocation) throws IOException {
|
||||
if (standardLocation.exists()) {
|
||||
return standardLocation;
|
||||
}
|
||||
String locations = this.environment.getOptions().get(
|
||||
ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION);
|
||||
String locations = this.environment.getOptions()
|
||||
.get(ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION);
|
||||
if (locations != null) {
|
||||
for (String location : locations.split(",")) {
|
||||
File candidate = new File(location, ADDITIONAL_METADATA_PATH);
|
||||
@@ -127,22 +122,18 @@ public class MetadataStore {
|
||||
}
|
||||
}
|
||||
}
|
||||
return new File(locateGradleResourcesFolder(standardLocation),
|
||||
ADDITIONAL_METADATA_PATH);
|
||||
return new File(locateGradleResourcesFolder(standardLocation), ADDITIONAL_METADATA_PATH);
|
||||
}
|
||||
|
||||
private File locateGradleResourcesFolder(File standardAdditionalMetadataLocation)
|
||||
throws FileNotFoundException {
|
||||
private File locateGradleResourcesFolder(File standardAdditionalMetadataLocation) throws FileNotFoundException {
|
||||
String path = standardAdditionalMetadataLocation.getPath();
|
||||
int index = path.lastIndexOf(CLASSES_FOLDER);
|
||||
if (index < 0) {
|
||||
throw new FileNotFoundException();
|
||||
}
|
||||
String buildFolderPath = path.substring(0, index);
|
||||
File classOutputLocation = standardAdditionalMetadataLocation.getParentFile()
|
||||
.getParentFile();
|
||||
return new File(buildFolderPath,
|
||||
RESOURCES_FOLDER + '/' + classOutputLocation.getName());
|
||||
File classOutputLocation = standardAdditionalMetadataLocation.getParentFile().getParentFile();
|
||||
return new File(buildFolderPath, RESOURCES_FOLDER + '/' + classOutputLocation.getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -60,8 +60,7 @@ class TypeElementMembers {
|
||||
|
||||
private final FieldValuesParser fieldValuesParser;
|
||||
|
||||
TypeElementMembers(ProcessingEnvironment env, FieldValuesParser fieldValuesParser,
|
||||
TypeElement element) {
|
||||
TypeElementMembers(ProcessingEnvironment env, FieldValuesParser fieldValuesParser, TypeElement element) {
|
||||
this.env = env;
|
||||
this.typeUtils = new TypeUtils(this.env);
|
||||
this.fieldValuesParser = fieldValuesParser;
|
||||
@@ -69,12 +68,10 @@ class TypeElementMembers {
|
||||
}
|
||||
|
||||
private void process(TypeElement element) {
|
||||
for (ExecutableElement method : ElementFilter
|
||||
.methodsIn(element.getEnclosedElements())) {
|
||||
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
|
||||
processMethod(method);
|
||||
}
|
||||
for (VariableElement field : ElementFilter
|
||||
.fieldsIn(element.getEnclosedElements())) {
|
||||
for (VariableElement field : ElementFilter.fieldsIn(element.getEnclosedElements())) {
|
||||
processField(field);
|
||||
}
|
||||
try {
|
||||
@@ -89,8 +86,7 @@ class TypeElementMembers {
|
||||
}
|
||||
|
||||
Element superType = this.env.getTypeUtils().asElement(element.getSuperclass());
|
||||
if (superType != null && superType instanceof TypeElement
|
||||
&& !OBJECT_CLASS_NAME.equals(superType.toString())) {
|
||||
if (superType != null && superType instanceof TypeElement && !OBJECT_CLASS_NAME.equals(superType.toString())) {
|
||||
process((TypeElement) superType);
|
||||
}
|
||||
}
|
||||
@@ -103,8 +99,7 @@ class TypeElementMembers {
|
||||
}
|
||||
else if (isSetter(method)) {
|
||||
String propertyName = getAccessorName(name);
|
||||
List<ExecutableElement> matchingSetters = this.publicSetters
|
||||
.get(propertyName);
|
||||
List<ExecutableElement> matchingSetters = this.publicSetters.get(propertyName);
|
||||
if (matchingSetters == null) {
|
||||
matchingSetters = new ArrayList<>();
|
||||
this.publicSetters.put(propertyName, matchingSetters);
|
||||
@@ -119,13 +114,11 @@ class TypeElementMembers {
|
||||
|
||||
private boolean isPublic(ExecutableElement method) {
|
||||
Set<Modifier> modifiers = method.getModifiers();
|
||||
return modifiers.contains(Modifier.PUBLIC)
|
||||
&& !modifiers.contains(Modifier.ABSTRACT)
|
||||
return modifiers.contains(Modifier.PUBLIC) && !modifiers.contains(Modifier.ABSTRACT)
|
||||
&& !modifiers.contains(Modifier.STATIC);
|
||||
}
|
||||
|
||||
private ExecutableElement getMatchingSetter(List<ExecutableElement> candidates,
|
||||
TypeMirror type) {
|
||||
private ExecutableElement getMatchingSetter(List<ExecutableElement> candidates, TypeMirror type) {
|
||||
for (ExecutableElement candidate : candidates) {
|
||||
TypeMirror paramType = candidate.getParameters().get(0).asType();
|
||||
if (this.env.getTypeUtils().isSameType(paramType, type)) {
|
||||
@@ -137,27 +130,24 @@ class TypeElementMembers {
|
||||
|
||||
private boolean isGetter(ExecutableElement method) {
|
||||
String name = method.getSimpleName().toString();
|
||||
return ((name.startsWith("get") && name.length() > 3)
|
||||
|| (name.startsWith("is") && name.length() > 2))
|
||||
&& method.getParameters().isEmpty()
|
||||
&& (TypeKind.VOID != method.getReturnType().getKind());
|
||||
return ((name.startsWith("get") && name.length() > 3) || (name.startsWith("is") && name.length() > 2))
|
||||
&& method.getParameters().isEmpty() && (TypeKind.VOID != method.getReturnType().getKind());
|
||||
}
|
||||
|
||||
private boolean isSetter(ExecutableElement method) {
|
||||
final String name = method.getSimpleName().toString();
|
||||
return (name.startsWith("set") && name.length() > 3
|
||||
&& method.getParameters().size() == 1 && isSetterReturnType(method));
|
||||
return (name.startsWith("set") && name.length() > 3 && method.getParameters().size() == 1
|
||||
&& isSetterReturnType(method));
|
||||
}
|
||||
|
||||
private boolean isSetterReturnType(ExecutableElement method) {
|
||||
TypeMirror returnType = method.getReturnType();
|
||||
return (TypeKind.VOID == returnType.getKind() || this.env.getTypeUtils()
|
||||
.isSameType(method.getEnclosingElement().asType(), returnType));
|
||||
return (TypeKind.VOID == returnType.getKind()
|
||||
|| this.env.getTypeUtils().isSameType(method.getEnclosingElement().asType(), returnType));
|
||||
}
|
||||
|
||||
private String getAccessorName(String methodName) {
|
||||
String name = methodName.startsWith("is") ? methodName.substring(2)
|
||||
: methodName.substring(3);
|
||||
String name = methodName.startsWith("is") ? methodName.substring(2) : methodName.substring(3);
|
||||
name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
|
||||
return name;
|
||||
}
|
||||
@@ -185,8 +175,7 @@ class TypeElementMembers {
|
||||
return candidate;
|
||||
}
|
||||
TypeMirror alternative = this.typeUtils.getWrapperOrPrimitiveFor(type);
|
||||
if (alternative != null
|
||||
&& this.env.getTypeUtils().isSameType(returnType, alternative)) {
|
||||
if (alternative != null && this.env.getTypeUtils().isSameType(returnType, alternative)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,8 +70,7 @@ class TypeUtils {
|
||||
|
||||
static {
|
||||
Map<String, TypeKind> primitives = new HashMap<>();
|
||||
PRIMITIVE_WRAPPERS.forEach(
|
||||
(kind, wrapperClass) -> primitives.put(wrapperClass.getName(), kind));
|
||||
PRIMITIVE_WRAPPERS.forEach((kind, wrapperClass) -> primitives.put(wrapperClass.getName(), kind));
|
||||
WRAPPER_TO_PRIMITIVE = primitives;
|
||||
}
|
||||
|
||||
@@ -95,12 +94,10 @@ class TypeUtils {
|
||||
this.mapType = getDeclaredType(this.types, Map.class, 2);
|
||||
}
|
||||
|
||||
private TypeMirror getDeclaredType(Types types, Class<?> typeClass,
|
||||
int numberOfTypeArgs) {
|
||||
private TypeMirror getDeclaredType(Types types, Class<?> typeClass, int numberOfTypeArgs) {
|
||||
TypeMirror[] typeArgs = new TypeMirror[numberOfTypeArgs];
|
||||
Arrays.setAll(typeArgs, (i) -> types.getWildcardType(null, null));
|
||||
TypeElement typeElement = this.env.getElementUtils()
|
||||
.getTypeElement(typeClass.getName());
|
||||
TypeElement typeElement = this.env.getElementUtils().getTypeElement(typeClass.getName());
|
||||
try {
|
||||
return types.getDeclaredType(typeElement, typeArgs);
|
||||
}
|
||||
@@ -140,8 +137,7 @@ class TypeUtils {
|
||||
}
|
||||
|
||||
public String getJavaDoc(Element element) {
|
||||
String javadoc = (element != null)
|
||||
? this.env.getElementUtils().getDocComment(element) : null;
|
||||
String javadoc = (element != null) ? this.env.getElementUtils().getDocComment(element) : null;
|
||||
if (javadoc != null) {
|
||||
javadoc = NEW_LINE_PATTERN.matcher(javadoc).replaceAll("").trim();
|
||||
}
|
||||
@@ -151,8 +147,7 @@ class TypeUtils {
|
||||
public TypeMirror getWrapperOrPrimitiveFor(TypeMirror typeMirror) {
|
||||
Class<?> candidate = getWrapperFor(typeMirror);
|
||||
if (candidate != null) {
|
||||
return this.env.getElementUtils().getTypeElement(candidate.getName())
|
||||
.asType();
|
||||
return this.env.getElementUtils().getTypeElement(candidate.getName()).asType();
|
||||
}
|
||||
TypeKind primitiveKind = getPrimitiveFor(typeMirror);
|
||||
if (primitiveKind != null) {
|
||||
@@ -200,8 +195,7 @@ class TypeUtils {
|
||||
}
|
||||
}
|
||||
catch (Exception ex) {
|
||||
this.env.getMessager().printMessage(Kind.WARNING,
|
||||
"Failed to generated type descriptor for " + type,
|
||||
this.env.getMessager().printMessage(Kind.WARNING, "Failed to generated type descriptor for " + type,
|
||||
this.types.asElement(type));
|
||||
}
|
||||
}
|
||||
@@ -210,8 +204,7 @@ class TypeUtils {
|
||||
* A visitor that extracts the fully qualified name of a type, including generic
|
||||
* information.
|
||||
*/
|
||||
private static class TypeExtractor
|
||||
extends SimpleTypeVisitor8<String, TypeDescriptor> {
|
||||
private static class TypeExtractor extends SimpleTypeVisitor8<String, TypeDescriptor> {
|
||||
|
||||
private final Types types;
|
||||
|
||||
@@ -228,17 +221,15 @@ class TypeUtils {
|
||||
}
|
||||
StringBuilder name = new StringBuilder();
|
||||
name.append(qualifiedName);
|
||||
name.append("<").append(type.getTypeArguments().stream()
|
||||
.map((t) -> visit(t, descriptor)).collect(Collectors.joining(",")))
|
||||
name.append("<").append(
|
||||
type.getTypeArguments().stream().map((t) -> visit(t, descriptor)).collect(Collectors.joining(",")))
|
||||
.append(">");
|
||||
return name.toString();
|
||||
}
|
||||
|
||||
private String determineQualifiedName(DeclaredType type,
|
||||
TypeElement enclosingElement) {
|
||||
private String determineQualifiedName(DeclaredType type, TypeElement enclosingElement) {
|
||||
if (enclosingElement != null) {
|
||||
return getQualifiedName(enclosingElement) + "$"
|
||||
+ type.asElement().getSimpleName();
|
||||
return getQualifiedName(enclosingElement) + "$" + type.asElement().getSimpleName();
|
||||
}
|
||||
return getQualifiedName(type.asElement());
|
||||
}
|
||||
@@ -299,8 +290,7 @@ class TypeUtils {
|
||||
if (element instanceof TypeElement) {
|
||||
return ((TypeElement) element).getQualifiedName().toString();
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
"Could not extract qualified name from " + element);
|
||||
throw new IllegalStateException("Could not extract qualified name from " + element);
|
||||
}
|
||||
|
||||
private TypeElement getEnclosingTypeElement(TypeMirror type) {
|
||||
@@ -332,8 +322,7 @@ class TypeUtils {
|
||||
}
|
||||
|
||||
public TypeMirror resolveGeneric(String parameterName) {
|
||||
return this.generics.entrySet().stream()
|
||||
.filter((e) -> getParameterName(e.getKey()).equals(parameterName))
|
||||
return this.generics.entrySet().stream().filter((e) -> getParameterName(e.getKey()).equals(parameterName))
|
||||
.findFirst().map(Entry::getValue).orElse(null);
|
||||
}
|
||||
|
||||
@@ -341,8 +330,7 @@ class TypeUtils {
|
||||
if (variable instanceof TypeVariable) {
|
||||
TypeVariable typeVariable = (TypeVariable) variable;
|
||||
if (this.generics.keySet().stream()
|
||||
.noneMatch((candidate) -> getParameterName(candidate)
|
||||
.equals(getParameterName(typeVariable)))) {
|
||||
.noneMatch((candidate) -> getParameterName(candidate).equals(getParameterName(typeVariable)))) {
|
||||
this.generics.put(typeVariable, resolution);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -31,20 +31,15 @@ class ExpressionTree extends ReflectionWrapper {
|
||||
|
||||
private final Class<?> literalTreeType = findClass("com.sun.source.tree.LiteralTree");
|
||||
|
||||
private final Method literalValueMethod = findMethod(this.literalTreeType,
|
||||
"getValue");
|
||||
private final Method literalValueMethod = findMethod(this.literalTreeType, "getValue");
|
||||
|
||||
private final Class<?> methodInvocationTreeType = findClass(
|
||||
"com.sun.source.tree.MethodInvocationTree");
|
||||
private final Class<?> methodInvocationTreeType = findClass("com.sun.source.tree.MethodInvocationTree");
|
||||
|
||||
private final Method methodInvocationArgumentsMethod = findMethod(
|
||||
this.methodInvocationTreeType, "getArguments");
|
||||
private final Method methodInvocationArgumentsMethod = findMethod(this.methodInvocationTreeType, "getArguments");
|
||||
|
||||
private final Class<?> newArrayTreeType = findClass(
|
||||
"com.sun.source.tree.NewArrayTree");
|
||||
private final Class<?> newArrayTreeType = findClass("com.sun.source.tree.NewArrayTree");
|
||||
|
||||
private final Method arrayValueMethod = findMethod(this.newArrayTreeType,
|
||||
"getInitializers");
|
||||
private final Method arrayValueMethod = findMethod(this.newArrayTreeType, "getInitializers");
|
||||
|
||||
ExpressionTree(Object instance) {
|
||||
super("com.sun.source.tree.ExpressionTree", instance);
|
||||
@@ -63,8 +58,7 @@ class ExpressionTree extends ReflectionWrapper {
|
||||
|
||||
public Object getFactoryValue() throws Exception {
|
||||
if (this.methodInvocationTreeType.isAssignableFrom(getInstance().getClass())) {
|
||||
List<?> arguments = (List<?>) this.methodInvocationArgumentsMethod
|
||||
.invoke(getInstance());
|
||||
List<?> arguments = (List<?>) this.methodInvocationArgumentsMethod.invoke(getInstance());
|
||||
if (arguments.size() == 1) {
|
||||
return new ExpressionTree(arguments.get(0)).getLiteralValue();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -155,8 +155,7 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
private Object getValue(ExpressionTree expression, Object defaultValue)
|
||||
throws Exception {
|
||||
private Object getValue(ExpressionTree expression, Object defaultValue) throws Exception {
|
||||
Object literalValue = expression.getLiteralValue();
|
||||
if (literalValue != null) {
|
||||
return literalValue;
|
||||
@@ -187,21 +186,19 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser {
|
||||
}
|
||||
|
||||
private Object getFactoryValue(ExpressionTree expression, Object factoryValue) {
|
||||
Object durationValue = getFactoryValue(expression, factoryValue, DURATION_OF,
|
||||
DURATION_SUFFIX);
|
||||
Object durationValue = getFactoryValue(expression, factoryValue, DURATION_OF, DURATION_SUFFIX);
|
||||
if (durationValue != null) {
|
||||
return durationValue;
|
||||
}
|
||||
Object dataSizeValue = getFactoryValue(expression, factoryValue, DATA_SIZE_OF,
|
||||
DATA_SIZE_SUFFIX);
|
||||
Object dataSizeValue = getFactoryValue(expression, factoryValue, DATA_SIZE_OF, DATA_SIZE_SUFFIX);
|
||||
if (dataSizeValue != null) {
|
||||
return dataSizeValue;
|
||||
}
|
||||
return factoryValue;
|
||||
}
|
||||
|
||||
private Object getFactoryValue(ExpressionTree expression, Object factoryValue,
|
||||
String prefix, Map<String, String> suffixMapping) {
|
||||
private Object getFactoryValue(ExpressionTree expression, Object factoryValue, String prefix,
|
||||
Map<String, String> suffixMapping) {
|
||||
Object instance = expression.getInstance();
|
||||
if (instance != null && instance.toString().startsWith(prefix)) {
|
||||
String type = instance.toString();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -62,8 +62,7 @@ class ReflectionWrapper {
|
||||
}
|
||||
}
|
||||
|
||||
protected static Method findMethod(Class<?> type, String name,
|
||||
Class<?>... parameterTypes) {
|
||||
protected static Method findMethod(Class<?> type, String name, Class<?>... parameterTypes) {
|
||||
try {
|
||||
return type.getMethod(name, parameterTypes);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -30,22 +30,17 @@ class Tree extends ReflectionWrapper {
|
||||
|
||||
private final Class<?> treeVisitorType = findClass("com.sun.source.tree.TreeVisitor");
|
||||
|
||||
private final Method acceptMethod = findMethod("accept", this.treeVisitorType,
|
||||
Object.class);
|
||||
private final Method acceptMethod = findMethod("accept", this.treeVisitorType, Object.class);
|
||||
|
||||
private final Method getClassTreeMembers = findMethod(
|
||||
findClass("com.sun.source.tree.ClassTree"), "getMembers");
|
||||
private final Method getClassTreeMembers = findMethod(findClass("com.sun.source.tree.ClassTree"), "getMembers");
|
||||
|
||||
Tree(Object instance) {
|
||||
super("com.sun.source.tree.Tree", instance);
|
||||
}
|
||||
|
||||
public void accept(TreeVisitor visitor) throws Exception {
|
||||
this.acceptMethod.invoke(getInstance(),
|
||||
Proxy.newProxyInstance(getInstance().getClass().getClassLoader(),
|
||||
new Class<?>[] { this.treeVisitorType },
|
||||
new TreeVisitorInvocationHandler(visitor)),
|
||||
0);
|
||||
this.acceptMethod.invoke(getInstance(), Proxy.newProxyInstance(getInstance().getClass().getClassLoader(),
|
||||
new Class<?>[] { this.treeVisitorType }, new TreeVisitorInvocationHandler(visitor)), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,15 +56,12 @@ class Tree extends ReflectionWrapper {
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("rawtypes")
|
||||
public Object invoke(Object proxy, Method method, Object[] args)
|
||||
throws Throwable {
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
if (method.getName().equals("visitClass") && (Integer) args[1] == 0) {
|
||||
Iterable members = (Iterable) Tree.this.getClassTreeMembers
|
||||
.invoke(args[0]);
|
||||
Iterable members = (Iterable) Tree.this.getClassTreeMembers.invoke(args[0]);
|
||||
for (Object member : members) {
|
||||
if (member != null) {
|
||||
Tree.this.acceptMethod.invoke(member, proxy,
|
||||
((Integer) args[1]) + 1);
|
||||
Tree.this.acceptMethod.invoke(member, proxy, ((Integer) args[1]) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -52,8 +52,7 @@ class VariableTree extends ReflectionWrapper {
|
||||
if (modifiers == null) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return (Set<Modifier>) findMethod(findClass("com.sun.source.tree.ModifiersTree"),
|
||||
"getFlags").invoke(modifiers);
|
||||
return (Set<Modifier>) findMethod(findClass("com.sun.source.tree.ModifiersTree"), "getFlags").invoke(modifiers);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -152,8 +152,7 @@ public class ConfigurationMetadata {
|
||||
candidates = new ArrayList<>(candidates);
|
||||
candidates.removeIf((itemMetadata) -> !itemMetadata.hasSameType(metadata));
|
||||
if (candidates.size() > 1 && metadata.getType() != null) {
|
||||
candidates.removeIf(
|
||||
(itemMetadata) -> !metadata.getType().equals(itemMetadata.getType()));
|
||||
candidates.removeIf((itemMetadata) -> !metadata.getType().equals(itemMetadata.getType()));
|
||||
}
|
||||
if (candidates.size() == 1) {
|
||||
return candidates.get(0);
|
||||
@@ -187,8 +186,7 @@ public class ConfigurationMetadata {
|
||||
if (SEPARATORS.contains(current)) {
|
||||
dashed.append("-");
|
||||
}
|
||||
else if (Character.isUpperCase(current) && previous != null
|
||||
&& !SEPARATORS.contains(previous)) {
|
||||
else if (Character.isUpperCase(current) && previous != null && !SEPARATORS.contains(previous)) {
|
||||
dashed.append("-").append(current);
|
||||
}
|
||||
else {
|
||||
@@ -213,8 +211,7 @@ public class ConfigurationMetadata {
|
||||
public String toString() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
result.append(String.format("items: %n"));
|
||||
this.items.values().forEach((itemMetadata) -> result.append("\t")
|
||||
.append(String.format("%s%n", itemMetadata)));
|
||||
this.items.values().forEach((itemMetadata) -> result.append("\t").append(String.format("%s%n", itemMetadata)));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -77,8 +77,7 @@ public class ItemDeprecation {
|
||||
return false;
|
||||
}
|
||||
ItemDeprecation other = (ItemDeprecation) o;
|
||||
return nullSafeEquals(this.reason, other.reason)
|
||||
&& nullSafeEquals(this.replacement, other.replacement)
|
||||
return nullSafeEquals(this.reason, other.reason) && nullSafeEquals(this.replacement, other.replacement)
|
||||
&& nullSafeEquals(this.level, other.level);
|
||||
}
|
||||
|
||||
@@ -92,9 +91,8 @@ public class ItemDeprecation {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ItemDeprecation{" + "reason='" + this.reason + '\'' + ", "
|
||||
+ "replacement='" + this.replacement + '\'' + ", " + "level='"
|
||||
+ this.level + '\'' + '}';
|
||||
return "ItemDeprecation{" + "reason='" + this.reason + '\'' + ", " + "replacement='" + this.replacement + '\''
|
||||
+ ", " + "level='" + this.level + '\'' + '}';
|
||||
}
|
||||
|
||||
private boolean nullSafeEquals(Object o1, Object o2) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -45,8 +45,7 @@ public class ItemHint implements Comparable<ItemHint> {
|
||||
public ItemHint(String name, List<ValueHint> values, List<ValueProvider> providers) {
|
||||
this.name = toCanonicalName(name);
|
||||
this.values = (values != null) ? new ArrayList<>(values) : new ArrayList<>();
|
||||
this.providers = (providers != null) ? new ArrayList<>(providers)
|
||||
: new ArrayList<>();
|
||||
this.providers = (providers != null) ? new ArrayList<>(providers) : new ArrayList<>();
|
||||
}
|
||||
|
||||
private String toCanonicalName(String name) {
|
||||
@@ -82,8 +81,7 @@ public class ItemHint implements Comparable<ItemHint> {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ItemHint{" + "name='" + this.name + "', values=" + this.values
|
||||
+ ", providers=" + this.providers + '}';
|
||||
return "ItemHint{" + "name='" + this.name + "', values=" + this.values + ", providers=" + this.providers + '}';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,8 +108,7 @@ public class ItemHint implements Comparable<ItemHint> {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ValueHint{" + "value=" + this.value + ", description='"
|
||||
+ this.description + '\'' + '}';
|
||||
return "ValueHint{" + "value=" + this.value + ", description='" + this.description + '\'' + '}';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -140,8 +137,7 @@ public class ItemHint implements Comparable<ItemHint> {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ValueProvider{" + "name='" + this.name + "', parameters="
|
||||
+ this.parameters + '}';
|
||||
return "ValueProvider{" + "name='" + this.name + "', parameters=" + this.parameters + '}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -44,9 +44,8 @@ public final class ItemMetadata implements Comparable<ItemMetadata> {
|
||||
|
||||
private ItemDeprecation deprecation;
|
||||
|
||||
ItemMetadata(ItemType itemType, String prefix, String name, String type,
|
||||
String sourceType, String sourceMethod, String description,
|
||||
Object defaultValue, ItemDeprecation deprecation) {
|
||||
ItemMetadata(ItemType itemType, String prefix, String name, String type, String sourceType, String sourceMethod,
|
||||
String description, Object defaultValue, ItemDeprecation deprecation) {
|
||||
this.itemType = itemType;
|
||||
this.name = buildName(prefix, name);
|
||||
this.type = type;
|
||||
@@ -197,8 +196,7 @@ public final class ItemMetadata implements Comparable<ItemMetadata> {
|
||||
return string.toString();
|
||||
}
|
||||
|
||||
protected void buildToStringProperty(StringBuilder string, String property,
|
||||
Object value) {
|
||||
protected void buildToStringProperty(StringBuilder string, String property, Object value) {
|
||||
if (value != null) {
|
||||
string.append(" ").append(property).append(":").append(value);
|
||||
}
|
||||
@@ -209,22 +207,18 @@ public final class ItemMetadata implements Comparable<ItemMetadata> {
|
||||
return getName().compareTo(o.getName());
|
||||
}
|
||||
|
||||
public static ItemMetadata newGroup(String name, String type, String sourceType,
|
||||
String sourceMethod) {
|
||||
return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType,
|
||||
sourceMethod, null, null, null);
|
||||
public static ItemMetadata newGroup(String name, String type, String sourceType, String sourceMethod) {
|
||||
return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, sourceMethod, null, null, null);
|
||||
}
|
||||
|
||||
public static ItemMetadata newProperty(String prefix, String name, String type,
|
||||
String sourceType, String sourceMethod, String description,
|
||||
Object defaultValue, ItemDeprecation deprecation) {
|
||||
return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType,
|
||||
sourceMethod, description, defaultValue, deprecation);
|
||||
public static ItemMetadata newProperty(String prefix, String name, String type, String sourceType,
|
||||
String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) {
|
||||
return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, sourceMethod, description,
|
||||
defaultValue, deprecation);
|
||||
}
|
||||
|
||||
public static String newItemMetadataPrefix(String prefix, String suffix) {
|
||||
return prefix.toLowerCase(Locale.ENGLISH)
|
||||
+ ConfigurationMetadata.toDashedCase(suffix);
|
||||
return prefix.toLowerCase(Locale.ENGLISH) + ConfigurationMetadata.toDashedCase(suffix);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -37,12 +37,10 @@ class JsonConverter {
|
||||
|
||||
private static final ItemMetadataComparator ITEM_COMPARATOR = new ItemMetadataComparator();
|
||||
|
||||
public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType)
|
||||
throws Exception {
|
||||
public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) throws Exception {
|
||||
JSONArray jsonArray = new JSONArray();
|
||||
List<ItemMetadata> items = metadata.getItems().stream()
|
||||
.filter((item) -> item.isOfItemType(itemType)).sorted(ITEM_COMPARATOR)
|
||||
.collect(Collectors.toList());
|
||||
List<ItemMetadata> items = metadata.getItems().stream().filter((item) -> item.isOfItemType(itemType))
|
||||
.sorted(ITEM_COMPARATOR).collect(Collectors.toList());
|
||||
for (ItemMetadata item : items) {
|
||||
if (item.isOfItemType(itemType)) {
|
||||
jsonArray.put(toJsonObject(item));
|
||||
@@ -123,8 +121,7 @@ class JsonConverter {
|
||||
return providers;
|
||||
}
|
||||
|
||||
private JSONObject getItemHintProvider(ItemHint.ValueProvider provider)
|
||||
throws Exception {
|
||||
private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) throws Exception {
|
||||
JSONObject result = new JSONObject();
|
||||
result.put("name", provider.getName());
|
||||
if (provider.getParameters() != null && !provider.getParameters().isEmpty()) {
|
||||
@@ -137,8 +134,7 @@ class JsonConverter {
|
||||
return result;
|
||||
}
|
||||
|
||||
private void putIfPresent(JSONObject jsonObject, String name, Object value)
|
||||
throws Exception {
|
||||
private void putIfPresent(JSONObject jsonObject, String name, Object value) throws Exception {
|
||||
if (value != null) {
|
||||
jsonObject.put(name, value);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -42,8 +42,7 @@ public class JsonMarshaller {
|
||||
|
||||
private static final int BUFFER_SIZE = 4098;
|
||||
|
||||
public void write(ConfigurationMetadata metadata, OutputStream outputStream)
|
||||
throws IOException {
|
||||
public void write(ConfigurationMetadata metadata, OutputStream outputStream) throws IOException {
|
||||
try {
|
||||
JSONObject object = new JSONObject();
|
||||
JsonConverter converter = new JsonConverter();
|
||||
@@ -75,8 +74,7 @@ public class JsonMarshaller {
|
||||
JSONArray properties = object.optJSONArray("properties");
|
||||
if (properties != null) {
|
||||
for (int i = 0; i < properties.length(); i++) {
|
||||
metadata.add(toItemMetadata((JSONObject) properties.get(i),
|
||||
ItemType.PROPERTY));
|
||||
metadata.add(toItemMetadata((JSONObject) properties.get(i), ItemType.PROPERTY));
|
||||
}
|
||||
}
|
||||
JSONArray hints = object.optJSONArray("hints");
|
||||
@@ -88,8 +86,7 @@ public class JsonMarshaller {
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private ItemMetadata toItemMetadata(JSONObject object, ItemType itemType)
|
||||
throws Exception {
|
||||
private ItemMetadata toItemMetadata(JSONObject object, ItemType itemType) throws Exception {
|
||||
String name = object.getString("name");
|
||||
String type = object.optString("type", null);
|
||||
String description = object.optString("description", null);
|
||||
@@ -97,8 +94,8 @@ public class JsonMarshaller {
|
||||
String sourceMethod = object.optString("sourceMethod", null);
|
||||
Object defaultValue = readItemValue(object.opt("defaultValue"));
|
||||
ItemDeprecation deprecation = toItemDeprecation(object);
|
||||
return new ItemMetadata(itemType, name, null, type, sourceType, sourceMethod,
|
||||
description, defaultValue, deprecation);
|
||||
return new ItemMetadata(itemType, name, null, type, sourceType, sourceMethod, description, defaultValue,
|
||||
deprecation);
|
||||
}
|
||||
|
||||
private ItemDeprecation toItemDeprecation(JSONObject object) throws Exception {
|
||||
@@ -107,8 +104,7 @@ public class JsonMarshaller {
|
||||
ItemDeprecation deprecation = new ItemDeprecation();
|
||||
deprecation.setLevel(deprecationJsonObject.optString("level", null));
|
||||
deprecation.setReason(deprecationJsonObject.optString("reason", null));
|
||||
deprecation
|
||||
.setReplacement(deprecationJsonObject.optString("replacement", null));
|
||||
deprecation.setReplacement(deprecationJsonObject.optString("replacement", null));
|
||||
return deprecation;
|
||||
}
|
||||
return object.optBoolean("deprecated") ? new ItemDeprecation() : null;
|
||||
@@ -167,8 +163,7 @@ public class JsonMarshaller {
|
||||
|
||||
private String toString(InputStream inputStream) throws IOException {
|
||||
StringBuilder out = new StringBuilder();
|
||||
InputStreamReader reader = new InputStreamReader(inputStream,
|
||||
StandardCharsets.UTF_8);
|
||||
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
||||
char[] buffer = new char[BUFFER_SIZE];
|
||||
int bytesRead;
|
||||
while ((bytesRead = reader.read(buffer)) != -1) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -50,13 +50,11 @@ public class MetadataStoreTests {
|
||||
File classesLocation = new File(app, "target/classes");
|
||||
File metaInf = new File(classesLocation, "META-INF");
|
||||
metaInf.mkdirs();
|
||||
File additionalMetadata = new File(metaInf,
|
||||
"additional-spring-configuration-metadata.json");
|
||||
File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json");
|
||||
additionalMetadata.createNewFile();
|
||||
assertThat(
|
||||
this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation,
|
||||
"META-INF/additional-spring-configuration-metadata.json")))
|
||||
.isEqualTo(additionalMetadata);
|
||||
assertThat(this.metadataStore.locateAdditionalMetadataFile(
|
||||
new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json")))
|
||||
.isEqualTo(additionalMetadata);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -66,13 +64,11 @@ public class MetadataStoreTests {
|
||||
File resourcesLocation = new File(app, "build/resources/main");
|
||||
File metaInf = new File(resourcesLocation, "META-INF");
|
||||
metaInf.mkdirs();
|
||||
File additionalMetadata = new File(metaInf,
|
||||
"additional-spring-configuration-metadata.json");
|
||||
File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json");
|
||||
additionalMetadata.createNewFile();
|
||||
assertThat(
|
||||
this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation,
|
||||
"META-INF/additional-spring-configuration-metadata.json")))
|
||||
.isEqualTo(additionalMetadata);
|
||||
assertThat(this.metadataStore.locateAdditionalMetadataFile(
|
||||
new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json")))
|
||||
.isEqualTo(additionalMetadata);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -82,13 +78,11 @@ public class MetadataStoreTests {
|
||||
File resourcesLocation = new File(app, "build/resources/main");
|
||||
File metaInf = new File(resourcesLocation, "META-INF");
|
||||
metaInf.mkdirs();
|
||||
File additionalMetadata = new File(metaInf,
|
||||
"additional-spring-configuration-metadata.json");
|
||||
File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json");
|
||||
additionalMetadata.createNewFile();
|
||||
assertThat(
|
||||
this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation,
|
||||
"META-INF/additional-spring-configuration-metadata.json")))
|
||||
.isEqualTo(additionalMetadata);
|
||||
assertThat(this.metadataStore.locateAdditionalMetadataFile(
|
||||
new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json")))
|
||||
.isEqualTo(additionalMetadata);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -97,14 +91,12 @@ public class MetadataStoreTests {
|
||||
File location = new File(app, "src/main/resources");
|
||||
File metaInf = new File(location, "META-INF");
|
||||
metaInf.mkdirs();
|
||||
File additionalMetadata = new File(metaInf,
|
||||
"additional-spring-configuration-metadata.json");
|
||||
File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json");
|
||||
additionalMetadata.createNewFile();
|
||||
given(this.environment.getOptions()).willReturn(Collections.singletonMap(
|
||||
ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION,
|
||||
location.getAbsolutePath()));
|
||||
assertThat(this.metadataStore.locateAdditionalMetadataFile(new File(app, "foo")))
|
||||
.isEqualTo(additionalMetadata);
|
||||
given(this.environment.getOptions()).willReturn(
|
||||
Collections.singletonMap(ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION,
|
||||
location.getAbsolutePath()));
|
||||
assertThat(this.metadataStore.locateAdditionalMetadataFile(new File(app, "foo"))).isEqualTo(additionalMetadata);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -37,8 +37,7 @@ import org.springframework.boot.configurationprocessor.metadata.JsonMarshaller;
|
||||
*/
|
||||
@SupportedAnnotationTypes({ "*" })
|
||||
@SupportedSourceVersion(SourceVersion.RELEASE_6)
|
||||
public class TestConfigurationMetadataAnnotationProcessor
|
||||
extends ConfigurationMetadataAnnotationProcessor {
|
||||
public class TestConfigurationMetadataAnnotationProcessor extends ConfigurationMetadataAnnotationProcessor {
|
||||
|
||||
static final String CONFIGURATION_PROPERTIES_ANNOTATION = "org.springframework.boot.configurationsample.ConfigurationProperties";
|
||||
|
||||
@@ -87,11 +86,9 @@ public class TestConfigurationMetadataAnnotationProcessor
|
||||
protected ConfigurationMetadata writeMetaData() throws Exception {
|
||||
super.writeMetaData();
|
||||
try {
|
||||
File metadataFile = new File(this.outputLocation,
|
||||
"META-INF/spring-configuration-metadata.json");
|
||||
File metadataFile = new File(this.outputLocation, "META-INF/spring-configuration-metadata.json");
|
||||
if (metadataFile.isFile()) {
|
||||
this.metadata = new JsonMarshaller()
|
||||
.read(new FileInputStream(metadataFile));
|
||||
this.metadata = new JsonMarshaller().read(new FileInputStream(metadataFile));
|
||||
}
|
||||
else {
|
||||
this.metadata = new ConfigurationMetadata();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -63,8 +63,7 @@ public class TestProject {
|
||||
|
||||
private Set<File> sourceFiles = new LinkedHashSet<>();
|
||||
|
||||
public TestProject(TemporaryFolder tempFolder, Class<?>... classes)
|
||||
throws IOException {
|
||||
public TestProject(TemporaryFolder tempFolder, Class<?>... classes) throws IOException {
|
||||
this.sourceFolder = tempFolder.newFolder();
|
||||
this.compiler = new TestCompiler(tempFolder) {
|
||||
@Override
|
||||
@@ -133,15 +132,12 @@ public class TestProject {
|
||||
* @param snippetStream the snippet stream
|
||||
* @throws Exception if the source cannot be added
|
||||
*/
|
||||
public void addSourceCode(Class<?> target, InputStream snippetStream)
|
||||
throws Exception {
|
||||
public void addSourceCode(Class<?> target, InputStream snippetStream) throws Exception {
|
||||
File targetFile = getSourceFile(target);
|
||||
String contents = getContents(targetFile);
|
||||
int insertAt = contents.lastIndexOf('}');
|
||||
String additionalSource = FileCopyUtils
|
||||
.copyToString(new InputStreamReader(snippetStream));
|
||||
contents = contents.substring(0, insertAt) + additionalSource
|
||||
+ contents.substring(insertAt);
|
||||
String additionalSource = FileCopyUtils.copyToString(new InputStreamReader(snippetStream));
|
||||
contents = contents.substring(0, insertAt) + additionalSource + contents.substring(insertAt);
|
||||
putContents(targetFile, contents);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,16 +56,12 @@ public class TypeUtilsTests {
|
||||
public void resolveTypeDescriptorOnConcreteClass() throws IOException {
|
||||
process(SimpleGenericProperties.class, (roundEnv, typeUtils) -> {
|
||||
for (Element rootElement : roundEnv.getRootElements()) {
|
||||
TypeDescriptor typeDescriptor = typeUtils
|
||||
.resolveTypeDescriptor((TypeElement) rootElement);
|
||||
assertThat(typeDescriptor.getGenerics().keySet().stream()
|
||||
.map(Object::toString)).containsOnly("A", "B", "C");
|
||||
assertThat(typeDescriptor.resolveGeneric("A"))
|
||||
.hasToString(String.class.getName());
|
||||
assertThat(typeDescriptor.resolveGeneric("B"))
|
||||
.hasToString(Integer.class.getName());
|
||||
assertThat(typeDescriptor.resolveGeneric("C"))
|
||||
.hasToString(Duration.class.getName());
|
||||
TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor((TypeElement) rootElement);
|
||||
assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B",
|
||||
"C");
|
||||
assertThat(typeDescriptor.resolveGeneric("A")).hasToString(String.class.getName());
|
||||
assertThat(typeDescriptor.resolveGeneric("B")).hasToString(Integer.class.getName());
|
||||
assertThat(typeDescriptor.resolveGeneric("C")).hasToString(Duration.class.getName());
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -74,14 +70,11 @@ public class TypeUtilsTests {
|
||||
public void resolveTypeDescriptorOnIntermediateClass() throws IOException {
|
||||
process(AbstractIntermediateGenericProperties.class, (roundEnv, typeUtils) -> {
|
||||
for (Element rootElement : roundEnv.getRootElements()) {
|
||||
TypeDescriptor typeDescriptor = typeUtils
|
||||
.resolveTypeDescriptor((TypeElement) rootElement);
|
||||
assertThat(typeDescriptor.getGenerics().keySet().stream()
|
||||
.map(Object::toString)).containsOnly("A", "B", "C");
|
||||
assertThat(typeDescriptor.resolveGeneric("A"))
|
||||
.hasToString(String.class.getName());
|
||||
assertThat(typeDescriptor.resolveGeneric("B"))
|
||||
.hasToString(Integer.class.getName());
|
||||
TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor((TypeElement) rootElement);
|
||||
assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B",
|
||||
"C");
|
||||
assertThat(typeDescriptor.resolveGeneric("A")).hasToString(String.class.getName());
|
||||
assertThat(typeDescriptor.resolveGeneric("B")).hasToString(Integer.class.getName());
|
||||
assertThat(typeDescriptor.resolveGeneric("C")).hasToString("C");
|
||||
}
|
||||
});
|
||||
@@ -91,17 +84,15 @@ public class TypeUtilsTests {
|
||||
public void resolveTypeDescriptorWithOnlyGenerics() throws IOException {
|
||||
process(AbstractGenericProperties.class, (roundEnv, typeUtils) -> {
|
||||
for (Element rootElement : roundEnv.getRootElements()) {
|
||||
TypeDescriptor typeDescriptor = typeUtils
|
||||
.resolveTypeDescriptor((TypeElement) rootElement);
|
||||
assertThat(typeDescriptor.getGenerics().keySet().stream()
|
||||
.map(Object::toString)).containsOnly("A", "B", "C");
|
||||
TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor((TypeElement) rootElement);
|
||||
assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B",
|
||||
"C");
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void process(Class<?> target,
|
||||
BiConsumer<RoundEnvironment, TypeUtils> consumer) throws IOException {
|
||||
private void process(Class<?> target, BiConsumer<RoundEnvironment, TypeUtils> consumer) throws IOException {
|
||||
TestProcessor processor = new TestProcessor(consumer);
|
||||
TestCompiler compiler = new TestCompiler(this.temporaryFolder);
|
||||
compiler.getTask(target).call(processor);
|
||||
@@ -125,8 +116,7 @@ public class TypeUtilsTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean process(Set<? extends TypeElement> annotations,
|
||||
RoundEnvironment roundEnv) {
|
||||
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
|
||||
this.typeUtilsConsumer.accept(roundEnv, this.typeUtils);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -84,8 +84,7 @@ public abstract class AbstractFieldValuesProcessorTests {
|
||||
assertThat(values.get("stringArrayNone")).isNull();
|
||||
assertThat(values.get("stringEmptyArray")).isEqualTo(new Object[0]);
|
||||
assertThat(values.get("stringArrayConst")).isEqualTo(new Object[] { "OK", "KO" });
|
||||
assertThat(values.get("stringArrayConstElements"))
|
||||
.isEqualTo(new Object[] { "c" });
|
||||
assertThat(values.get("stringArrayConstElements")).isEqualTo(new Object[] { "c" });
|
||||
assertThat(values.get("integerArray")).isEqualTo(new Object[] { 42, 24 });
|
||||
assertThat(values.get("unknownArray")).isNull();
|
||||
assertThat(values.get("durationNone")).isNull();
|
||||
@@ -103,8 +102,7 @@ public abstract class AbstractFieldValuesProcessorTests {
|
||||
assertThat(values.get("dataSizeTerabytes")).isEqualTo("40TB");
|
||||
}
|
||||
|
||||
@SupportedAnnotationTypes({
|
||||
"org.springframework.boot.configurationsample.ConfigurationProperties" })
|
||||
@SupportedAnnotationTypes({ "org.springframework.boot.configurationsample.ConfigurationProperties" })
|
||||
@SupportedSourceVersion(SourceVersion.RELEASE_6)
|
||||
private class TestProcessor extends AbstractProcessor {
|
||||
|
||||
@@ -118,14 +116,12 @@ public abstract class AbstractFieldValuesProcessorTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean process(Set<? extends TypeElement> annotations,
|
||||
RoundEnvironment roundEnv) {
|
||||
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
|
||||
for (TypeElement annotation : annotations) {
|
||||
for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
|
||||
if (element instanceof TypeElement) {
|
||||
try {
|
||||
this.values.putAll(
|
||||
this.processor.getFieldValues((TypeElement) element));
|
||||
this.values.putAll(this.processor.getFieldValues((TypeElement) element));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -28,8 +28,7 @@ import static org.junit.Assume.assumeNoException;
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class JavaCompilerFieldValuesProcessorTests
|
||||
extends AbstractFieldValuesProcessorTests {
|
||||
public class JavaCompilerFieldValuesProcessorTests extends AbstractFieldValuesProcessorTests {
|
||||
|
||||
@Override
|
||||
protected FieldValuesParser createProcessor(ProcessingEnvironment env) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -44,14 +44,12 @@ public class ConfigurationMetadataTests {
|
||||
|
||||
@Test
|
||||
public void toDashedCaseWordsUnderscore() {
|
||||
assertThat(toDashedCase("Word_With_underscore"))
|
||||
.isEqualTo("word-with-underscore");
|
||||
assertThat(toDashedCase("Word_With_underscore")).isEqualTo("word-with-underscore");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toDashedCaseWordsSeveralUnderscores() {
|
||||
assertThat(toDashedCase("Word___With__underscore"))
|
||||
.isEqualTo("word---with--underscore");
|
||||
assertThat(toDashedCase("Word___With__underscore")).isEqualTo("word---with--underscore");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -34,14 +34,12 @@ public class ItemMetadataTests {
|
||||
|
||||
@Test
|
||||
public void newItemMetadataPrefixWithCamelCaseSuffix() {
|
||||
assertThat(newItemMetadataPrefix("prefix.", "myValue"))
|
||||
.isEqualTo("prefix.my-value");
|
||||
assertThat(newItemMetadataPrefix("prefix.", "myValue")).isEqualTo("prefix.my-value");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newItemMetadataPrefixWithUpperCamelCaseSuffix() {
|
||||
assertThat(newItemMetadataPrefix("prefix.", "MyValue"))
|
||||
.isEqualTo("prefix.my-value");
|
||||
assertThat(newItemMetadataPrefix("prefix.", "MyValue")).isEqualTo("prefix.my-value");
|
||||
}
|
||||
|
||||
private String newItemMetadataPrefix(String prefix, String suffix) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -38,49 +38,34 @@ public class JsonMarshallerTests {
|
||||
@Test
|
||||
public void marshallAndUnmarshal() throws Exception {
|
||||
ConfigurationMetadata metadata = new ConfigurationMetadata();
|
||||
metadata.add(ItemMetadata.newProperty("a", "b", StringBuffer.class.getName(),
|
||||
InputStream.class.getName(), "sourceMethod", "desc", "x",
|
||||
new ItemDeprecation("Deprecation comment", "b.c.d")));
|
||||
metadata.add(ItemMetadata.newProperty("b.c.d", null, null, null, null, null, null,
|
||||
null));
|
||||
metadata.add(
|
||||
ItemMetadata.newProperty("c", null, null, null, null, null, 123, null));
|
||||
metadata.add(
|
||||
ItemMetadata.newProperty("d", null, null, null, null, null, true, null));
|
||||
metadata.add(ItemMetadata.newProperty("e", null, null, null, null, null,
|
||||
new String[] { "y", "n" }, null));
|
||||
metadata.add(ItemMetadata.newProperty("f", null, null, null, null, null,
|
||||
new Boolean[] { true, false }, null));
|
||||
metadata.add(ItemMetadata.newProperty("a", "b", StringBuffer.class.getName(), InputStream.class.getName(),
|
||||
"sourceMethod", "desc", "x", new ItemDeprecation("Deprecation comment", "b.c.d")));
|
||||
metadata.add(ItemMetadata.newProperty("b.c.d", null, null, null, null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("c", null, null, null, null, null, 123, null));
|
||||
metadata.add(ItemMetadata.newProperty("d", null, null, null, null, null, true, null));
|
||||
metadata.add(ItemMetadata.newProperty("e", null, null, null, null, null, new String[] { "y", "n" }, null));
|
||||
metadata.add(ItemMetadata.newProperty("f", null, null, null, null, null, new Boolean[] { true, false }, null));
|
||||
metadata.add(ItemMetadata.newGroup("d", null, null, null));
|
||||
metadata.add(ItemHint.newHint("a.b"));
|
||||
metadata.add(ItemHint.newHint("c", new ItemHint.ValueHint(123, "hey"),
|
||||
new ItemHint.ValueHint(456, null)));
|
||||
metadata.add(ItemHint.newHint("c", new ItemHint.ValueHint(123, "hey"), new ItemHint.ValueHint(456, null)));
|
||||
metadata.add(new ItemHint("d", null,
|
||||
Arrays.asList(
|
||||
new ItemHint.ValueProvider("first",
|
||||
Collections.singletonMap("target", "foo")),
|
||||
Arrays.asList(new ItemHint.ValueProvider("first", Collections.singletonMap("target", "foo")),
|
||||
new ItemHint.ValueProvider("second", null))));
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
JsonMarshaller marshaller = new JsonMarshaller();
|
||||
marshaller.write(metadata, outputStream);
|
||||
ConfigurationMetadata read = marshaller
|
||||
.read(new ByteArrayInputStream(outputStream.toByteArray()));
|
||||
assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class)
|
||||
.fromSource(InputStream.class).withDescription("desc")
|
||||
.withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d"));
|
||||
ConfigurationMetadata read = marshaller.read(new ByteArrayInputStream(outputStream.toByteArray()));
|
||||
assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class).fromSource(InputStream.class)
|
||||
.withDescription("desc").withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d"));
|
||||
assertThat(read).has(Metadata.withProperty("b.c.d"));
|
||||
assertThat(read).has(Metadata.withProperty("c").withDefaultValue(123));
|
||||
assertThat(read).has(Metadata.withProperty("d").withDefaultValue(true));
|
||||
assertThat(read).has(
|
||||
Metadata.withProperty("e").withDefaultValue(new String[] { "y", "n" }));
|
||||
assertThat(read).has(Metadata.withProperty("f")
|
||||
.withDefaultValue(new Object[] { true, false }));
|
||||
assertThat(read).has(Metadata.withProperty("e").withDefaultValue(new String[] { "y", "n" }));
|
||||
assertThat(read).has(Metadata.withProperty("f").withDefaultValue(new Object[] { true, false }));
|
||||
assertThat(read).has(Metadata.withGroup("d"));
|
||||
assertThat(read).has(Metadata.withHint("a.b"));
|
||||
assertThat(read).has(
|
||||
Metadata.withHint("c").withValue(0, 123, "hey").withValue(1, 456, null));
|
||||
assertThat(read).has(Metadata.withHint("d").withProvider("first", "target", "foo")
|
||||
.withProvider("second"));
|
||||
assertThat(read).has(Metadata.withHint("c").withValue(0, 123, "hey").withValue(1, 456, null));
|
||||
assertThat(read).has(Metadata.withHint("d").withProvider("first", "target", "foo").withProvider("second"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -88,45 +73,35 @@ public class JsonMarshallerTests {
|
||||
ConfigurationMetadata metadata = new ConfigurationMetadata();
|
||||
metadata.add(ItemHint.newHint("fff"));
|
||||
metadata.add(ItemHint.newHint("eee"));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null,
|
||||
null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null,
|
||||
null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null,
|
||||
null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null,
|
||||
null, null, null, null));
|
||||
metadata.add(ItemMetadata.newGroup("com.acme.bravo",
|
||||
"com.example.AnotherTestProperties", null, null));
|
||||
metadata.add(ItemMetadata.newGroup("com.acme.alpha", "com.example.TestProperties",
|
||||
null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null, null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null, null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null, null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null, null, null, null, null));
|
||||
metadata.add(ItemMetadata.newGroup("com.acme.bravo", "com.example.AnotherTestProperties", null, null));
|
||||
metadata.add(ItemMetadata.newGroup("com.acme.alpha", "com.example.TestProperties", null, null));
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
JsonMarshaller marshaller = new JsonMarshaller();
|
||||
marshaller.write(metadata, outputStream);
|
||||
String json = new String(outputStream.toByteArray());
|
||||
assertThat(json).containsSubsequence("\"groups\"", "\"com.acme.alpha\"",
|
||||
"\"com.acme.bravo\"", "\"properties\"", "\"com.example.alpha.ccc\"",
|
||||
"\"com.example.alpha.ddd\"", "\"com.example.bravo.aaa\"",
|
||||
assertThat(json).containsSubsequence("\"groups\"", "\"com.acme.alpha\"", "\"com.acme.bravo\"", "\"properties\"",
|
||||
"\"com.example.alpha.ccc\"", "\"com.example.alpha.ddd\"", "\"com.example.bravo.aaa\"",
|
||||
"\"com.example.bravo.bbb\"", "\"hints\"", "\"eee\"", "\"fff\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void marshallPutDeprecatedItemsAtTheEnd() throws IOException {
|
||||
ConfigurationMetadata metadata = new ConfigurationMetadata();
|
||||
metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null,
|
||||
null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null,
|
||||
null, null, null, new ItemDeprecation(null, null, "warning")));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null,
|
||||
null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null,
|
||||
null, null, null, new ItemDeprecation(null, null, "warning")));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null, null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null, null, null, null,
|
||||
new ItemDeprecation(null, null, "warning")));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null, null, null, null, null));
|
||||
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null, null, null, null,
|
||||
new ItemDeprecation(null, null, "warning")));
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
JsonMarshaller marshaller = new JsonMarshaller();
|
||||
marshaller.write(metadata, outputStream);
|
||||
String json = new String(outputStream.toByteArray());
|
||||
assertThat(json).containsSubsequence("\"properties\"",
|
||||
"\"com.example.alpha.ddd\"", "\"com.example.bravo.bbb\"",
|
||||
assertThat(json).containsSubsequence("\"properties\"", "\"com.example.alpha.ddd\"", "\"com.example.bravo.bbb\"",
|
||||
"\"com.example.alpha.ccc\"", "\"com.example.bravo.aaa\"");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -92,9 +92,8 @@ public final class Metadata {
|
||||
this(itemType, name, null, null, null, null, null, null);
|
||||
}
|
||||
|
||||
public MetadataItemCondition(ItemType itemType, String name, String type,
|
||||
Class<?> sourceType, String sourceMethod, String description,
|
||||
Object defaultValue, ItemDeprecation deprecation) {
|
||||
public MetadataItemCondition(ItemType itemType, String name, String type, Class<?> sourceType,
|
||||
String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) {
|
||||
this.itemType = itemType;
|
||||
this.name = name;
|
||||
this.type = type;
|
||||
@@ -139,90 +138,76 @@ public final class Metadata {
|
||||
if (this.type != null && !this.type.equals(itemMetadata.getType())) {
|
||||
return false;
|
||||
}
|
||||
if (this.sourceType != null
|
||||
&& !this.sourceType.getName().equals(itemMetadata.getSourceType())) {
|
||||
if (this.sourceType != null && !this.sourceType.getName().equals(itemMetadata.getSourceType())) {
|
||||
return false;
|
||||
}
|
||||
if (this.sourceMethod != null
|
||||
&& !this.sourceMethod.equals(itemMetadata.getSourceMethod())) {
|
||||
if (this.sourceMethod != null && !this.sourceMethod.equals(itemMetadata.getSourceMethod())) {
|
||||
return false;
|
||||
}
|
||||
if (this.defaultValue != null && !ObjectUtils
|
||||
.nullSafeEquals(this.defaultValue, itemMetadata.getDefaultValue())) {
|
||||
if (this.defaultValue != null
|
||||
&& !ObjectUtils.nullSafeEquals(this.defaultValue, itemMetadata.getDefaultValue())) {
|
||||
return false;
|
||||
}
|
||||
if (this.defaultValue == null && itemMetadata.getDefaultValue() != null) {
|
||||
return false;
|
||||
}
|
||||
if (this.description != null
|
||||
&& !this.description.equals(itemMetadata.getDescription())) {
|
||||
if (this.description != null && !this.description.equals(itemMetadata.getDescription())) {
|
||||
return false;
|
||||
}
|
||||
if (this.deprecation == null && itemMetadata.getDeprecation() != null) {
|
||||
return false;
|
||||
}
|
||||
if (this.deprecation != null
|
||||
&& !this.deprecation.equals(itemMetadata.getDeprecation())) {
|
||||
if (this.deprecation != null && !this.deprecation.equals(itemMetadata.getDeprecation())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public MetadataItemCondition ofType(Class<?> dataType) {
|
||||
return new MetadataItemCondition(this.itemType, this.name, dataType.getName(),
|
||||
this.sourceType, this.sourceMethod, this.description,
|
||||
this.defaultValue, this.deprecation);
|
||||
return new MetadataItemCondition(this.itemType, this.name, dataType.getName(), this.sourceType,
|
||||
this.sourceMethod, this.description, this.defaultValue, this.deprecation);
|
||||
}
|
||||
|
||||
public MetadataItemCondition ofType(String dataType) {
|
||||
return new MetadataItemCondition(this.itemType, this.name, dataType,
|
||||
this.sourceType, this.sourceMethod, this.description,
|
||||
this.defaultValue, this.deprecation);
|
||||
return new MetadataItemCondition(this.itemType, this.name, dataType, this.sourceType, this.sourceMethod,
|
||||
this.description, this.defaultValue, this.deprecation);
|
||||
}
|
||||
|
||||
public MetadataItemCondition fromSource(Class<?> sourceType) {
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type,
|
||||
sourceType, this.sourceMethod, this.description, this.defaultValue,
|
||||
this.deprecation);
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type, sourceType, this.sourceMethod,
|
||||
this.description, this.defaultValue, this.deprecation);
|
||||
}
|
||||
|
||||
public MetadataItemCondition fromSourceMethod(String sourceMethod) {
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type,
|
||||
this.sourceType, sourceMethod, this.description, this.defaultValue,
|
||||
this.deprecation);
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, sourceMethod,
|
||||
this.description, this.defaultValue, this.deprecation);
|
||||
}
|
||||
|
||||
public MetadataItemCondition withDescription(String description) {
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type,
|
||||
this.sourceType, this.sourceMethod, description, this.defaultValue,
|
||||
this.deprecation);
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod,
|
||||
description, this.defaultValue, this.deprecation);
|
||||
}
|
||||
|
||||
public MetadataItemCondition withDefaultValue(Object defaultValue) {
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type,
|
||||
this.sourceType, this.sourceMethod, this.description, defaultValue,
|
||||
this.deprecation);
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod,
|
||||
this.description, defaultValue, this.deprecation);
|
||||
}
|
||||
|
||||
public MetadataItemCondition withDeprecation(String reason, String replacement) {
|
||||
return withDeprecation(reason, replacement, null);
|
||||
}
|
||||
|
||||
public MetadataItemCondition withDeprecation(String reason, String replacement,
|
||||
String level) {
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type,
|
||||
this.sourceType, this.sourceMethod, this.description,
|
||||
this.defaultValue, new ItemDeprecation(reason, replacement, level));
|
||||
public MetadataItemCondition withDeprecation(String reason, String replacement, String level) {
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod,
|
||||
this.description, this.defaultValue, new ItemDeprecation(reason, replacement, level));
|
||||
}
|
||||
|
||||
public MetadataItemCondition withNoDeprecation() {
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type,
|
||||
this.sourceType, this.sourceMethod, this.description,
|
||||
this.defaultValue, null);
|
||||
return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod,
|
||||
this.description, this.defaultValue, null);
|
||||
}
|
||||
|
||||
private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata,
|
||||
String name) {
|
||||
private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata, String name) {
|
||||
for (ItemMetadata item : metadata.getItems()) {
|
||||
if (item.isOfItemType(this.itemType) && name.equals(item.getName())) {
|
||||
return item;
|
||||
@@ -247,8 +232,7 @@ public final class Metadata {
|
||||
this.providerConditions = Collections.emptyList();
|
||||
}
|
||||
|
||||
public MetadataHintCondition(String name,
|
||||
List<ItemHintValueCondition> valueConditions,
|
||||
public MetadataHintCondition(String name, List<ItemHintValueCondition> valueConditions,
|
||||
List<ItemHintProviderCondition> providerConditions) {
|
||||
this.name = name;
|
||||
this.valueConditions = valueConditions;
|
||||
@@ -274,12 +258,10 @@ public final class Metadata {
|
||||
if (itemHint == null) {
|
||||
return false;
|
||||
}
|
||||
return matches(itemHint, this.valueConditions)
|
||||
&& matches(itemHint, this.providerConditions);
|
||||
return matches(itemHint, this.valueConditions) && matches(itemHint, this.providerConditions);
|
||||
}
|
||||
|
||||
private boolean matches(ItemHint itemHint,
|
||||
List<? extends Condition<ItemHint>> conditions) {
|
||||
private boolean matches(ItemHint itemHint, List<? extends Condition<ItemHint>> conditions) {
|
||||
for (Condition<ItemHint> condition : conditions) {
|
||||
if (!condition.matches(itemHint)) {
|
||||
return false;
|
||||
@@ -288,8 +270,7 @@ public final class Metadata {
|
||||
return true;
|
||||
}
|
||||
|
||||
private ItemHint getFirstHintWithName(ConfigurationMetadata metadata,
|
||||
String name) {
|
||||
private ItemHint getFirstHintWithName(ConfigurationMetadata metadata, String name) {
|
||||
for (ItemHint hint : metadata.getHints()) {
|
||||
if (name.equals(hint.getName())) {
|
||||
return hint;
|
||||
@@ -298,11 +279,9 @@ public final class Metadata {
|
||||
return null;
|
||||
}
|
||||
|
||||
public MetadataHintCondition withValue(int index, Object value,
|
||||
String description) {
|
||||
public MetadataHintCondition withValue(int index, Object value, String description) {
|
||||
return new MetadataHintCondition(this.name,
|
||||
add(this.valueConditions,
|
||||
new ItemHintValueCondition(index, value, description)),
|
||||
add(this.valueConditions, new ItemHintValueCondition(index, value, description)),
|
||||
this.providerConditions);
|
||||
}
|
||||
|
||||
@@ -310,17 +289,13 @@ public final class Metadata {
|
||||
return withProvider(this.providerConditions.size(), provider, null);
|
||||
}
|
||||
|
||||
public MetadataHintCondition withProvider(String provider, String key,
|
||||
Object value) {
|
||||
return withProvider(this.providerConditions.size(), provider,
|
||||
Collections.singletonMap(key, value));
|
||||
public MetadataHintCondition withProvider(String provider, String key, Object value) {
|
||||
return withProvider(this.providerConditions.size(), provider, Collections.singletonMap(key, value));
|
||||
}
|
||||
|
||||
public MetadataHintCondition withProvider(int index, String provider,
|
||||
Map<String, Object> parameters) {
|
||||
public MetadataHintCondition withProvider(int index, String provider, Map<String, Object> parameters) {
|
||||
return new MetadataHintCondition(this.name, this.valueConditions,
|
||||
add(this.providerConditions,
|
||||
new ItemHintProviderCondition(index, provider, parameters)));
|
||||
add(this.providerConditions, new ItemHintProviderCondition(index, provider, parameters)));
|
||||
}
|
||||
|
||||
private <T> List<T> add(List<T> items, T item) {
|
||||
@@ -367,8 +342,7 @@ public final class Metadata {
|
||||
if (this.value != null && !this.value.equals(valueHint.getValue())) {
|
||||
return false;
|
||||
}
|
||||
if (this.description != null
|
||||
&& !this.description.equals(valueHint.getDescription())) {
|
||||
if (this.description != null && !this.description.equals(valueHint.getDescription())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -384,8 +358,7 @@ public final class Metadata {
|
||||
|
||||
private final Map<String, Object> parameters;
|
||||
|
||||
ItemHintProviderCondition(int index, String name,
|
||||
Map<String, Object> parameters) {
|
||||
ItemHintProviderCondition(int index, String name, Map<String, Object> parameters) {
|
||||
this.index = index;
|
||||
this.name = name;
|
||||
this.parameters = parameters;
|
||||
|
||||
@@ -22,7 +22,6 @@ package org.springframework.boot.configurationsample.generic;
|
||||
* @param <C> mapping value type
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
public abstract class AbstractIntermediateGenericProperties<C>
|
||||
extends AbstractGenericProperties<String, Integer, C> {
|
||||
public abstract class AbstractIntermediateGenericProperties<C> extends AbstractGenericProperties<String, Integer, C> {
|
||||
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ import org.springframework.boot.configurationsample.ConfigurationProperties;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@ConfigurationProperties("generic")
|
||||
public class SimpleGenericProperties
|
||||
extends AbstractIntermediateGenericProperties<Duration> {
|
||||
public class SimpleGenericProperties extends AbstractIntermediateGenericProperties<Duration> {
|
||||
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ import org.springframework.boot.configurationsample.ConfigurationProperties;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@ConfigurationProperties("generic")
|
||||
public class UnresolvedGenericProperties<B extends Number, C>
|
||||
extends AbstractGenericProperties<String, B, C> {
|
||||
public class UnresolvedGenericProperties<B extends Number, C> extends AbstractGenericProperties<String, B, C> {
|
||||
|
||||
}
|
||||
|
||||
@@ -30,8 +30,7 @@ public class DeprecatedSingleProperty {
|
||||
private String newName;
|
||||
|
||||
@Deprecated
|
||||
@DeprecatedConfigurationProperty(reason = "renamed",
|
||||
replacement = "singledeprecated.new-name")
|
||||
@DeprecatedConfigurationProperty(reason = "renamed", replacement = "singledeprecated.new-name")
|
||||
public String getName() {
|
||||
return getNewName();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -21,8 +21,7 @@ package org.springframework.boot.configurationsample.simple;
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
public abstract class HierarchicalPropertiesParent
|
||||
extends HierarchicalPropertiesGrandparent {
|
||||
public abstract class HierarchicalPropertiesParent extends HierarchicalPropertiesGrandparent {
|
||||
|
||||
private String second;
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ buildscript {
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath("io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.9")
|
||||
classpath("io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.11")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -89,13 +89,11 @@ public class SpringBootExtension {
|
||||
* @param configurer the task configurer
|
||||
*/
|
||||
public void buildInfo(Action<BuildInfo> configurer) {
|
||||
BuildInfo bootBuildInfo = this.project.getTasks().create("bootBuildInfo",
|
||||
BuildInfo.class);
|
||||
BuildInfo bootBuildInfo = this.project.getTasks().create("bootBuildInfo", BuildInfo.class);
|
||||
bootBuildInfo.setGroup(BasePlugin.BUILD_GROUP);
|
||||
bootBuildInfo.setDescription("Generates a META-INF/build-info.properties file.");
|
||||
this.project.getPlugins().withType(JavaPlugin.class, (plugin) -> {
|
||||
this.project.getTasks().getByName(JavaPlugin.CLASSES_TASK_NAME)
|
||||
.dependsOn(bootBuildInfo);
|
||||
this.project.getTasks().getByName(JavaPlugin.CLASSES_TASK_NAME).dependsOn(bootBuildInfo);
|
||||
this.project.afterEvaluate((evaluated) -> {
|
||||
BuildInfoProperties properties = bootBuildInfo.getProperties();
|
||||
if (properties.getArtifact() == null) {
|
||||
@@ -103,8 +101,7 @@ public class SpringBootExtension {
|
||||
}
|
||||
});
|
||||
bootBuildInfo.getConventionMapping().map("destinationDir",
|
||||
() -> new File(determineMainSourceSetResourcesOutputDir(),
|
||||
"META-INF"));
|
||||
() -> new File(determineMainSourceSetResourcesOutputDir(), "META-INF"));
|
||||
});
|
||||
if (configurer != null) {
|
||||
configurer.execute(bootBuildInfo);
|
||||
@@ -112,9 +109,8 @@ public class SpringBootExtension {
|
||||
}
|
||||
|
||||
private File determineMainSourceSetResourcesOutputDir() {
|
||||
return this.project.getConvention().getPlugin(JavaPluginConvention.class)
|
||||
.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME).getOutput()
|
||||
.getResourcesDir();
|
||||
return this.project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets()
|
||||
.getByName(SourceSet.MAIN_SOURCE_SET_NAME).getOutput().getResourcesDir();
|
||||
}
|
||||
|
||||
private String determineArtifactBaseName() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -47,37 +47,31 @@ final class ApplicationPluginAction implements PluginApplicationAction {
|
||||
public void execute(Project project) {
|
||||
ApplicationPluginConvention applicationConvention = project.getConvention()
|
||||
.getPlugin(ApplicationPluginConvention.class);
|
||||
DistributionContainer distributions = project.getExtensions()
|
||||
.getByType(DistributionContainer.class);
|
||||
DistributionContainer distributions = project.getExtensions().getByType(DistributionContainer.class);
|
||||
Distribution distribution = distributions.create("boot");
|
||||
if (distribution instanceof IConventionAware) {
|
||||
((IConventionAware) distribution).getConventionMapping().map("baseName",
|
||||
() -> applicationConvention.getApplicationName() + "-boot");
|
||||
}
|
||||
CreateBootStartScripts bootStartScripts = project.getTasks()
|
||||
.create("bootStartScripts", CreateBootStartScripts.class);
|
||||
bootStartScripts.setDescription("Generates OS-specific start scripts to run the"
|
||||
+ " project as a Spring Boot application.");
|
||||
CreateBootStartScripts bootStartScripts = project.getTasks().create("bootStartScripts",
|
||||
CreateBootStartScripts.class);
|
||||
bootStartScripts.setDescription(
|
||||
"Generates OS-specific start scripts to run the" + " project as a Spring Boot application.");
|
||||
((TemplateBasedScriptGenerator) bootStartScripts.getUnixStartScriptGenerator())
|
||||
.setTemplate(project.getResources().getText()
|
||||
.fromString(loadResource("/unixStartScript.txt")));
|
||||
.setTemplate(project.getResources().getText().fromString(loadResource("/unixStartScript.txt")));
|
||||
((TemplateBasedScriptGenerator) bootStartScripts.getWindowsStartScriptGenerator())
|
||||
.setTemplate(project.getResources().getText()
|
||||
.fromString(loadResource("/windowsStartScript.txt")));
|
||||
.setTemplate(project.getResources().getText().fromString(loadResource("/windowsStartScript.txt")));
|
||||
project.getConfigurations().all((configuration) -> {
|
||||
if ("bootArchives".equals(configuration.getName())) {
|
||||
CopySpec libCopySpec = project.copySpec().into("lib")
|
||||
.from((Callable<FileCollection>) () -> configuration
|
||||
.getArtifacts().getFiles());
|
||||
.from((Callable<FileCollection>) () -> configuration.getArtifacts().getFiles());
|
||||
libCopySpec.setFileMode(0644);
|
||||
distribution.getContents().with(libCopySpec);
|
||||
bootStartScripts.setClasspath(configuration.getArtifacts().getFiles());
|
||||
}
|
||||
});
|
||||
bootStartScripts.getConventionMapping().map("outputDir",
|
||||
() -> new File(project.getBuildDir(), "bootScripts"));
|
||||
bootStartScripts.getConventionMapping().map("applicationName",
|
||||
applicationConvention::getApplicationName);
|
||||
bootStartScripts.getConventionMapping().map("outputDir", () -> new File(project.getBuildDir(), "bootScripts"));
|
||||
bootStartScripts.getConventionMapping().map("applicationName", applicationConvention::getApplicationName);
|
||||
bootStartScripts.getConventionMapping().map("defaultJvmOpts",
|
||||
applicationConvention::getApplicationDefaultJvmArgs);
|
||||
CopySpec binCopySpec = project.copySpec().into("bin").from(bootStartScripts);
|
||||
@@ -91,8 +85,7 @@ final class ApplicationPluginAction implements PluginApplicationAction {
|
||||
}
|
||||
|
||||
private String loadResource(String name) {
|
||||
try (InputStreamReader reader = new InputStreamReader(
|
||||
getClass().getResourceAsStream(name))) {
|
||||
try (InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(name))) {
|
||||
char[] buffer = new char[4096];
|
||||
int read = 0;
|
||||
StringWriter writer = new StringWriter();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -33,8 +33,7 @@ final class DependencyManagementPluginAction implements PluginApplicationAction
|
||||
@Override
|
||||
public void execute(Project project) {
|
||||
project.getExtensions().findByType(DependencyManagementExtension.class)
|
||||
.imports((importsHandler) -> importsHandler
|
||||
.mavenBom(SpringBootPlugin.BOM_COORDINATES));
|
||||
.imports((importsHandler) -> importsHandler.mavenBom(SpringBootPlugin.BOM_COORDINATES));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -77,25 +77,20 @@ final class JavaPluginAction implements PluginApplicationAction {
|
||||
}
|
||||
|
||||
private void configureBuildTask(Project project) {
|
||||
project.getTasks().getByName(BasePlugin.ASSEMBLE_TASK_NAME)
|
||||
.dependsOn(this.singlePublishedArtifact);
|
||||
project.getTasks().getByName(BasePlugin.ASSEMBLE_TASK_NAME).dependsOn(this.singlePublishedArtifact);
|
||||
}
|
||||
|
||||
private BootJar configureBootJarTask(Project project) {
|
||||
BootJar bootJar = project.getTasks().create(SpringBootPlugin.BOOT_JAR_TASK_NAME,
|
||||
BootJar.class);
|
||||
bootJar.setDescription("Assembles an executable jar archive containing the main"
|
||||
+ " classes and their dependencies.");
|
||||
BootJar bootJar = project.getTasks().create(SpringBootPlugin.BOOT_JAR_TASK_NAME, BootJar.class);
|
||||
bootJar.setDescription(
|
||||
"Assembles an executable jar archive containing the main" + " classes and their dependencies.");
|
||||
bootJar.setGroup(BasePlugin.BUILD_GROUP);
|
||||
bootJar.classpath((Callable<FileCollection>) () -> {
|
||||
JavaPluginConvention convention = project.getConvention()
|
||||
.getPlugin(JavaPluginConvention.class);
|
||||
SourceSet mainSourceSet = convention.getSourceSets()
|
||||
.getByName(SourceSet.MAIN_SOURCE_SET_NAME);
|
||||
JavaPluginConvention convention = project.getConvention().getPlugin(JavaPluginConvention.class);
|
||||
SourceSet mainSourceSet = convention.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME);
|
||||
return mainSourceSet.getRuntimeClasspath();
|
||||
});
|
||||
bootJar.conventionMapping("mainClassName",
|
||||
new MainClassConvention(project, bootJar::getClasspath));
|
||||
bootJar.conventionMapping("mainClassName", new MainClassConvention(project, bootJar::getClasspath));
|
||||
return bootJar;
|
||||
}
|
||||
|
||||
@@ -105,30 +100,26 @@ final class JavaPluginAction implements PluginApplicationAction {
|
||||
}
|
||||
|
||||
private void configureBootRunTask(Project project) {
|
||||
JavaPluginConvention javaConvention = project.getConvention()
|
||||
.getPlugin(JavaPluginConvention.class);
|
||||
JavaPluginConvention javaConvention = project.getConvention().getPlugin(JavaPluginConvention.class);
|
||||
BootRun run = project.getTasks().create("bootRun", BootRun.class);
|
||||
run.setDescription("Runs this project as a Spring Boot application.");
|
||||
run.setGroup(ApplicationPlugin.APPLICATION_GROUP);
|
||||
run.classpath(javaConvention.getSourceSets()
|
||||
.findByName(SourceSet.MAIN_SOURCE_SET_NAME).getRuntimeClasspath());
|
||||
run.classpath(javaConvention.getSourceSets().findByName(SourceSet.MAIN_SOURCE_SET_NAME).getRuntimeClasspath());
|
||||
run.getConventionMapping().map("jvmArgs", () -> {
|
||||
if (project.hasProperty("applicationDefaultJvmArgs")) {
|
||||
return project.property("applicationDefaultJvmArgs");
|
||||
}
|
||||
return Collections.emptyList();
|
||||
});
|
||||
run.conventionMapping("main",
|
||||
new MainClassConvention(project, run::getClasspath));
|
||||
run.conventionMapping("main", new MainClassConvention(project, run::getClasspath));
|
||||
}
|
||||
|
||||
private void configureUtf8Encoding(Project project) {
|
||||
project.afterEvaluate((evaluated) -> evaluated.getTasks()
|
||||
.withType(JavaCompile.class, (compile) -> {
|
||||
if (compile.getOptions().getEncoding() == null) {
|
||||
compile.getOptions().setEncoding("UTF-8");
|
||||
}
|
||||
}));
|
||||
project.afterEvaluate((evaluated) -> evaluated.getTasks().withType(JavaCompile.class, (compile) -> {
|
||||
if (compile.getOptions().getEncoding() == null) {
|
||||
compile.getOptions().setEncoding("UTF-8");
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private void configureParametersCompilerArg(Project project) {
|
||||
@@ -141,8 +132,8 @@ final class JavaPluginAction implements PluginApplicationAction {
|
||||
}
|
||||
|
||||
private void configureAdditionalMetadataLocations(Project project) {
|
||||
project.afterEvaluate((evaluated) -> evaluated.getTasks()
|
||||
.withType(JavaCompile.class, this::configureAdditionalMetadataLocations));
|
||||
project.afterEvaluate((evaluated) -> evaluated.getTasks().withType(JavaCompile.class,
|
||||
this::configureAdditionalMetadataLocations));
|
||||
}
|
||||
|
||||
private void configureAdditionalMetadataLocations(JavaCompile compile) {
|
||||
@@ -163,35 +154,27 @@ final class JavaPluginAction implements PluginApplicationAction {
|
||||
}
|
||||
JavaCompile compile = (JavaCompile) task;
|
||||
if (hasConfigurationProcessorOnClasspath(compile)) {
|
||||
findMatchingSourceSet(compile).ifPresent(
|
||||
(sourceSet) -> configureAdditionalMetadataLocations(compile,
|
||||
sourceSet));
|
||||
findMatchingSourceSet(compile)
|
||||
.ifPresent((sourceSet) -> configureAdditionalMetadataLocations(compile, sourceSet));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasConfigurationProcessorOnClasspath(JavaCompile compile) {
|
||||
Set<File> files = (compile.getOptions().getAnnotationProcessorPath() != null)
|
||||
? compile.getOptions().getAnnotationProcessorPath().getFiles()
|
||||
: compile.getClasspath().getFiles();
|
||||
return files.stream().map(File::getName).anyMatch(
|
||||
(name) -> name.startsWith("spring-boot-configuration-processor"));
|
||||
? compile.getOptions().getAnnotationProcessorPath().getFiles() : compile.getClasspath().getFiles();
|
||||
return files.stream().map(File::getName)
|
||||
.anyMatch((name) -> name.startsWith("spring-boot-configuration-processor"));
|
||||
}
|
||||
|
||||
private Optional<SourceSet> findMatchingSourceSet(JavaCompile compile) {
|
||||
return compile
|
||||
.getProject().getConvention().getPlugin(JavaPluginConvention.class)
|
||||
.getSourceSets().stream().filter((sourceSet) -> sourceSet
|
||||
.getCompileJavaTaskName().equals(compile.getName()))
|
||||
.findFirst();
|
||||
return compile.getProject().getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().stream()
|
||||
.filter((sourceSet) -> sourceSet.getCompileJavaTaskName().equals(compile.getName())).findFirst();
|
||||
}
|
||||
|
||||
private void configureAdditionalMetadataLocations(JavaCompile compile,
|
||||
SourceSet sourceSet) {
|
||||
String locations = StringUtils.collectionToCommaDelimitedString(
|
||||
sourceSet.getResources().getSrcDirs());
|
||||
compile.getOptions().getCompilerArgs().add(
|
||||
"-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations="
|
||||
+ locations);
|
||||
private void configureAdditionalMetadataLocations(JavaCompile compile, SourceSet sourceSet) {
|
||||
String locations = StringUtils.collectionToCommaDelimitedString(sourceSet.getResources().getSrcDirs());
|
||||
compile.getOptions().getCompilerArgs()
|
||||
.add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" + locations);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -33,10 +33,8 @@ class KotlinPluginAction implements PluginApplicationAction {
|
||||
|
||||
@Override
|
||||
public void execute(Project project) {
|
||||
String kotlinVersion = project.getPlugins().getPlugin(KotlinPluginWrapper.class)
|
||||
.getKotlinPluginVersion();
|
||||
ExtraPropertiesExtension extraProperties = project.getExtensions()
|
||||
.getExtraProperties();
|
||||
String kotlinVersion = project.getPlugins().getPlugin(KotlinPluginWrapper.class).getKotlinPluginVersion();
|
||||
ExtraPropertiesExtension extraProperties = project.getExtensions().getExtraProperties();
|
||||
if (!extraProperties.has("kotlin.version")) {
|
||||
extraProperties.set("kotlin.version", kotlinVersion);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -49,10 +49,8 @@ final class MainClassConvention implements Callable<Object> {
|
||||
|
||||
@Override
|
||||
public Object call() throws Exception {
|
||||
SpringBootExtension springBootExtension = this.project.getExtensions()
|
||||
.findByType(SpringBootExtension.class);
|
||||
if (springBootExtension != null
|
||||
&& springBootExtension.getMainClassName() != null) {
|
||||
SpringBootExtension springBootExtension = this.project.getExtensions().findByType(SpringBootExtension.class);
|
||||
if (springBootExtension != null && springBootExtension.getMainClassName() != null) {
|
||||
return springBootExtension.getMainClassName();
|
||||
}
|
||||
if (this.project.hasProperty("mainClassName")) {
|
||||
@@ -65,16 +63,14 @@ final class MainClassConvention implements Callable<Object> {
|
||||
}
|
||||
|
||||
private String resolveMainClass() {
|
||||
return this.classpathSupplier.get().filter(File::isDirectory).getFiles().stream()
|
||||
.map(this::findMainClass).filter(Objects::nonNull).findFirst()
|
||||
.orElseThrow(() -> new InvalidUserDataException(
|
||||
return this.classpathSupplier.get().filter(File::isDirectory).getFiles().stream().map(this::findMainClass)
|
||||
.filter(Objects::nonNull).findFirst().orElseThrow(() -> new InvalidUserDataException(
|
||||
"Main class name has not been configured and it could not be resolved"));
|
||||
}
|
||||
|
||||
private String findMainClass(File file) {
|
||||
try {
|
||||
return MainClassFinder.findSingleMainClass(file,
|
||||
SPRING_BOOT_APPLICATION_CLASS_NAME);
|
||||
return MainClassFinder.findSingleMainClass(file, SPRING_BOOT_APPLICATION_CLASS_NAME);
|
||||
}
|
||||
catch (IOException ex) {
|
||||
return null;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -85,8 +85,8 @@ public class SpringBootPlugin implements Plugin<Project> {
|
||||
|
||||
private void verifyGradleVersion() {
|
||||
if (GradleVersion.current().compareTo(GradleVersion.version("4.4")) < 0) {
|
||||
throw new GradleException("Spring Boot plugin requires Gradle 4.4 or later."
|
||||
+ " The current version is " + GradleVersion.current());
|
||||
throw new GradleException("Spring Boot plugin requires Gradle 4.4 or later." + " The current version is "
|
||||
+ GradleVersion.current());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,27 +95,20 @@ public class SpringBootPlugin implements Plugin<Project> {
|
||||
}
|
||||
|
||||
private Configuration createBootArchivesConfiguration(Project project) {
|
||||
Configuration bootArchives = project.getConfigurations()
|
||||
.create(BOOT_ARCHIVES_CONFIGURATION_NAME);
|
||||
Configuration bootArchives = project.getConfigurations().create(BOOT_ARCHIVES_CONFIGURATION_NAME);
|
||||
bootArchives.setDescription("Configuration for Spring Boot archive artifacts.");
|
||||
return bootArchives;
|
||||
}
|
||||
|
||||
private void registerPluginActions(Project project, Configuration bootArchives) {
|
||||
SinglePublishedArtifact singlePublishedArtifact = new SinglePublishedArtifact(
|
||||
bootArchives.getArtifacts());
|
||||
List<PluginApplicationAction> actions = Arrays.asList(
|
||||
new JavaPluginAction(singlePublishedArtifact),
|
||||
new WarPluginAction(singlePublishedArtifact),
|
||||
new MavenPluginAction(bootArchives.getUploadTaskName()),
|
||||
new DependencyManagementPluginAction(), new ApplicationPluginAction(),
|
||||
new KotlinPluginAction());
|
||||
SinglePublishedArtifact singlePublishedArtifact = new SinglePublishedArtifact(bootArchives.getArtifacts());
|
||||
List<PluginApplicationAction> actions = Arrays.asList(new JavaPluginAction(singlePublishedArtifact),
|
||||
new WarPluginAction(singlePublishedArtifact), new MavenPluginAction(bootArchives.getUploadTaskName()),
|
||||
new DependencyManagementPluginAction(), new ApplicationPluginAction(), new KotlinPluginAction());
|
||||
for (PluginApplicationAction action : actions) {
|
||||
Class<? extends Plugin<? extends Project>> pluginClass = action
|
||||
.getPluginClass();
|
||||
Class<? extends Plugin<? extends Project>> pluginClass = action.getPluginClass();
|
||||
if (pluginClass != null) {
|
||||
project.getPlugins().withType(pluginClass,
|
||||
(plugin) -> action.execute(project));
|
||||
project.getPlugins().withType(pluginClass, (plugin) -> action.execute(project));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,29 +119,25 @@ public class SpringBootPlugin implements Plugin<Project> {
|
||||
ResolvableDependencies incoming = configuration.getIncoming();
|
||||
incoming.afterResolve((resolvableDependencies) -> {
|
||||
if (incoming.equals(resolvableDependencies)) {
|
||||
unresolvedDependenciesAnalyzer.analyze(configuration
|
||||
.getResolvedConfiguration().getLenientConfiguration()
|
||||
.getUnresolvedModuleDependencies());
|
||||
unresolvedDependenciesAnalyzer.analyze(configuration.getResolvedConfiguration()
|
||||
.getLenientConfiguration().getUnresolvedModuleDependencies());
|
||||
}
|
||||
});
|
||||
});
|
||||
project.getGradle().buildFinished(
|
||||
(buildResult) -> unresolvedDependenciesAnalyzer.buildFinished(project));
|
||||
project.getGradle().buildFinished((buildResult) -> unresolvedDependenciesAnalyzer.buildFinished(project));
|
||||
}
|
||||
|
||||
private static String determineSpringBootVersion() {
|
||||
String implementationVersion = DependencyManagementPluginAction.class.getPackage()
|
||||
.getImplementationVersion();
|
||||
String implementationVersion = DependencyManagementPluginAction.class.getPackage().getImplementationVersion();
|
||||
if (implementationVersion != null) {
|
||||
return implementationVersion;
|
||||
}
|
||||
URL codeSourceLocation = DependencyManagementPluginAction.class
|
||||
.getProtectionDomain().getCodeSource().getLocation();
|
||||
URL codeSourceLocation = DependencyManagementPluginAction.class.getProtectionDomain().getCodeSource()
|
||||
.getLocation();
|
||||
try {
|
||||
URLConnection connection = codeSourceLocation.openConnection();
|
||||
if (connection instanceof JarURLConnection) {
|
||||
return getImplementationVersion(
|
||||
((JarURLConnection) connection).getJarFile());
|
||||
return getImplementationVersion(((JarURLConnection) connection).getJarFile());
|
||||
}
|
||||
try (JarFile jarFile = new JarFile(new File(codeSourceLocation.toURI()))) {
|
||||
return getImplementationVersion(jarFile);
|
||||
@@ -160,8 +149,7 @@ public class SpringBootPlugin implements Plugin<Project> {
|
||||
}
|
||||
|
||||
private static String getImplementationVersion(JarFile jarFile) throws IOException {
|
||||
return jarFile.getManifest().getMainAttributes()
|
||||
.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
|
||||
return jarFile.getManifest().getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -42,8 +42,8 @@ class UnresolvedDependenciesAnalyzer {
|
||||
|
||||
void analyze(Set<UnresolvedDependency> unresolvedDependencies) {
|
||||
this.dependenciesWithNoVersion = unresolvedDependencies.stream()
|
||||
.map((unresolvedDependency) -> unresolvedDependency.getSelector())
|
||||
.filter(this::hasNoVersion).collect(Collectors.toSet());
|
||||
.map((unresolvedDependency) -> unresolvedDependency.getSelector()).filter(this::hasNoVersion)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
void buildFinished(Project project) {
|
||||
@@ -52,11 +52,9 @@ class UnresolvedDependenciesAnalyzer {
|
||||
StringBuilder message = new StringBuilder();
|
||||
message.append("\nDuring the build, one or more dependencies that were "
|
||||
+ "declared without a version failed to resolve:\n");
|
||||
this.dependenciesWithNoVersion
|
||||
.forEach((dependency) -> message.append(" " + dependency + "\n"));
|
||||
message.append("\nDid you forget to apply the "
|
||||
+ "io.spring.dependency-management plugin to the " + project.getName()
|
||||
+ " project?\n");
|
||||
this.dependenciesWithNoVersion.forEach((dependency) -> message.append(" " + dependency + "\n"));
|
||||
message.append("\nDid you forget to apply the " + "io.spring.dependency-management plugin to the "
|
||||
+ project.getName() + " project?\n");
|
||||
logger.warn(message.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -47,21 +47,18 @@ class WarPluginAction implements PluginApplicationAction {
|
||||
@Override
|
||||
public void execute(Project project) {
|
||||
project.getTasks().getByName(WarPlugin.WAR_TASK_NAME).setEnabled(false);
|
||||
BootWar bootWar = project.getTasks().create(SpringBootPlugin.BOOT_WAR_TASK_NAME,
|
||||
BootWar.class);
|
||||
BootWar bootWar = project.getTasks().create(SpringBootPlugin.BOOT_WAR_TASK_NAME, BootWar.class);
|
||||
bootWar.setGroup(BasePlugin.BUILD_GROUP);
|
||||
bootWar.setDescription("Assembles an executable war archive containing webapp"
|
||||
+ " content, and the main classes and their dependencies.");
|
||||
bootWar.providedClasspath(providedRuntimeConfiguration(project));
|
||||
ArchivePublishArtifact artifact = new ArchivePublishArtifact(bootWar);
|
||||
this.singlePublishedArtifact.addCandidate(artifact);
|
||||
bootWar.conventionMapping("mainClassName",
|
||||
new MainClassConvention(project, bootWar::getClasspath));
|
||||
bootWar.conventionMapping("mainClassName", new MainClassConvention(project, bootWar::getClasspath));
|
||||
}
|
||||
|
||||
private Configuration providedRuntimeConfiguration(Project project) {
|
||||
return project.getConfigurations()
|
||||
.getByName(WarPlugin.PROVIDED_RUNTIME_CONFIGURATION_NAME);
|
||||
return project.getConfigurations().getByName(WarPlugin.PROVIDED_RUNTIME_CONFIGURATION_NAME);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -53,14 +53,13 @@ public class BuildInfo extends ConventionTask {
|
||||
@TaskAction
|
||||
public void generateBuildProperties() {
|
||||
try {
|
||||
new BuildPropertiesWriter(new File(getDestinationDir(),
|
||||
"build-info.properties")).writeBuildProperties(new ProjectDetails(
|
||||
this.properties.getGroup(),
|
||||
(this.properties.getArtifact() != null)
|
||||
? this.properties.getArtifact() : "unspecified",
|
||||
this.properties.getVersion(), this.properties.getName(),
|
||||
this.properties.getTime(),
|
||||
coerceToStringValues(this.properties.getAdditional())));
|
||||
new BuildPropertiesWriter(new File(getDestinationDir(), "build-info.properties"))
|
||||
.writeBuildProperties(
|
||||
new ProjectDetails(this.properties.getGroup(),
|
||||
(this.properties.getArtifact() != null) ? this.properties.getArtifact()
|
||||
: "unspecified",
|
||||
this.properties.getVersion(), this.properties.getName(), this.properties.getTime(),
|
||||
coerceToStringValues(this.properties.getAdditional())));
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new TaskExecutionException(this, ex);
|
||||
@@ -74,8 +73,7 @@ public class BuildInfo extends ConventionTask {
|
||||
*/
|
||||
@OutputDirectory
|
||||
public File getDestinationDir() {
|
||||
return (this.destinationDir != null) ? this.destinationDir
|
||||
: getProject().getBuildDir();
|
||||
return (this.destinationDir != null) ? this.destinationDir : getProject().getBuildDir();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -172,8 +172,7 @@ public class BuildInfoProperties implements Serializable {
|
||||
}
|
||||
BuildInfoProperties other = (BuildInfoProperties) obj;
|
||||
boolean result = true;
|
||||
result = result
|
||||
&& nullSafeEquals(this.additionalProperties, other.additionalProperties);
|
||||
result = result && nullSafeEquals(this.additionalProperties, other.additionalProperties);
|
||||
result = result && nullSafeEquals(this.artifact, other.artifact);
|
||||
result = result && nullSafeEquals(this.group, other.group);
|
||||
result = result && nullSafeEquals(this.name, other.name);
|
||||
@@ -196,10 +195,8 @@ public class BuildInfoProperties implements Serializable {
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((this.additionalProperties == null) ? 0
|
||||
: this.additionalProperties.hashCode());
|
||||
result = prime * result
|
||||
+ ((this.artifact == null) ? 0 : this.artifact.hashCode());
|
||||
result = prime * result + ((this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode());
|
||||
result = prime * result + ((this.artifact == null) ? 0 : this.artifact.hashCode());
|
||||
result = prime * result + ((this.group == null) ? 0 : this.group.hashCode());
|
||||
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
|
||||
result = prime * result + ((this.version == null) ? 0 : this.version.hashCode());
|
||||
|
||||
@@ -71,21 +71,18 @@ class BootArchiveSupport {
|
||||
|
||||
private boolean excludeDevtools = true;
|
||||
|
||||
BootArchiveSupport(String loaderMainClass,
|
||||
Function<FileCopyDetails, ZipCompression> compressionResolver) {
|
||||
BootArchiveSupport(String loaderMainClass, Function<FileCopyDetails, ZipCompression> compressionResolver) {
|
||||
this.loaderMainClass = loaderMainClass;
|
||||
this.compressionResolver = compressionResolver;
|
||||
this.requiresUnpack.include(Specs.satisfyNone());
|
||||
configureExclusions();
|
||||
}
|
||||
|
||||
void configureManifest(Jar jar, String mainClassName, String springBootClasses,
|
||||
String springBootLib) {
|
||||
void configureManifest(Jar jar, String mainClassName, String springBootClasses, String springBootLib) {
|
||||
Attributes attributes = jar.getManifest().getAttributes();
|
||||
attributes.putIfAbsent("Main-Class", this.loaderMainClass);
|
||||
attributes.putIfAbsent("Start-Class", mainClassName);
|
||||
attributes.computeIfAbsent("Spring-Boot-Version",
|
||||
(key) -> determineSpringBootVersion());
|
||||
attributes.computeIfAbsent("Spring-Boot-Version", (key) -> determineSpringBootVersion());
|
||||
attributes.putIfAbsent("Spring-Boot-Classes", springBootClasses);
|
||||
attributes.putIfAbsent("Spring-Boot-Lib", springBootLib);
|
||||
}
|
||||
@@ -96,9 +93,8 @@ class BootArchiveSupport {
|
||||
}
|
||||
|
||||
CopyAction createCopyAction(Jar jar) {
|
||||
CopyAction copyAction = new BootZipCopyAction(jar.getArchivePath(),
|
||||
jar.isPreserveFileTimestamps(), isUsingDefaultLoader(jar),
|
||||
this.requiresUnpack.getAsSpec(), this.exclusions.getAsExcludeSpec(),
|
||||
CopyAction copyAction = new BootZipCopyAction(jar.getArchivePath(), jar.isPreserveFileTimestamps(),
|
||||
isUsingDefaultLoader(jar), this.requiresUnpack.getAsSpec(), this.exclusions.getAsExcludeSpec(),
|
||||
this.launchScript, this.compressionResolver, jar.getMetadataCharset());
|
||||
if (!jar.isReproducibleFileOrder()) {
|
||||
return copyAction;
|
||||
@@ -107,8 +103,7 @@ class BootArchiveSupport {
|
||||
}
|
||||
|
||||
private boolean isUsingDefaultLoader(Jar jar) {
|
||||
return DEFAULT_LAUNCHER_CLASSES
|
||||
.contains(jar.getManifest().getAttributes().get("Main-Class"));
|
||||
return DEFAULT_LAUNCHER_CLASSES.contains(jar.getManifest().getAttributes().get("Main-Class"));
|
||||
}
|
||||
|
||||
LaunchScriptConfiguration getLaunchScript() {
|
||||
@@ -176,8 +171,7 @@ class BootArchiveSupport {
|
||||
public WorkResult execute(CopyActionProcessingStream stream) {
|
||||
return this.delegate.execute((action) -> {
|
||||
Map<RelativePath, FileCopyDetailsInternal> detailsByPath = new TreeMap<>();
|
||||
stream.process((details) -> detailsByPath.put(details.getRelativePath(),
|
||||
details));
|
||||
stream.process((details) -> detailsByPath.put(details.getRelativePath(), details));
|
||||
detailsByPath.values().forEach(action::processFile);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -38,8 +38,8 @@ import org.gradle.api.tasks.bundling.Jar;
|
||||
*/
|
||||
public class BootJar extends Jar implements BootArchive {
|
||||
|
||||
private final BootArchiveSupport support = new BootArchiveSupport(
|
||||
"org.springframework.boot.loader.JarLauncher", this::resolveZipCompression);
|
||||
private final BootArchiveSupport support = new BootArchiveSupport("org.springframework.boot.loader.JarLauncher",
|
||||
this::resolveZipCompression);
|
||||
|
||||
private final CopySpec bootInf;
|
||||
|
||||
@@ -59,23 +59,20 @@ public class BootJar extends Jar implements BootArchive {
|
||||
(details) -> details.setRelativePath(details.getRelativeSourcePath()));
|
||||
getRootSpec().eachFile((details) -> {
|
||||
String pathString = details.getRelativePath().getPathString();
|
||||
if (pathString.startsWith("BOOT-INF/lib/")
|
||||
&& !this.support.isZip(details.getFile())) {
|
||||
if (pathString.startsWith("BOOT-INF/lib/") && !this.support.isZip(details.getFile())) {
|
||||
details.exclude();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Action<CopySpec> classpathFiles(Spec<File> filter) {
|
||||
return (copySpec) -> copySpec
|
||||
.from((Callable<Iterable<File>>) () -> (this.classpath != null)
|
||||
? this.classpath.filter(filter) : Collections.emptyList());
|
||||
return (copySpec) -> copySpec.from((Callable<Iterable<File>>) () -> (this.classpath != null)
|
||||
? this.classpath.filter(filter) : Collections.emptyList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void copy() {
|
||||
this.support.configureManifest(this, getMainClassName(), "BOOT-INF/classes/",
|
||||
"BOOT-INF/lib/");
|
||||
this.support.configureManifest(this, getMainClassName(), "BOOT-INF/classes/", "BOOT-INF/lib/");
|
||||
super.copy();
|
||||
}
|
||||
|
||||
@@ -87,8 +84,7 @@ public class BootJar extends Jar implements BootArchive {
|
||||
@Override
|
||||
public String getMainClassName() {
|
||||
if (this.mainClassName == null) {
|
||||
String manifestStartClass = (String) getManifest().getAttributes()
|
||||
.get("Start-Class");
|
||||
String manifestStartClass = (String) getManifest().getAttributes().get("Start-Class");
|
||||
if (manifestStartClass != null) {
|
||||
setMainClassName(manifestStartClass);
|
||||
}
|
||||
@@ -134,8 +130,7 @@ public class BootJar extends Jar implements BootArchive {
|
||||
@Override
|
||||
public void classpath(Object... classpath) {
|
||||
FileCollection existingClasspath = this.classpath;
|
||||
this.classpath = getProject().files(
|
||||
(existingClasspath != null) ? existingClasspath : Collections.emptyList(),
|
||||
this.classpath = getProject().files((existingClasspath != null) ? existingClasspath : Collections.emptyList(),
|
||||
classpath);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,8 @@ import org.gradle.api.tasks.bundling.War;
|
||||
*/
|
||||
public class BootWar extends War implements BootArchive {
|
||||
|
||||
private final BootArchiveSupport support = new BootArchiveSupport(
|
||||
"org.springframework.boot.loader.WarLauncher", this::resolveZipCompression);
|
||||
private final BootArchiveSupport support = new BootArchiveSupport("org.springframework.boot.loader.WarLauncher",
|
||||
this::resolveZipCompression);
|
||||
|
||||
private String mainClassName;
|
||||
|
||||
@@ -51,15 +51,13 @@ public class BootWar extends War implements BootArchive {
|
||||
*/
|
||||
public BootWar() {
|
||||
getWebInf().into("lib-provided",
|
||||
(copySpec) -> copySpec.from(
|
||||
(Callable<Iterable<File>>) () -> (this.providedClasspath != null)
|
||||
? this.providedClasspath : Collections.emptyList()));
|
||||
(copySpec) -> copySpec.from((Callable<Iterable<File>>) () -> (this.providedClasspath != null)
|
||||
? this.providedClasspath : Collections.emptyList()));
|
||||
getRootSpec().filesMatching("module-info.class",
|
||||
(details) -> details.setRelativePath(details.getRelativeSourcePath()));
|
||||
getRootSpec().eachFile((details) -> {
|
||||
String pathString = details.getRelativePath().getPathString();
|
||||
if ((pathString.startsWith("WEB-INF/lib/")
|
||||
|| pathString.startsWith("WEB-INF/lib-provided/"))
|
||||
if ((pathString.startsWith("WEB-INF/lib/") || pathString.startsWith("WEB-INF/lib-provided/"))
|
||||
&& !this.support.isZip(details.getFile())) {
|
||||
details.exclude();
|
||||
}
|
||||
@@ -68,8 +66,7 @@ public class BootWar extends War implements BootArchive {
|
||||
|
||||
@Override
|
||||
public void copy() {
|
||||
this.support.configureManifest(this, getMainClassName(), "WEB-INF/classes/",
|
||||
"WEB-INF/lib/");
|
||||
this.support.configureManifest(this, getMainClassName(), "WEB-INF/classes/", "WEB-INF/lib/");
|
||||
super.copy();
|
||||
}
|
||||
|
||||
@@ -81,8 +78,7 @@ public class BootWar extends War implements BootArchive {
|
||||
@Override
|
||||
public String getMainClassName() {
|
||||
if (this.mainClassName == null) {
|
||||
String manifestStartClass = (String) getManifest().getAttributes()
|
||||
.get("Start-Class");
|
||||
String manifestStartClass = (String) getManifest().getAttributes().get("Start-Class");
|
||||
if (manifestStartClass != null) {
|
||||
setMainClassName(manifestStartClass);
|
||||
}
|
||||
@@ -139,9 +135,8 @@ public class BootWar extends War implements BootArchive {
|
||||
*/
|
||||
public void providedClasspath(Object... classpath) {
|
||||
FileCollection existingClasspath = this.providedClasspath;
|
||||
this.providedClasspath = getProject().files(
|
||||
(existingClasspath != null) ? existingClasspath : Collections.emptyList(),
|
||||
classpath);
|
||||
this.providedClasspath = getProject()
|
||||
.files((existingClasspath != null) ? existingClasspath : Collections.emptyList(), classpath);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -186,8 +181,7 @@ public class BootWar extends War implements BootArchive {
|
||||
*/
|
||||
protected ZipCompression resolveZipCompression(FileCopyDetails details) {
|
||||
String relativePath = details.getRelativePath().getPathString();
|
||||
if (relativePath.startsWith("WEB-INF/lib/")
|
||||
|| relativePath.startsWith("WEB-INF/lib-provided/")) {
|
||||
if (relativePath.startsWith("WEB-INF/lib/") || relativePath.startsWith("WEB-INF/lib-provided/")) {
|
||||
return ZipCompression.STORED;
|
||||
}
|
||||
return ZipCompression.DEFLATED;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -53,8 +53,8 @@ import org.springframework.boot.loader.tools.FileUtils;
|
||||
*/
|
||||
class BootZipCopyAction implements CopyAction {
|
||||
|
||||
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = new GregorianCalendar(1980,
|
||||
Calendar.FEBRUARY, 1, 0, 0, 0).getTimeInMillis();
|
||||
static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = new GregorianCalendar(1980, Calendar.FEBRUARY, 1, 0, 0, 0)
|
||||
.getTimeInMillis();
|
||||
|
||||
private final File output;
|
||||
|
||||
@@ -72,10 +72,9 @@ class BootZipCopyAction implements CopyAction {
|
||||
|
||||
private final String encoding;
|
||||
|
||||
BootZipCopyAction(File output, boolean preserveFileTimestamps,
|
||||
boolean includeDefaultLoader, Spec<FileTreeElement> requiresUnpack,
|
||||
Spec<FileTreeElement> exclusions, LaunchScriptConfiguration launchScript,
|
||||
Function<FileCopyDetails, ZipCompression> compressionResolver,
|
||||
BootZipCopyAction(File output, boolean preserveFileTimestamps, boolean includeDefaultLoader,
|
||||
Spec<FileTreeElement> requiresUnpack, Spec<FileTreeElement> exclusions,
|
||||
LaunchScriptConfiguration launchScript, Function<FileCopyDetails, ZipCompression> compressionResolver,
|
||||
String encoding) {
|
||||
this.output = output;
|
||||
this.preserveFileTimestamps = preserveFileTimestamps;
|
||||
@@ -104,8 +103,7 @@ class BootZipCopyAction implements CopyAction {
|
||||
throw new GradleException("Failed to create " + this.output, ex);
|
||||
}
|
||||
try {
|
||||
stream.process(new ZipStreamAction(zipStream, this.output,
|
||||
this.preserveFileTimestamps, this.requiresUnpack,
|
||||
stream.process(new ZipStreamAction(zipStream, this.output, this.preserveFileTimestamps, this.requiresUnpack,
|
||||
createExclusionSpec(loaderEntries), this.compressionResolver));
|
||||
}
|
||||
finally {
|
||||
@@ -120,13 +118,11 @@ class BootZipCopyAction implements CopyAction {
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Spec<FileTreeElement> createExclusionSpec(
|
||||
Spec<FileTreeElement> loaderEntries) {
|
||||
private Spec<FileTreeElement> createExclusionSpec(Spec<FileTreeElement> loaderEntries) {
|
||||
return Specs.union(loaderEntries, this.exclusions);
|
||||
}
|
||||
|
||||
private Spec<FileTreeElement> writeLoaderClassesIfNecessary(
|
||||
ZipArchiveOutputStream out) {
|
||||
private Spec<FileTreeElement> writeLoaderClassesIfNecessary(ZipArchiveOutputStream out) {
|
||||
if (!this.includeDefaultLoader) {
|
||||
return Specs.satisfyNone();
|
||||
}
|
||||
@@ -134,8 +130,8 @@ class BootZipCopyAction implements CopyAction {
|
||||
}
|
||||
|
||||
private Spec<FileTreeElement> writeLoaderClasses(ZipArchiveOutputStream out) {
|
||||
try (ZipInputStream in = new ZipInputStream(getClass()
|
||||
.getResourceAsStream("/META-INF/loader/spring-boot-loader.jar"))) {
|
||||
try (ZipInputStream in = new ZipInputStream(
|
||||
getClass().getResourceAsStream("/META-INF/loader/spring-boot-loader.jar"))) {
|
||||
Set<String> entries = new HashSet<>();
|
||||
java.util.zip.ZipEntry entry;
|
||||
while ((entry = in.getNextEntry()) != null) {
|
||||
@@ -160,15 +156,13 @@ class BootZipCopyAction implements CopyAction {
|
||||
}
|
||||
}
|
||||
|
||||
private void writeDirectory(ZipArchiveEntry entry, ZipArchiveOutputStream out)
|
||||
throws IOException {
|
||||
private void writeDirectory(ZipArchiveEntry entry, ZipArchiveOutputStream out) throws IOException {
|
||||
prepareEntry(entry, UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM);
|
||||
out.putArchiveEntry(entry);
|
||||
out.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private void writeClass(ZipArchiveEntry entry, ZipInputStream in,
|
||||
ZipArchiveOutputStream out) throws IOException {
|
||||
private void writeClass(ZipArchiveEntry entry, ZipInputStream in, ZipArchiveOutputStream out) throws IOException {
|
||||
prepareEntry(entry, UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM);
|
||||
out.putArchiveEntry(entry);
|
||||
byte[] buffer = new byte[4096];
|
||||
@@ -189,19 +183,18 @@ class BootZipCopyAction implements CopyAction {
|
||||
private void writeLaunchScriptIfNecessary(FileOutputStream fileStream) {
|
||||
try {
|
||||
if (this.launchScript != null) {
|
||||
fileStream.write(new DefaultLaunchScript(this.launchScript.getScript(),
|
||||
this.launchScript.getProperties()).toByteArray());
|
||||
fileStream
|
||||
.write(new DefaultLaunchScript(this.launchScript.getScript(), this.launchScript.getProperties())
|
||||
.toByteArray());
|
||||
this.output.setExecutable(true);
|
||||
}
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new GradleException("Failed to write launch script to " + this.output,
|
||||
ex);
|
||||
throw new GradleException("Failed to write launch script to " + this.output, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ZipStreamAction
|
||||
implements CopyActionProcessingStreamAction {
|
||||
private static final class ZipStreamAction implements CopyActionProcessingStreamAction {
|
||||
|
||||
private final ZipArchiveOutputStream zipStream;
|
||||
|
||||
@@ -215,9 +208,8 @@ class BootZipCopyAction implements CopyAction {
|
||||
|
||||
private final Function<FileCopyDetails, ZipCompression> compressionType;
|
||||
|
||||
private ZipStreamAction(ZipArchiveOutputStream zipStream, File output,
|
||||
boolean preserveFileTimestamps, Spec<FileTreeElement> requiresUnpack,
|
||||
Spec<FileTreeElement> exclusions,
|
||||
private ZipStreamAction(ZipArchiveOutputStream zipStream, File output, boolean preserveFileTimestamps,
|
||||
Spec<FileTreeElement> requiresUnpack, Spec<FileTreeElement> exclusions,
|
||||
Function<FileCopyDetails, ZipCompression> compressionType) {
|
||||
this.zipStream = zipStream;
|
||||
this.output = output;
|
||||
@@ -241,14 +233,12 @@ class BootZipCopyAction implements CopyAction {
|
||||
}
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new GradleException(
|
||||
"Failed to add " + details + " to " + this.output, ex);
|
||||
throw new GradleException("Failed to add " + details + " to " + this.output, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void createDirectory(FileCopyDetailsInternal details) throws IOException {
|
||||
ZipArchiveEntry archiveEntry = new ZipArchiveEntry(
|
||||
details.getRelativePath().getPathString() + '/');
|
||||
ZipArchiveEntry archiveEntry = new ZipArchiveEntry(details.getRelativePath().getPathString() + '/');
|
||||
archiveEntry.setUnixMode(UnixStat.DIR_FLAG | details.getMode());
|
||||
archiveEntry.setTime(getTime(details));
|
||||
this.zipStream.putArchiveEntry(archiveEntry);
|
||||
@@ -269,8 +259,8 @@ class BootZipCopyAction implements CopyAction {
|
||||
this.zipStream.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private void prepareStoredEntry(FileCopyDetailsInternal details,
|
||||
ZipArchiveEntry archiveEntry) throws IOException {
|
||||
private void prepareStoredEntry(FileCopyDetailsInternal details, ZipArchiveEntry archiveEntry)
|
||||
throws IOException {
|
||||
archiveEntry.setMethod(java.util.zip.ZipEntry.STORED);
|
||||
archiveEntry.setSize(details.getSize());
|
||||
archiveEntry.setCompressedSize(details.getSize());
|
||||
@@ -278,14 +268,12 @@ class BootZipCopyAction implements CopyAction {
|
||||
details.copyTo(crcStream);
|
||||
archiveEntry.setCrc(crcStream.getCrc());
|
||||
if (this.requiresUnpack.isSatisfiedBy(details)) {
|
||||
archiveEntry
|
||||
.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
|
||||
archiveEntry.setComment("UNPACK:" + FileUtils.sha1Hash(details.getFile()));
|
||||
}
|
||||
}
|
||||
|
||||
private long getTime(FileCopyDetails details) {
|
||||
return this.preserveFileTimestamps ? details.getLastModified()
|
||||
: CONSTANT_TIME_FOR_ZIP_ENTRIES;
|
||||
return this.preserveFileTimestamps ? details.getLastModified() : CONSTANT_TIME_FOR_ZIP_ENTRIES;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -51,10 +51,10 @@ public class LaunchScriptConfiguration implements Serializable {
|
||||
LaunchScriptConfiguration(AbstractArchiveTask archiveTask) {
|
||||
Project project = archiveTask.getProject();
|
||||
putIfMissing(this.properties, "initInfoProvides", archiveTask.getBaseName());
|
||||
putIfMissing(this.properties, "initInfoShortDescription",
|
||||
removeLineBreaks(project.getDescription()), archiveTask.getBaseName());
|
||||
putIfMissing(this.properties, "initInfoDescription",
|
||||
augmentLineBreaks(project.getDescription()), archiveTask.getBaseName());
|
||||
putIfMissing(this.properties, "initInfoShortDescription", removeLineBreaks(project.getDescription()),
|
||||
archiveTask.getBaseName());
|
||||
putIfMissing(this.properties, "initInfoDescription", augmentLineBreaks(project.getDescription()),
|
||||
archiveTask.getBaseName());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,24 +132,20 @@ public class LaunchScriptConfiguration implements Serializable {
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result
|
||||
+ ((this.properties == null) ? 0 : this.properties.hashCode());
|
||||
result = prime * result + ((this.properties == null) ? 0 : this.properties.hashCode());
|
||||
result = prime * result + ((this.script == null) ? 0 : this.script.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
private String removeLineBreaks(String string) {
|
||||
return (string != null) ? WHITE_SPACE_PATTERN.matcher(string).replaceAll(" ")
|
||||
: null;
|
||||
return (string != null) ? WHITE_SPACE_PATTERN.matcher(string).replaceAll(" ") : null;
|
||||
}
|
||||
|
||||
private String augmentLineBreaks(String string) {
|
||||
return (string != null) ? LINE_FEED_PATTERN.matcher(string).replaceAll("\n# ")
|
||||
: null;
|
||||
return (string != null) ? LINE_FEED_PATTERN.matcher(string).replaceAll("\n# ") : null;
|
||||
}
|
||||
|
||||
private void putIfMissing(Map<String, String> properties, String key,
|
||||
String... valueCandidates) {
|
||||
private void putIfMissing(Map<String, String> properties, String key, String... valueCandidates) {
|
||||
if (!properties.containsKey(key)) {
|
||||
for (String candidate : valueCandidates) {
|
||||
if (candidate != null && !candidate.isEmpty()) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -37,8 +37,7 @@ public class BootRun extends JavaExec {
|
||||
* @param sourceSet the source set
|
||||
*/
|
||||
public void sourceResources(SourceSet sourceSet) {
|
||||
setClasspath(getProject()
|
||||
.files(sourceSet.getResources().getSrcDirs(), getClasspath())
|
||||
setClasspath(getProject().files(sourceSet.getResources().getSrcDirs(), getClasspath())
|
||||
.filter((file) -> !file.equals(sourceSet.getOutput().getResourcesDir())));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -32,8 +32,7 @@ public class BootRunApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
int i = 1;
|
||||
for (String entry : ManagementFactory.getRuntimeMXBean().getClassPath()
|
||||
.split(File.pathSeparator)) {
|
||||
for (String entry : ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) {
|
||||
System.out.println(i++ + ". " + entry);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -40,8 +40,7 @@ public class GettingStartedDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void typicalPluginsAppliesExceptedPlugins() {
|
||||
this.gradleBuild.script("src/main/gradle/getting-started/typical-plugins")
|
||||
.build("verify");
|
||||
this.gradleBuild.script("src/main/gradle/getting-started/typical-plugins").build("verify");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -44,20 +44,16 @@ public class IntegratingWithActuatorDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void basicBuildInfo() throws IOException {
|
||||
this.gradleBuild
|
||||
.script("src/main/gradle/integrating-with-actuator/build-info-basic")
|
||||
.build("bootBuildInfo");
|
||||
assertThat(new File(this.gradleBuild.getProjectDir(),
|
||||
"build/resources/main/META-INF/build-info.properties")).isFile();
|
||||
this.gradleBuild.script("src/main/gradle/integrating-with-actuator/build-info-basic").build("bootBuildInfo");
|
||||
assertThat(new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties"))
|
||||
.isFile();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void buildInfoCustomValues() throws IOException {
|
||||
this.gradleBuild.script(
|
||||
"src/main/gradle/integrating-with-actuator/build-info-custom-values")
|
||||
this.gradleBuild.script("src/main/gradle/integrating-with-actuator/build-info-custom-values")
|
||||
.build("bootBuildInfo");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/resources/main/META-INF/build-info.properties");
|
||||
File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties");
|
||||
assertThat(file).isFile();
|
||||
Properties properties = buildInfoProperties(file);
|
||||
assertThat(properties).containsEntry("build.artifact", "example-app");
|
||||
@@ -68,11 +64,9 @@ public class IntegratingWithActuatorDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void buildInfoAdditional() throws IOException {
|
||||
this.gradleBuild
|
||||
.script("src/main/gradle/integrating-with-actuator/build-info-additional")
|
||||
this.gradleBuild.script("src/main/gradle/integrating-with-actuator/build-info-additional")
|
||||
.build("bootBuildInfo");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/resources/main/META-INF/build-info.properties");
|
||||
File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties");
|
||||
assertThat(file).isFile();
|
||||
Properties properties = buildInfoProperties(file);
|
||||
assertThat(properties).containsEntry("build.a", "alpha");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -41,32 +41,26 @@ public class ManagingDependenciesDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void dependenciesExampleEvaluatesSuccessfully() {
|
||||
this.gradleBuild.script("src/main/gradle/managing-dependencies/dependencies")
|
||||
.build();
|
||||
this.gradleBuild.script("src/main/gradle/managing-dependencies/dependencies").build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customManagedVersions() {
|
||||
assertThat(this.gradleBuild
|
||||
.script("src/main/gradle/managing-dependencies/custom-version")
|
||||
.build("slf4jVersion").getOutput()).contains("1.7.20");
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/managing-dependencies/custom-version").build("slf4jVersion")
|
||||
.getOutput()).contains("1.7.20");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dependencyManagementInIsolation() {
|
||||
assertThat(this.gradleBuild
|
||||
.script("src/main/gradle/managing-dependencies/configure-bom")
|
||||
.build("dependencyManagement").getOutput())
|
||||
.contains("org.springframework.boot:spring-boot-starter ");
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/managing-dependencies/configure-bom")
|
||||
.build("dependencyManagement").getOutput()).contains("org.springframework.boot:spring-boot-starter ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dependencyManagementInIsolationWithPluginsBlock() {
|
||||
Assume.assumeTrue(this.gradleBuild.getDsl() == Dsl.KOTLIN);
|
||||
assertThat(this.gradleBuild.script(
|
||||
"src/main/gradle/managing-dependencies/configure-bom-with-plugins")
|
||||
.build("dependencyManagement").getOutput())
|
||||
.contains("org.springframework.boot:spring-boot-starter ");
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/managing-dependencies/configure-bom-with-plugins")
|
||||
.build("dependencyManagement").getOutput()).contains("org.springframework.boot:spring-boot-starter ");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -54,14 +54,12 @@ public class PackagingDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void warContainerDependencyEvaluatesSuccessfully() {
|
||||
this.gradleBuild.script("src/main/gradle/packaging/war-container-dependency")
|
||||
.build();
|
||||
this.gradleBuild.script("src/main/gradle/packaging/war-container-dependency").build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bootJarMainClass() throws IOException {
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-main-class")
|
||||
.build("bootJar");
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-main-class").build("bootJar");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar");
|
||||
assertThat(file).isFile();
|
||||
@@ -73,8 +71,7 @@ public class PackagingDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void bootJarManifestMainClass() throws IOException {
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-manifest-main-class")
|
||||
.build("bootJar");
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-manifest-main-class").build("bootJar");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar");
|
||||
assertThat(file).isFile();
|
||||
@@ -86,8 +83,7 @@ public class PackagingDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void applicationPluginMainClass() throws IOException {
|
||||
this.gradleBuild.script("src/main/gradle/packaging/application-plugin-main-class")
|
||||
.build("bootJar");
|
||||
this.gradleBuild.script("src/main/gradle/packaging/application-plugin-main-class").build("bootJar");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar");
|
||||
assertThat(file).isFile();
|
||||
@@ -99,8 +95,7 @@ public class PackagingDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void springBootDslMainClass() throws IOException {
|
||||
this.gradleBuild.script("src/main/gradle/packaging/spring-boot-dsl-main-class")
|
||||
.build("bootJar");
|
||||
this.gradleBuild.script("src/main/gradle/packaging/spring-boot-dsl-main-class").build("bootJar");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar");
|
||||
assertThat(file).isFile();
|
||||
@@ -112,23 +107,19 @@ public class PackagingDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void bootWarIncludeDevtools() throws IOException {
|
||||
jarFile(new File(this.gradleBuild.getProjectDir(),
|
||||
"spring-boot-devtools-1.2.3.RELEASE.jar"));
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-war-include-devtools")
|
||||
.build("bootWar");
|
||||
jarFile(new File(this.gradleBuild.getProjectDir(), "spring-boot-devtools-1.2.3.RELEASE.jar"));
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-war-include-devtools").build("bootWar");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".war");
|
||||
assertThat(file).isFile();
|
||||
try (JarFile jar = new JarFile(file)) {
|
||||
assertThat(jar.getEntry("WEB-INF/lib/spring-boot-devtools-1.2.3.RELEASE.jar"))
|
||||
.isNotNull();
|
||||
assertThat(jar.getEntry("WEB-INF/lib/spring-boot-devtools-1.2.3.RELEASE.jar")).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bootJarRequiresUnpack() throws IOException {
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-requires-unpack")
|
||||
.build("bootJar");
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-requires-unpack").build("bootJar");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar");
|
||||
assertThat(file).isFile();
|
||||
@@ -141,36 +132,28 @@ public class PackagingDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void bootJarIncludeLaunchScript() throws IOException {
|
||||
this.gradleBuild
|
||||
.script("src/main/gradle/packaging/boot-jar-include-launch-script")
|
||||
.build("bootJar");
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-include-launch-script").build("bootJar");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar");
|
||||
assertThat(file).isFile();
|
||||
assertThat(FileCopyUtils.copyToString(new FileReader(file)))
|
||||
.startsWith("#!/bin/bash");
|
||||
assertThat(FileCopyUtils.copyToString(new FileReader(file))).startsWith("#!/bin/bash");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bootJarLaunchScriptProperties() throws IOException {
|
||||
this.gradleBuild
|
||||
.script("src/main/gradle/packaging/boot-jar-launch-script-properties")
|
||||
.build("bootJar");
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-launch-script-properties").build("bootJar");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar");
|
||||
assertThat(file).isFile();
|
||||
assertThat(FileCopyUtils.copyToString(new FileReader(file)))
|
||||
.contains("example-app.log");
|
||||
assertThat(FileCopyUtils.copyToString(new FileReader(file))).contains("example-app.log");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bootJarCustomLaunchScript() throws IOException {
|
||||
File customScriptFile = new File(this.gradleBuild.getProjectDir(),
|
||||
"src/custom.script");
|
||||
File customScriptFile = new File(this.gradleBuild.getProjectDir(), "src/custom.script");
|
||||
customScriptFile.getParentFile().mkdirs();
|
||||
FileCopyUtils.copy("custom", new FileWriter(customScriptFile));
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-custom-launch-script")
|
||||
.build("bootJar");
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-custom-launch-script").build("bootJar");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar");
|
||||
assertThat(file).isFile();
|
||||
@@ -179,8 +162,7 @@ public class PackagingDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void bootWarPropertiesLauncher() throws IOException {
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-war-properties-launcher")
|
||||
.build("bootWar");
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-war-properties-launcher").build("bootWar");
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".war");
|
||||
assertThat(file).isFile();
|
||||
@@ -192,8 +174,7 @@ public class PackagingDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void bootJarAndJar() {
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-and-jar")
|
||||
.build("assemble");
|
||||
this.gradleBuild.script("src/main/gradle/packaging/boot-jar-and-jar").build("assemble");
|
||||
File jar = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar");
|
||||
assertThat(jar).isFile();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -41,17 +41,14 @@ public class PublishingDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void mavenUpload() throws IOException {
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven")
|
||||
.build("deployerRepository").getOutput())
|
||||
.contains("https://repo.example.com");
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven").build("deployerRepository").getOutput())
|
||||
.contains("https://repo.example.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mavenPublish() throws IOException {
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven-publish")
|
||||
.build("publishingConfiguration").getOutput())
|
||||
.contains("MavenPublication")
|
||||
.contains("https://repo.example.com");
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven-publish").build("publishingConfiguration")
|
||||
.getOutput()).contains("MavenPublication").contains("https://repo.example.com");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -42,33 +42,26 @@ public class RunningDocumentationTests {
|
||||
|
||||
@Test
|
||||
public void bootRunMain() throws IOException {
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/running/boot-run-main")
|
||||
.build("configuredMainClass").getOutput())
|
||||
.contains("com.example.ExampleApplication");
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/running/boot-run-main").build("configuredMainClass")
|
||||
.getOutput()).contains("com.example.ExampleApplication");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applicationPluginMainClassName() {
|
||||
assertThat(this.gradleBuild
|
||||
.script("src/main/gradle/running/application-plugin-main-class-name")
|
||||
.build("configuredMainClass").getOutput())
|
||||
.contains("com.example.ExampleApplication");
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/running/application-plugin-main-class-name")
|
||||
.build("configuredMainClass").getOutput()).contains("com.example.ExampleApplication");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void springBootDslMainClassName() throws IOException {
|
||||
assertThat(this.gradleBuild
|
||||
.script("src/main/gradle/running/spring-boot-dsl-main-class-name")
|
||||
.build("configuredMainClass").getOutput())
|
||||
.contains("com.example.ExampleApplication");
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/running/spring-boot-dsl-main-class-name")
|
||||
.build("configuredMainClass").getOutput()).contains("com.example.ExampleApplication");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bootRunSourceResources() throws IOException {
|
||||
assertThat(this.gradleBuild
|
||||
.script("src/main/gradle/running/boot-run-source-resources")
|
||||
.build("configuredClasspath").getOutput())
|
||||
.contains(new File("src/main/resources").getPath());
|
||||
assertThat(this.gradleBuild.script("src/main/gradle/running/boot-run-source-resources")
|
||||
.build("configuredClasspath").getOutput()).contains(new File("src/main/resources").getPath());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -43,24 +43,21 @@ public class BuildInfoDslIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void basicJar() throws IOException {
|
||||
assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace")
|
||||
.task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
Properties properties = buildInfoProperties();
|
||||
assertThat(properties).containsEntry("build.name",
|
||||
this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.artifact",
|
||||
this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.group", "com.example");
|
||||
assertThat(properties).containsEntry("build.version", "1.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jarWithCustomName() throws IOException {
|
||||
assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace")
|
||||
.task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
Properties properties = buildInfoProperties();
|
||||
assertThat(properties).containsEntry("build.name",
|
||||
this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.artifact", "foo");
|
||||
assertThat(properties).containsEntry("build.group", "com.example");
|
||||
assertThat(properties).containsEntry("build.version", "1.0");
|
||||
@@ -68,24 +65,21 @@ public class BuildInfoDslIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void basicWar() throws IOException {
|
||||
assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace")
|
||||
.task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
Properties properties = buildInfoProperties();
|
||||
assertThat(properties).containsEntry("build.name",
|
||||
this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.artifact",
|
||||
this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.group", "com.example");
|
||||
assertThat(properties).containsEntry("build.version", "1.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void warWithCustomName() throws IOException {
|
||||
assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace")
|
||||
.task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
Properties properties = buildInfoProperties();
|
||||
assertThat(properties).containsEntry("build.name",
|
||||
this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.artifact", "foo");
|
||||
assertThat(properties).containsEntry("build.group", "com.example");
|
||||
assertThat(properties).containsEntry("build.version", "1.0");
|
||||
@@ -93,13 +87,11 @@ public class BuildInfoDslIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void additionalProperties() throws IOException {
|
||||
assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace")
|
||||
.task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
Properties properties = buildInfoProperties();
|
||||
assertThat(properties).containsEntry("build.name",
|
||||
this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.artifact",
|
||||
this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(properties).containsEntry("build.group", "com.example");
|
||||
assertThat(properties).containsEntry("build.version", "1.0");
|
||||
assertThat(properties).containsEntry("build.a", "alpha");
|
||||
@@ -108,13 +100,12 @@ public class BuildInfoDslIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void classesDependency() throws IOException {
|
||||
assertThat(this.gradleBuild.build("classes", "--stacktrace")
|
||||
.task(":bootBuildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("classes", "--stacktrace").task(":bootBuildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
}
|
||||
|
||||
private Properties buildInfoProperties() {
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/resources/main/META-INF/build-info.properties");
|
||||
File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties");
|
||||
assertThat(file).isFile();
|
||||
Properties properties = new Properties();
|
||||
try (FileReader reader = new FileReader(file)) {
|
||||
|
||||
@@ -38,9 +38,8 @@ import org.springframework.boot.gradle.testkit.GradleBuild;
|
||||
*/
|
||||
public final class GradleCompatibilitySuite extends Suite {
|
||||
|
||||
private static final List<String> GRADLE_VERSIONS = Arrays.asList("default", "4.5.1",
|
||||
"4.6", "4.7", "4.8.1", "4.9", "4.10.3", "5.0", "5.1.1", "5.2.1", "5.3.1",
|
||||
"5.4.1");
|
||||
private static final List<String> GRADLE_VERSIONS = Arrays.asList("default", "4.5.1", "4.6", "4.7", "4.8.1", "4.9",
|
||||
"4.10.3", "5.0", "5.1.1", "5.2.1", "5.3.1", "5.4.1");
|
||||
|
||||
public GradleCompatibilitySuite(Class<?> clazz) throws InitializationError {
|
||||
super(clazz, createRunners(clazz));
|
||||
@@ -54,13 +53,11 @@ public final class GradleCompatibilitySuite extends Suite {
|
||||
return runners;
|
||||
}
|
||||
|
||||
private static final class GradleCompatibilityClassRunner
|
||||
extends BlockJUnit4ClassRunner {
|
||||
private static final class GradleCompatibilityClassRunner extends BlockJUnit4ClassRunner {
|
||||
|
||||
private final String gradleVersion;
|
||||
|
||||
private GradleCompatibilityClassRunner(Class<?> klass, String gradleVersion)
|
||||
throws InitializationError {
|
||||
private GradleCompatibilityClassRunner(Class<?> klass, String gradleVersion) throws InitializationError {
|
||||
super(klass);
|
||||
this.gradleVersion = gradleVersion;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -54,8 +54,7 @@ public final class GradleMultiDslSuite extends Suite {
|
||||
|
||||
private final GradleBuild gradleBuild;
|
||||
|
||||
private GradleDslClassRunner(Class<?> klass, GradleBuild gradleBuild)
|
||||
throws InitializationError {
|
||||
private GradleDslClassRunner(Class<?> klass, GradleBuild gradleBuild) throws InitializationError {
|
||||
super(klass);
|
||||
this.gradleBuild = gradleBuild;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -51,120 +51,100 @@ public class ApplicationPluginActionIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void noBootDistributionWithoutApplicationPluginApplied() {
|
||||
assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot")
|
||||
.getOutput()).contains("boot exists = false");
|
||||
assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot").getOutput())
|
||||
.contains("boot exists = false");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyingApplicationPluginCreatesBootDistribution() {
|
||||
assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot",
|
||||
"-PapplyApplicationPlugin").getOutput()).contains("boot exists = true");
|
||||
assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot", "-PapplyApplicationPlugin")
|
||||
.getOutput()).contains("boot exists = true");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noBootStartScriptsTaskWithoutApplicationPluginApplied() {
|
||||
assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts")
|
||||
.getOutput()).contains("bootStartScripts exists = false");
|
||||
assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts").getOutput())
|
||||
.contains("bootStartScripts exists = false");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyingApplicationPluginCreatesBootStartScriptsTask() {
|
||||
assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts",
|
||||
"-PapplyApplicationPlugin").getOutput())
|
||||
.contains("bootStartScripts exists = true");
|
||||
assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts", "-PapplyApplicationPlugin")
|
||||
.getOutput()).contains("bootStartScripts exists = true");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createsBootStartScriptsTaskUsesApplicationPluginsDefaultJvmOpts() {
|
||||
assertThat(this.gradleBuild
|
||||
.build("startScriptsDefaultJvmOpts", "-PapplyApplicationPlugin")
|
||||
.getOutput()).contains(
|
||||
"bootStartScripts defaultJvmOpts = [-Dcom.example.a=alpha, -Dcom.example.b=bravo]");
|
||||
assertThat(this.gradleBuild.build("startScriptsDefaultJvmOpts", "-PapplyApplicationPlugin").getOutput())
|
||||
.contains("bootStartScripts defaultJvmOpts = [-Dcom.example.a=alpha, -Dcom.example.b=bravo]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipDistributionForJarCanBeBuilt() throws IOException {
|
||||
assertThat(
|
||||
this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
String name = this.gradleBuild.getProjectDir().getName();
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/distributions/" + name + "-boot.zip");
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.zip");
|
||||
assertThat(distribution).isFile();
|
||||
assertThat(zipEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/",
|
||||
name + "-boot/lib/", name + "-boot/lib/" + name + ".jar",
|
||||
name + "-boot/bin/", name + "-boot/bin/" + name,
|
||||
assertThat(zipEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", name + "-boot/lib/",
|
||||
name + "-boot/lib/" + name + ".jar", name + "-boot/bin/", name + "-boot/bin/" + name,
|
||||
name + "-boot/bin/" + name + ".bat");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void tarDistributionForJarCanBeBuilt() throws IOException {
|
||||
assertThat(
|
||||
this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
String name = this.gradleBuild.getProjectDir().getName();
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/distributions/" + name + "-boot.tar");
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar");
|
||||
assertThat(distribution).isFile();
|
||||
assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/",
|
||||
name + "-boot/lib/", name + "-boot/lib/" + name + ".jar",
|
||||
name + "-boot/bin/", name + "-boot/bin/" + name,
|
||||
assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", name + "-boot/lib/",
|
||||
name + "-boot/lib/" + name + ".jar", name + "-boot/bin/", name + "-boot/bin/" + name,
|
||||
name + "-boot/bin/" + name + ".bat");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipDistributionForWarCanBeBuilt() throws IOException {
|
||||
assertThat(
|
||||
this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
String name = this.gradleBuild.getProjectDir().getName();
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/distributions/" + name + "-boot.zip");
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.zip");
|
||||
assertThat(distribution).isFile();
|
||||
assertThat(zipEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/",
|
||||
name + "-boot/lib/", name + "-boot/lib/" + name + ".war",
|
||||
name + "-boot/bin/", name + "-boot/bin/" + name,
|
||||
assertThat(zipEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", name + "-boot/lib/",
|
||||
name + "-boot/lib/" + name + ".war", name + "-boot/bin/", name + "-boot/bin/" + name,
|
||||
name + "-boot/bin/" + name + ".bat");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void tarDistributionForWarCanBeBuilt() throws IOException {
|
||||
assertThat(
|
||||
this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
String name = this.gradleBuild.getProjectDir().getName();
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/distributions/" + name + "-boot.tar");
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar");
|
||||
assertThat(distribution).isFile();
|
||||
assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/",
|
||||
name + "-boot/lib/", name + "-boot/lib/" + name + ".war",
|
||||
name + "-boot/bin/", name + "-boot/bin/" + name,
|
||||
assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder(name + "-boot/", name + "-boot/lib/",
|
||||
name + "-boot/lib/" + name + ".war", name + "-boot/bin/", name + "-boot/bin/" + name,
|
||||
name + "-boot/bin/" + name + ".bat");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applicationNameCanBeUsedToCustomizeDistributionName() throws IOException {
|
||||
assertThat(
|
||||
this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/distributions/custom-boot.tar");
|
||||
assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/custom-boot.tar");
|
||||
assertThat(distribution).isFile();
|
||||
String name = this.gradleBuild.getProjectDir().getName();
|
||||
assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder("custom-boot/",
|
||||
"custom-boot/lib/", "custom-boot/lib/" + name + ".jar",
|
||||
"custom-boot/bin/", "custom-boot/bin/custom",
|
||||
assertThat(tarEntryNames(distribution)).containsExactlyInAnyOrder("custom-boot/", "custom-boot/lib/",
|
||||
"custom-boot/lib/" + name + ".jar", "custom-boot/bin/", "custom-boot/bin/custom",
|
||||
"custom-boot/bin/custom.bat");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void scriptsHaveCorrectPermissions() throws IOException {
|
||||
assertThat(
|
||||
this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
String name = this.gradleBuild.getProjectDir().getName();
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/distributions/" + name + "-boot.tar");
|
||||
File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar");
|
||||
assertThat(distribution).isFile();
|
||||
tarEntries(distribution, (entry) -> {
|
||||
int filePermissions = entry.getMode() & 0777;
|
||||
@@ -190,8 +170,7 @@ public class ApplicationPluginActionIntegrationTests {
|
||||
|
||||
private List<String> tarEntryNames(File distribution) throws IOException {
|
||||
List<String> entryNames = new ArrayList<>();
|
||||
try (TarArchiveInputStream input = new TarArchiveInputStream(
|
||||
new FileInputStream(distribution))) {
|
||||
try (TarArchiveInputStream input = new TarArchiveInputStream(new FileInputStream(distribution))) {
|
||||
TarArchiveEntry entry;
|
||||
while ((entry = input.getNextTarEntry()) != null) {
|
||||
entryNames.add(entry.getName());
|
||||
@@ -200,10 +179,8 @@ public class ApplicationPluginActionIntegrationTests {
|
||||
return entryNames;
|
||||
}
|
||||
|
||||
private void tarEntries(File distribution, Consumer<TarArchiveEntry> consumer)
|
||||
throws IOException {
|
||||
try (TarArchiveInputStream input = new TarArchiveInputStream(
|
||||
new FileInputStream(distribution))) {
|
||||
private void tarEntries(File distribution, Consumer<TarArchiveEntry> consumer) throws IOException {
|
||||
try (TarArchiveInputStream input = new TarArchiveInputStream(new FileInputStream(distribution))) {
|
||||
TarArchiveEntry entry;
|
||||
while ((entry = input.getNextTarEntry()) != null) {
|
||||
consumer.accept(entry);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -45,35 +45,28 @@ public class DependencyManagementPluginActionIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void noDependencyManagementIsAppliedByDefault() {
|
||||
assertThat(this.gradleBuild.build("doesNotHaveDependencyManagement")
|
||||
.task(":doesNotHaveDependencyManagement").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("doesNotHaveDependencyManagement").task(":doesNotHaveDependencyManagement")
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bomIsImportedWhenDependencyManagementPluginIsApplied() {
|
||||
assertThat(this.gradleBuild
|
||||
.build("hasDependencyManagement", "-PapplyDependencyManagementPlugin")
|
||||
.task(":hasDependencyManagement").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("hasDependencyManagement", "-PapplyDependencyManagementPlugin")
|
||||
.task(":hasDependencyManagement").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void helpfulErrorWhenVersionlessDependencyFailsToResolve() throws IOException {
|
||||
File examplePackage = new File(this.gradleBuild.getProjectDir(),
|
||||
"src/main/java/com/example");
|
||||
File examplePackage = new File(this.gradleBuild.getProjectDir(), "src/main/java/com/example");
|
||||
examplePackage.mkdirs();
|
||||
FileSystemUtils.copyRecursively(new File("src/test/java/com/example"),
|
||||
examplePackage);
|
||||
FileSystemUtils.copyRecursively(new File("src/test/java/com/example"), examplePackage);
|
||||
BuildResult result = this.gradleBuild.buildAndFail("compileJava");
|
||||
assertThat(result.task(":compileJava").getOutcome())
|
||||
.isEqualTo(TaskOutcome.FAILED);
|
||||
assertThat(result.task(":compileJava").getOutcome()).isEqualTo(TaskOutcome.FAILED);
|
||||
String output = result.getOutput();
|
||||
assertThat(output).contains("During the build, one or more dependencies that "
|
||||
+ "were declared without a version failed to resolve:");
|
||||
assertThat(output).contains("org.springframework.boot:spring-boot-starter-web:");
|
||||
assertThat(output).contains("Did you forget to apply the "
|
||||
+ "io.spring.dependency-management plugin to the "
|
||||
assertThat(output).contains("Did you forget to apply the " + "io.spring.dependency-management plugin to the "
|
||||
+ this.gradleBuild.getProjectDir().getName() + " project?");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -51,9 +51,8 @@ public class JavaPluginActionIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void applyingJavaPluginCreatesBootJarTask() {
|
||||
assertThat(this.gradleBuild
|
||||
.build("taskExists", "-PtaskName=bootJar", "-PapplyJavaPlugin")
|
||||
.getOutput()).contains("bootJar exists = true");
|
||||
assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootJar", "-PapplyJavaPlugin").getOutput())
|
||||
.contains("bootJar exists = true");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -64,16 +63,14 @@ public class JavaPluginActionIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void applyingJavaPluginCreatesBootRunTask() {
|
||||
assertThat(this.gradleBuild
|
||||
.build("taskExists", "-PtaskName=bootRun", "-PapplyJavaPlugin")
|
||||
.getOutput()).contains("bootRun exists = true");
|
||||
assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootRun", "-PapplyJavaPlugin").getOutput())
|
||||
.contains("bootRun exists = true");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void javaCompileTasksUseUtf8Encoding() {
|
||||
assertThat(this.gradleBuild.build("javaCompileEncoding", "-PapplyJavaPlugin")
|
||||
.getOutput()).contains("compileJava = UTF-8")
|
||||
.contains("compileTestJava = UTF-8");
|
||||
assertThat(this.gradleBuild.build("javaCompileEncoding", "-PapplyJavaPlugin").getOutput())
|
||||
.contains("compileJava = UTF-8").contains("compileTestJava = UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -108,8 +105,7 @@ public class JavaPluginActionIntegrationTests {
|
||||
public void errorMessageIsHelpfulWhenMainClassCannotBeResolved() {
|
||||
BuildResult result = this.gradleBuild.buildAndFail("build", "-PapplyJavaPlugin");
|
||||
assertThat(result.task(":bootJar").getOutcome()).isEqualTo(TaskOutcome.FAILED);
|
||||
assertThat(result.getOutput()).contains(
|
||||
"Main class name has not been configured and it could not be resolved");
|
||||
assertThat(result.getOutput()).contains("Main class name has not been configured and it could not be resolved");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -120,42 +116,33 @@ public class JavaPluginActionIntegrationTests {
|
||||
File buildLibs = new File(this.gradleBuild.getProjectDir(), "build/libs");
|
||||
assertThat(buildLibs.listFiles()).containsExactlyInAnyOrder(
|
||||
new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".jar"),
|
||||
new File(buildLibs,
|
||||
this.gradleBuild.getProjectDir().getName() + "-boot.jar"));
|
||||
new File(buildLibs, this.gradleBuild.getProjectDir().getName() + "-boot.jar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void additionalMetadataLocationsConfiguredWhenProcessorIsPresent()
|
||||
throws IOException {
|
||||
public void additionalMetadataLocationsConfiguredWhenProcessorIsPresent() throws IOException {
|
||||
createMinimalMainSource();
|
||||
File libs = new File(this.gradleBuild.getProjectDir(), "libs");
|
||||
libs.mkdirs();
|
||||
new JarOutputStream(new FileOutputStream(
|
||||
new File(libs, "spring-boot-configuration-processor-1.2.3.jar"))).close();
|
||||
new JarOutputStream(new FileOutputStream(new File(libs, "spring-boot-configuration-processor-1.2.3.jar")))
|
||||
.close();
|
||||
BuildResult result = this.gradleBuild.build("compileJava");
|
||||
assertThat(result.task(":compileJava").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(result.getOutput()).contains(
|
||||
"compileJava compiler args: [-parameters, -Aorg.springframework.boot."
|
||||
+ "configurationprocessor.additionalMetadataLocations="
|
||||
+ new File(this.gradleBuild.getProjectDir(), "src/main/resources")
|
||||
.getCanonicalPath());
|
||||
assertThat(result.task(":compileJava").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(result.getOutput()).contains("compileJava compiler args: [-parameters, -Aorg.springframework.boot."
|
||||
+ "configurationprocessor.additionalMetadataLocations="
|
||||
+ new File(this.gradleBuild.getProjectDir(), "src/main/resources").getCanonicalPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void additionalMetadataLocationsNotConfiguredWhenProcessorIsAbsent()
|
||||
throws IOException {
|
||||
public void additionalMetadataLocationsNotConfiguredWhenProcessorIsAbsent() throws IOException {
|
||||
createMinimalMainSource();
|
||||
BuildResult result = this.gradleBuild.build("compileJava");
|
||||
assertThat(result.task(":compileJava").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(result.getOutput())
|
||||
.contains("compileJava compiler args: [-parameters]");
|
||||
assertThat(result.task(":compileJava").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(result.getOutput()).contains("compileJava compiler args: [-parameters]");
|
||||
}
|
||||
|
||||
private void createMinimalMainSource() throws IOException {
|
||||
File examplePackage = new File(this.gradleBuild.getProjectDir(),
|
||||
"src/main/java/com/example");
|
||||
File examplePackage = new File(this.gradleBuild.getProjectDir(), "src/main/java/com/example");
|
||||
examplePackage.mkdirs();
|
||||
new File(examplePackage, "Application.java").createNewFile();
|
||||
}
|
||||
|
||||
@@ -38,29 +38,26 @@ public class KotlinPluginActionIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void noKotlinVersionPropertyWithoutKotlinPlugin() {
|
||||
assertThat(this.gradleBuild.build("kotlinVersion").getOutput())
|
||||
.contains("Kotlin version: none");
|
||||
assertThat(this.gradleBuild.build("kotlinVersion").getOutput()).contains("Kotlin version: none");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void kotlinVersionPropertyIsSet() {
|
||||
String output = this.gradleBuild.build("kotlinVersion", "dependencies",
|
||||
"--configuration", "compileClasspath").getOutput();
|
||||
String output = this.gradleBuild.build("kotlinVersion", "dependencies", "--configuration", "compileClasspath")
|
||||
.getOutput();
|
||||
assertThat(output).containsPattern("Kotlin version: [0-9]\\.[0-9]\\.[0-9]+");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void kotlinCompileTasksUseJavaParametersFlagByDefault() {
|
||||
assertThat(this.gradleBuild.build("kotlinCompileTasksJavaParameters").getOutput())
|
||||
.contains("compileKotlin java parameters: true")
|
||||
.contains("compileTestKotlin java parameters: true");
|
||||
.contains("compileKotlin java parameters: true").contains("compileTestKotlin java parameters: true");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void kotlinCompileTasksCanOverrideDefaultJavaParametersFlag() {
|
||||
assertThat(this.gradleBuild.build("kotlinCompileTasksJavaParameters").getOutput())
|
||||
.contains("compileKotlin java parameters: false")
|
||||
.contains("compileTestKotlin java parameters: false");
|
||||
.contains("compileKotlin java parameters: false").contains("compileTestKotlin java parameters: false");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -41,36 +41,33 @@ public class MainClassConventionTests {
|
||||
|
||||
@Before
|
||||
public void createConvention() throws IOException {
|
||||
this.project = ProjectBuilder.builder().withProjectDir(this.temp.newFolder())
|
||||
.build();
|
||||
this.project = ProjectBuilder.builder().withProjectDir(this.temp.newFolder()).build();
|
||||
this.convention = new MainClassConvention(this.project, () -> null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mainClassNameProjectPropertyIsUsed() throws Exception {
|
||||
this.project.getExtensions().getByType(ExtraPropertiesExtension.class)
|
||||
.set("mainClassName", "com.example.MainClass");
|
||||
this.project.getExtensions().getByType(ExtraPropertiesExtension.class).set("mainClassName",
|
||||
"com.example.MainClass");
|
||||
assertThat(this.convention.call()).isEqualTo("com.example.MainClass");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void springBootExtensionMainClassNameIsUsed() throws Exception {
|
||||
SpringBootExtension extension = this.project.getExtensions().create("springBoot",
|
||||
SpringBootExtension.class, this.project);
|
||||
SpringBootExtension extension = this.project.getExtensions().create("springBoot", SpringBootExtension.class,
|
||||
this.project);
|
||||
extension.setMainClassName("com.example.MainClass");
|
||||
assertThat(this.convention.call()).isEqualTo("com.example.MainClass");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void springBootExtensionMainClassNameIsUsedInPreferenceToMainClassNameProjectProperty()
|
||||
throws Exception {
|
||||
this.project.getExtensions().getByType(ExtraPropertiesExtension.class)
|
||||
.set("mainClassName", "com.example.ProjectPropertyMainClass");
|
||||
SpringBootExtension extension = this.project.getExtensions().create("springBoot",
|
||||
SpringBootExtension.class, this.project);
|
||||
public void springBootExtensionMainClassNameIsUsedInPreferenceToMainClassNameProjectProperty() throws Exception {
|
||||
this.project.getExtensions().getByType(ExtraPropertiesExtension.class).set("mainClassName",
|
||||
"com.example.ProjectPropertyMainClass");
|
||||
SpringBootExtension extension = this.project.getExtensions().create("springBoot", SpringBootExtension.class,
|
||||
this.project);
|
||||
extension.setMainClassName("com.example.SpringBootExtensionMainClass");
|
||||
assertThat(this.convention.call())
|
||||
.isEqualTo("com.example.SpringBootExtensionMainClass");
|
||||
assertThat(this.convention.call()).isEqualTo("com.example.SpringBootExtensionMainClass");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -38,8 +38,7 @@ public class MavenPluginActionIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void clearsConf2ScopeMappingsOfUploadBootArchivesTask() {
|
||||
assertThat(this.gradleBuild.build("conf2ScopeMappings").getOutput())
|
||||
.contains("Conf2ScopeMappings = 0");
|
||||
assertThat(this.gradleBuild.build("conf2ScopeMappings").getOutput()).contains("Conf2ScopeMappings = 0");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -40,8 +40,8 @@ public class SpringBootPluginIntegrationTests {
|
||||
@Test
|
||||
public void failFastWithVersionOfGradleLowerThanRequired() {
|
||||
BuildResult result = this.gradleBuild.gradleVersion("4.3").buildAndFail();
|
||||
assertThat(result.getOutput()).contains("Spring Boot plugin requires Gradle 4.4"
|
||||
+ " or later. The current version is Gradle 4.3");
|
||||
assertThat(result.getOutput())
|
||||
.contains("Spring Boot plugin requires Gradle 4.4" + " or later. The current version is Gradle 4.3");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -55,19 +55,17 @@ public class SpringBootPluginIntegrationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unresolvedDependenciesAreAnalyzedWhenDependencyResolutionFails()
|
||||
throws IOException {
|
||||
public void unresolvedDependenciesAreAnalyzedWhenDependencyResolutionFails() throws IOException {
|
||||
createMinimalMainSource();
|
||||
BuildResult result = this.gradleBuild.buildAndFail("compileJava");
|
||||
assertThat(result.getOutput()).contains(
|
||||
"During the build, one or more dependencies that were declared without a"
|
||||
assertThat(result.getOutput())
|
||||
.contains("During the build, one or more dependencies that were declared without a"
|
||||
+ " version failed to resolve:")
|
||||
.contains(" org.springframework.boot:spring-boot-starter:");
|
||||
}
|
||||
|
||||
private void createMinimalMainSource() throws IOException {
|
||||
File examplePackage = new File(this.gradleBuild.getProjectDir(),
|
||||
"src/main/java/com/example");
|
||||
File examplePackage = new File(this.gradleBuild.getProjectDir(), "src/main/java/com/example");
|
||||
examplePackage.mkdirs();
|
||||
new File(examplePackage, "Application.java").createNewFile();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -48,9 +48,8 @@ public class WarPluginActionIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void applyingWarPluginCreatesBootWarTask() {
|
||||
assertThat(this.gradleBuild
|
||||
.build("taskExists", "-PtaskName=bootWar", "-PapplyWarPlugin")
|
||||
.getOutput()).contains("bootWar exists = true");
|
||||
assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootWar", "-PapplyWarPlugin").getOutput())
|
||||
.contains("bootWar exists = true");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -68,16 +67,14 @@ public class WarPluginActionIntegrationTests {
|
||||
File buildLibs = new File(this.gradleBuild.getProjectDir(), "build/libs");
|
||||
assertThat(buildLibs.listFiles()).containsExactlyInAnyOrder(
|
||||
new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war"),
|
||||
new File(buildLibs,
|
||||
this.gradleBuild.getProjectDir().getName() + "-boot.war"));
|
||||
new File(buildLibs, this.gradleBuild.getProjectDir().getName() + "-boot.war"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void errorMessageIsHelpfulWhenMainClassCannotBeResolved() {
|
||||
BuildResult result = this.gradleBuild.buildAndFail("build", "-PapplyWarPlugin");
|
||||
assertThat(result.task(":bootWar").getOutcome()).isEqualTo(TaskOutcome.FAILED);
|
||||
assertThat(result.getOutput()).contains(
|
||||
"Main class name has not been configured and it could not be resolved");
|
||||
assertThat(result.getOutput()).contains("Main class name has not been configured and it could not be resolved");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -45,21 +45,18 @@ public class BuildInfoIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void defaultValues() {
|
||||
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
Properties buildInfoProperties = buildInfoProperties();
|
||||
assertThat(buildInfoProperties).containsKey("build.time");
|
||||
assertThat(buildInfoProperties).containsEntry("build.artifact", "unspecified");
|
||||
assertThat(buildInfoProperties).containsEntry("build.group", "");
|
||||
assertThat(buildInfoProperties).containsEntry("build.name",
|
||||
this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(buildInfoProperties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName());
|
||||
assertThat(buildInfoProperties).containsEntry("build.version", "unspecified");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void basicExecution() {
|
||||
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
Properties buildInfoProperties = buildInfoProperties();
|
||||
assertThat(buildInfoProperties).containsKey("build.time");
|
||||
assertThat(buildInfoProperties).containsEntry("build.artifact", "foo");
|
||||
@@ -71,32 +68,28 @@ public class BuildInfoIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void notUpToDateWhenExecutedTwiceAsTimeChanges() {
|
||||
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upToDateWhenExecutedTwiceWithFixedTime() {
|
||||
assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo")
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo")
|
||||
.getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notUpToDateWhenExecutedTwiceWithFixedTimeAndChangedProjectVersion() {
|
||||
assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo")
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
BuildResult result = this.gradleBuild.build("buildInfo", "-PnullTime",
|
||||
"-PprojectVersion=0.2.0");
|
||||
assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
BuildResult result = this.gradleBuild.build("buildInfo", "-PnullTime", "-PprojectVersion=0.2.0");
|
||||
assertThat(result.task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
}
|
||||
|
||||
private Properties buildInfoProperties() {
|
||||
File file = new File(this.gradleBuild.getProjectDir(),
|
||||
"build/build-info.properties");
|
||||
File file = new File(this.gradleBuild.getProjectDir(), "build/build-info.properties");
|
||||
assertThat(file).isFile();
|
||||
Properties properties = new Properties();
|
||||
try (FileReader reader = new FileReader(file)) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -112,8 +112,7 @@ public class BuildInfoTests {
|
||||
Instant now = Instant.now();
|
||||
BuildInfo task = createTask(createProject("test"));
|
||||
task.getProperties().setTime(now);
|
||||
assertThat(buildInfoProperties(task)).containsEntry("build.time",
|
||||
DateTimeFormatter.ISO_INSTANT.format(now));
|
||||
assertThat(buildInfoProperties(task)).containsEntry("build.time", DateTimeFormatter.ISO_INSTANT.format(now));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -128,8 +127,7 @@ public class BuildInfoTests {
|
||||
private Project createProject(String projectName) {
|
||||
try {
|
||||
File projectDir = this.temp.newFolder(projectName);
|
||||
return ProjectBuilder.builder().withProjectDir(projectDir)
|
||||
.withName(projectName).build();
|
||||
return ProjectBuilder.builder().withProjectDir(projectDir).withName(projectName).build();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
@@ -142,8 +140,7 @@ public class BuildInfoTests {
|
||||
|
||||
private Properties buildInfoProperties(BuildInfo task) {
|
||||
task.generateBuildProperties();
|
||||
return buildInfoProperties(
|
||||
new File(task.getDestinationDir(), "build-info.properties"));
|
||||
return buildInfoProperties(new File(task.getDestinationDir(), "build-info.properties"));
|
||||
}
|
||||
|
||||
private Properties buildInfoProperties(File file) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -51,80 +51,72 @@ public abstract class AbstractBootArchiveIntegrationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void basicBuild() throws InvalidRunnerConfigurationException,
|
||||
UnexpectedBuildFailure, IOException {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
public void basicBuild() throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, IOException {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void reproducibleArchive() throws InvalidRunnerConfigurationException,
|
||||
UnexpectedBuildFailure, IOException, InterruptedException {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
File jar = new File(this.gradleBuild.getProjectDir(), "build/libs")
|
||||
.listFiles()[0];
|
||||
public void reproducibleArchive()
|
||||
throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, IOException, InterruptedException {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
File jar = new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0];
|
||||
String firstHash = FileUtils.sha1Hash(jar);
|
||||
Thread.sleep(1500);
|
||||
assertThat(this.gradleBuild.build("clean", this.taskName)
|
||||
.task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("clean", this.taskName).task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
String secondHash = FileUtils.sha1Hash(jar);
|
||||
assertThat(firstHash).isEqualTo(secondHash);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upToDateWhenBuiltTwice() throws InvalidRunnerConfigurationException,
|
||||
UnexpectedBuildFailure, IOException {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
public void upToDateWhenBuiltTwice()
|
||||
throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, IOException {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upToDateWhenBuiltTwiceWithLaunchScriptIncluded()
|
||||
throws InvalidRunnerConfigurationException, UnexpectedBuildFailure,
|
||||
IOException {
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName)
|
||||
.task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName)
|
||||
.task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
throws InvalidRunnerConfigurationException, UnexpectedBuildFailure, IOException {
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notUpToDateWhenLaunchScriptWasNotIncludedAndThenIsIncluded() {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName)
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName)
|
||||
.task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notUpToDateWhenLaunchScriptWasIncludedAndThenIsNotIncluded() {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName)
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName)
|
||||
.task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notUpToDateWhenLaunchScriptPropertyChanges() {
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true",
|
||||
"-PlaunchScriptProperty=foo", this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true",
|
||||
"-PlaunchScriptProperty=bar", this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", "-PlaunchScriptProperty=foo", this.taskName)
|
||||
.task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", "-PlaunchScriptProperty=bar", this.taskName)
|
||||
.task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applicationPluginMainClassNameIsUsed() throws IOException {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
try (JarFile jarFile = new JarFile(
|
||||
new File(this.gradleBuild.getProjectDir(), "build/libs")
|
||||
.listFiles()[0])) {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) {
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class"))
|
||||
.isEqualTo("com.example.CustomMain");
|
||||
}
|
||||
@@ -132,11 +124,9 @@ public abstract class AbstractBootArchiveIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void springBootExtensionMainClassNameIsUsed() throws IOException {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
try (JarFile jarFile = new JarFile(
|
||||
new File(this.gradleBuild.getProjectDir(), "build/libs")
|
||||
.listFiles()[0])) {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) {
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class"))
|
||||
.isEqualTo("com.example.CustomMain");
|
||||
}
|
||||
@@ -144,8 +134,8 @@ public abstract class AbstractBootArchiveIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void duplicatesAreHandledGracefully() throws IOException {
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName)
|
||||
.getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -73,8 +73,7 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
|
||||
private T task;
|
||||
|
||||
protected AbstractBootArchiveTests(Class<T> taskClass, String launcherClass,
|
||||
String libPath, String classesPath) {
|
||||
protected AbstractBootArchiveTests(Class<T> taskClass, String launcherClass, String libPath, String classesPath) {
|
||||
this.taskClass = taskClass;
|
||||
this.launcherClass = launcherClass;
|
||||
this.libPath = libPath;
|
||||
@@ -84,12 +83,9 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
@Before
|
||||
public void createTask() {
|
||||
try {
|
||||
this.project = ProjectBuilder.builder().withProjectDir(this.temp.newFolder())
|
||||
.build();
|
||||
this.project
|
||||
.setDescription("Test project for " + this.taskClass.getSimpleName());
|
||||
this.task = configure(
|
||||
this.project.getTasks().create("testArchive", this.taskClass));
|
||||
this.project = ProjectBuilder.builder().withProjectDir(this.temp.newFolder()).build();
|
||||
this.project.setDescription("Test project for " + this.taskClass.getSimpleName());
|
||||
this.task = configure(this.project.getTasks().create("testArchive", this.taskClass));
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
@@ -102,17 +98,12 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
this.task.execute();
|
||||
assertThat(this.task.getArchivePath()).exists();
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo(this.launcherClass);
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class"))
|
||||
.isEqualTo("com.example.Main");
|
||||
assertThat(jarFile.getManifest().getMainAttributes()
|
||||
.getValue("Spring-Boot-Classes")).isEqualTo(this.classesPath);
|
||||
assertThat(
|
||||
jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Lib"))
|
||||
.isEqualTo(this.libPath);
|
||||
assertThat(jarFile.getManifest().getMainAttributes()
|
||||
.getValue("Spring-Boot-Version")).isNotNull();
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")).isEqualTo(this.launcherClass);
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")).isEqualTo("com.example.Main");
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classes"))
|
||||
.isEqualTo(this.classesPath);
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo(this.libPath);
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Version")).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,16 +122,13 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
public void classpathFoldersArePackagedBeneathClassesPath() throws IOException {
|
||||
this.task.setMainClassName("com.example.Main");
|
||||
File classpathFolder = this.temp.newFolder();
|
||||
File applicationClass = new File(classpathFolder,
|
||||
"com/example/Application.class");
|
||||
File applicationClass = new File(classpathFolder, "com/example/Application.class");
|
||||
applicationClass.getParentFile().mkdirs();
|
||||
applicationClass.createNewFile();
|
||||
this.task.classpath(classpathFolder);
|
||||
this.task.execute();
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(
|
||||
jarFile.getEntry(this.classesPath + "com/example/Application.class"))
|
||||
.isNotNull();
|
||||
assertThat(jarFile.getEntry(this.classesPath + "com/example/Application.class")).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,20 +139,16 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
File moduleInfoClass = new File(classpathFolder, "module-info.class");
|
||||
moduleInfoClass.getParentFile().mkdirs();
|
||||
moduleInfoClass.createNewFile();
|
||||
File applicationClass = new File(classpathFolder,
|
||||
"com/example/Application.class");
|
||||
File applicationClass = new File(classpathFolder, "com/example/Application.class");
|
||||
applicationClass.getParentFile().mkdirs();
|
||||
applicationClass.createNewFile();
|
||||
this.task.classpath(classpathFolder);
|
||||
this.task.execute();
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(
|
||||
jarFile.getEntry(this.classesPath + "com/example/Application.class"))
|
||||
.isNotNull();
|
||||
assertThat(jarFile.getEntry(this.classesPath + "com/example/Application.class")).isNotNull();
|
||||
assertThat(jarFile.getEntry("com/example/Application.class")).isNull();
|
||||
assertThat(jarFile.getEntry("module-info.class")).isNotNull();
|
||||
assertThat(jarFile.getEntry(this.classesPath + "/module-info.class"))
|
||||
.isNull();
|
||||
assertThat(jarFile.getEntry(this.classesPath + "/module-info.class")).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,24 +191,18 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
this.task.setMainClassName("com.example.Main");
|
||||
this.task.execute();
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(jarFile.getEntry(
|
||||
"org/springframework/boot/loader/LaunchedURLClassLoader.class"))
|
||||
.isNotNull();
|
||||
assertThat(jarFile.getEntry("org/springframework/boot/loader/LaunchedURLClassLoader.class")).isNotNull();
|
||||
assertThat(jarFile.getEntry("org/springframework/boot/loader/")).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loaderIsWrittenToTheRootOfTheJarWhenUsingThePropertiesLauncher()
|
||||
throws IOException {
|
||||
public void loaderIsWrittenToTheRootOfTheJarWhenUsingThePropertiesLauncher() throws IOException {
|
||||
this.task.setMainClassName("com.example.Main");
|
||||
this.task.execute();
|
||||
this.task.getManifest().getAttributes().put("Main-Class",
|
||||
"org.springframework.boot.loader.PropertiesLauncher");
|
||||
this.task.getManifest().getAttributes().put("Main-Class", "org.springframework.boot.loader.PropertiesLauncher");
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(jarFile.getEntry(
|
||||
"org/springframework/boot/loader/LaunchedURLClassLoader.class"))
|
||||
.isNotNull();
|
||||
assertThat(jarFile.getEntry("org/springframework/boot/loader/LaunchedURLClassLoader.class")).isNotNull();
|
||||
assertThat(jarFile.getEntry("org/springframework/boot/loader/")).isNotNull();
|
||||
}
|
||||
}
|
||||
@@ -236,8 +214,7 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
this.task.requiresUnpack("**/one.jar");
|
||||
this.task.execute();
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(jarFile.getEntry(this.libPath + "one.jar").getComment())
|
||||
.startsWith("UNPACK:");
|
||||
assertThat(jarFile.getEntry(this.libPath + "one.jar").getComment()).startsWith("UNPACK:");
|
||||
assertThat(jarFile.getEntry(this.libPath + "two.jar").getComment()).isNull();
|
||||
}
|
||||
}
|
||||
@@ -249,8 +226,7 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
this.task.requiresUnpack((element) -> element.getName().endsWith("two.jar"));
|
||||
this.task.execute();
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(jarFile.getEntry(this.libPath + "two.jar").getComment())
|
||||
.startsWith("UNPACK:");
|
||||
assertThat(jarFile.getEntry(this.libPath + "two.jar").getComment()).startsWith("UNPACK:");
|
||||
assertThat(jarFile.getEntry(this.libPath + "one.jar").getComment()).isNull();
|
||||
}
|
||||
}
|
||||
@@ -267,8 +243,7 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
assertThat(Files.readAllBytes(this.task.getArchivePath().toPath()))
|
||||
.startsWith(new DefaultLaunchScript(null, properties).toByteArray());
|
||||
try {
|
||||
Set<PosixFilePermission> permissions = Files
|
||||
.getPosixFilePermissions(this.task.getArchivePath().toPath());
|
||||
Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(this.task.getArchivePath().toPath());
|
||||
assertThat(permissions).contains(PosixFilePermission.OWNER_EXECUTE);
|
||||
}
|
||||
catch (UnsupportedOperationException ex) {
|
||||
@@ -280,12 +255,10 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
public void customLaunchScriptCanBePrepended() throws IOException {
|
||||
this.task.setMainClassName("com.example.Main");
|
||||
File customScript = this.temp.newFile("custom.script");
|
||||
Files.write(customScript.toPath(), Arrays.asList("custom script"),
|
||||
StandardOpenOption.CREATE);
|
||||
Files.write(customScript.toPath(), Arrays.asList("custom script"), StandardOpenOption.CREATE);
|
||||
this.task.launchScript((configuration) -> configuration.setScript(customScript));
|
||||
this.task.execute();
|
||||
assertThat(Files.readAllBytes(this.task.getArchivePath().toPath()))
|
||||
.startsWith("custom script".getBytes());
|
||||
assertThat(Files.readAllBytes(this.task.getArchivePath().toPath())).startsWith("custom script".getBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -293,46 +266,38 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
this.task.setMainClassName("com.example.Main");
|
||||
this.task.launchScript((configuration) -> {
|
||||
configuration.getProperties().put("initInfoProvides", "provides");
|
||||
configuration.getProperties().put("initInfoShortDescription",
|
||||
"short description");
|
||||
configuration.getProperties().put("initInfoShortDescription", "short description");
|
||||
configuration.getProperties().put("initInfoDescription", "description");
|
||||
});
|
||||
this.task.execute();
|
||||
byte[] bytes = Files.readAllBytes(this.task.getArchivePath().toPath());
|
||||
assertThat(bytes).containsSequence("Provides: provides".getBytes());
|
||||
assertThat(bytes)
|
||||
.containsSequence("Short-Description: short description".getBytes());
|
||||
assertThat(bytes).containsSequence("Short-Description: short description".getBytes());
|
||||
assertThat(bytes).containsSequence("Description: description".getBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customMainClassInTheManifestIsHonored() throws IOException {
|
||||
this.task.setMainClassName("com.example.Main");
|
||||
this.task.getManifest().getAttributes().put("Main-Class",
|
||||
"com.example.CustomLauncher");
|
||||
this.task.getManifest().getAttributes().put("Main-Class", "com.example.CustomLauncher");
|
||||
this.task.execute();
|
||||
assertThat(this.task.getArchivePath()).exists();
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo("com.example.CustomLauncher");
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class"))
|
||||
.isEqualTo("com.example.Main");
|
||||
assertThat(jarFile.getEntry(
|
||||
"org/springframework/boot/loader/LaunchedURLClassLoader.class"))
|
||||
.isNull();
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")).isEqualTo("com.example.Main");
|
||||
assertThat(jarFile.getEntry("org/springframework/boot/loader/LaunchedURLClassLoader.class")).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customStartClassInTheManifestIsHonored() throws IOException {
|
||||
this.task.setMainClassName("com.example.Main");
|
||||
this.task.getManifest().getAttributes().put("Start-Class",
|
||||
"com.example.CustomMain");
|
||||
this.task.getManifest().getAttributes().put("Start-Class", "com.example.CustomMain");
|
||||
this.task.execute();
|
||||
assertThat(this.task.getArchivePath()).exists();
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo(this.launcherClass);
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")).isEqualTo(this.launcherClass);
|
||||
assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class"))
|
||||
.isEqualTo("com.example.CustomMain");
|
||||
}
|
||||
@@ -348,8 +313,7 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
Enumeration<JarEntry> entries = jarFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
JarEntry entry = entries.nextElement();
|
||||
assertThat(entry.getTime())
|
||||
.isEqualTo(BootZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES);
|
||||
assertThat(entry.getTime()).isEqualTo(BootZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -382,8 +346,7 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
this.task.execute();
|
||||
assertThat(this.task.getArchivePath()).exists();
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(jarFile.getEntry(this.libPath + "spring-boot-devtools-0.1.2.jar"))
|
||||
.isNull();
|
||||
assertThat(jarFile.getEntry(this.libPath + "spring-boot-devtools-0.1.2.jar")).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -395,8 +358,7 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
this.task.execute();
|
||||
assertThat(this.task.getArchivePath()).exists();
|
||||
try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
|
||||
assertThat(jarFile.getEntry(this.libPath + "spring-boot-devtools-0.1.2.jar"))
|
||||
.isNotNull();
|
||||
assertThat(jarFile.getEntry(this.libPath + "spring-boot-devtools-0.1.2.jar")).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -422,23 +384,19 @@ public abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loaderIsWrittenFirstThenApplicationClassesThenLibraries()
|
||||
throws IOException {
|
||||
public void loaderIsWrittenFirstThenApplicationClassesThenLibraries() throws IOException {
|
||||
this.task.setMainClassName("com.example.Main");
|
||||
File classpathFolder = this.temp.newFolder();
|
||||
File applicationClass = new File(classpathFolder,
|
||||
"com/example/Application.class");
|
||||
File applicationClass = new File(classpathFolder, "com/example/Application.class");
|
||||
applicationClass.getParentFile().mkdirs();
|
||||
applicationClass.createNewFile();
|
||||
this.task.classpath(classpathFolder, jarFile("first-library.jar"),
|
||||
jarFile("second-library.jar"), jarFile("third-library.jar"));
|
||||
this.task.classpath(classpathFolder, jarFile("first-library.jar"), jarFile("second-library.jar"),
|
||||
jarFile("third-library.jar"));
|
||||
this.task.requiresUnpack("second-library.jar");
|
||||
this.task.execute();
|
||||
assertThat(getEntryNames(this.task.getArchivePath())).containsSubsequence(
|
||||
"org/springframework/boot/loader/",
|
||||
this.classesPath + "com/example/Application.class",
|
||||
this.libPath + "first-library.jar", this.libPath + "second-library.jar",
|
||||
this.libPath + "third-library.jar");
|
||||
assertThat(getEntryNames(this.task.getArchivePath())).containsSubsequence("org/springframework/boot/loader/",
|
||||
this.classesPath + "com/example/Application.class", this.libPath + "first-library.jar",
|
||||
this.libPath + "second-library.jar", this.libPath + "third-library.jar");
|
||||
}
|
||||
|
||||
protected File jarFile(String name) throws IOException {
|
||||
|
||||
@@ -32,16 +32,14 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
public class BootJarTests extends AbstractBootArchiveTests<BootJar> {
|
||||
|
||||
public BootJarTests() {
|
||||
super(BootJar.class, "org.springframework.boot.loader.JarLauncher",
|
||||
"BOOT-INF/lib/", "BOOT-INF/classes/");
|
||||
super(BootJar.class, "org.springframework.boot.loader.JarLauncher", "BOOT-INF/lib/", "BOOT-INF/classes/");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contentCanBeAddedToBootInfUsingCopySpecFromGetter() throws IOException {
|
||||
BootJar bootJar = getTask();
|
||||
bootJar.setMainClassName("com.example.Application");
|
||||
bootJar.getBootInf().into("test")
|
||||
.from(new File("build.gradle").getAbsolutePath());
|
||||
bootJar.getBootInf().into("test").from(new File("build.gradle").getAbsolutePath());
|
||||
bootJar.execute();
|
||||
try (JarFile jarFile = new JarFile(bootJar.getArchivePath())) {
|
||||
assertThat(jarFile.getJarEntry("BOOT-INF/test/build.gradle")).isNotNull();
|
||||
@@ -52,8 +50,7 @@ public class BootJarTests extends AbstractBootArchiveTests<BootJar> {
|
||||
public void contentCanBeAddedToBootInfUsingCopySpecAction() throws IOException {
|
||||
BootJar bootJar = getTask();
|
||||
bootJar.setMainClassName("com.example.Application");
|
||||
bootJar.bootInf((copySpec) -> copySpec.into("test")
|
||||
.from(new File("build.gradle").getAbsolutePath()));
|
||||
bootJar.bootInf((copySpec) -> copySpec.into("test").from(new File("build.gradle").getAbsolutePath()));
|
||||
bootJar.execute();
|
||||
try (JarFile jarFile = new JarFile(bootJar.getArchivePath())) {
|
||||
assertThat(jarFile.getJarEntry("BOOT-INF/test/build.gradle")).isNotNull();
|
||||
|
||||
@@ -32,8 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
public class BootWarTests extends AbstractBootArchiveTests<BootWar> {
|
||||
|
||||
public BootWarTests() {
|
||||
super(BootWar.class, "org.springframework.boot.loader.WarLauncher",
|
||||
"WEB-INF/lib/", "WEB-INF/classes/");
|
||||
super(BootWar.class, "org.springframework.boot.loader.WarLauncher", "WEB-INF/lib/", "WEB-INF/classes/");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -72,37 +71,30 @@ public class BootWarTests extends AbstractBootArchiveTests<BootWar> {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void devtoolsJarIsExcludedByDefaultWhenItsOnTheProvidedClasspath()
|
||||
throws IOException {
|
||||
public void devtoolsJarIsExcludedByDefaultWhenItsOnTheProvidedClasspath() throws IOException {
|
||||
getTask().setMainClassName("com.example.Main");
|
||||
getTask().providedClasspath(this.temp.newFile("spring-boot-devtools-0.1.2.jar"));
|
||||
getTask().execute();
|
||||
assertThat(getTask().getArchivePath()).exists();
|
||||
try (JarFile jarFile = new JarFile(getTask().getArchivePath())) {
|
||||
assertThat(jarFile
|
||||
.getEntry("WEB-INF/lib-provided/spring-boot-devtools-0.1.2.jar"))
|
||||
.isNull();
|
||||
assertThat(jarFile.getEntry("WEB-INF/lib-provided/spring-boot-devtools-0.1.2.jar")).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void devtoolsJarCanBeIncludedWhenItsOnTheProvidedClasspath()
|
||||
throws IOException {
|
||||
public void devtoolsJarCanBeIncludedWhenItsOnTheProvidedClasspath() throws IOException {
|
||||
getTask().setMainClassName("com.example.Main");
|
||||
getTask().providedClasspath(jarFile("spring-boot-devtools-0.1.2.jar"));
|
||||
getTask().setExcludeDevtools(false);
|
||||
getTask().execute();
|
||||
assertThat(getTask().getArchivePath()).exists();
|
||||
try (JarFile jarFile = new JarFile(getTask().getArchivePath())) {
|
||||
assertThat(jarFile
|
||||
.getEntry("WEB-INF/lib-provided/spring-boot-devtools-0.1.2.jar"))
|
||||
.isNotNull();
|
||||
assertThat(jarFile.getEntry("WEB-INF/lib-provided/spring-boot-devtools-0.1.2.jar")).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void webappResourcesInDirectoriesThatOverlapWithLoaderCanBePackaged()
|
||||
throws IOException {
|
||||
public void webappResourcesInDirectoriesThatOverlapWithLoaderCanBePackaged() throws IOException {
|
||||
File webappFolder = this.temp.newFolder("src", "main", "webapp");
|
||||
File orgFolder = new File(webappFolder, "org");
|
||||
orgFolder.mkdir();
|
||||
@@ -123,8 +115,8 @@ public class BootWarTests extends AbstractBootArchiveTests<BootWar> {
|
||||
getTask().classpath(jarFile("library.jar"));
|
||||
getTask().providedClasspath(jarFile("provided-library.jar"));
|
||||
getTask().execute();
|
||||
assertThat(getEntryNames(getTask().getArchivePath())).containsSubsequence(
|
||||
"WEB-INF/lib/library.jar", "WEB-INF/lib-provided/provided-library.jar");
|
||||
assertThat(getEntryNames(getTask().getArchivePath())).containsSubsequence("WEB-INF/lib/library.jar",
|
||||
"WEB-INF/lib-provided/provided-library.jar");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -44,50 +44,50 @@ public class LaunchScriptConfigurationTests {
|
||||
@Test
|
||||
public void initInfoProvidesUsesArchiveBaseNameByDefault() {
|
||||
given(this.task.getBaseName()).willReturn("base-name");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties())
|
||||
.containsEntry("initInfoProvides", "base-name");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoProvides",
|
||||
"base-name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initInfoShortDescriptionUsesDescriptionByDefault() {
|
||||
given(this.project.getDescription()).willReturn("Project description");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties())
|
||||
.containsEntry("initInfoShortDescription", "Project description");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoShortDescription",
|
||||
"Project description");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initInfoShortDescriptionUsesArchiveBaseNameWhenDescriptionIsNull() {
|
||||
given(this.task.getBaseName()).willReturn("base-name");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties())
|
||||
.containsEntry("initInfoShortDescription", "base-name");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoShortDescription",
|
||||
"base-name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initInfoShortDescriptionUsesSingleLineVersionOfMultiLineProjectDescription() {
|
||||
given(this.project.getDescription()).willReturn("Project\ndescription");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties())
|
||||
.containsEntry("initInfoShortDescription", "Project description");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoShortDescription",
|
||||
"Project description");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initInfoDescriptionUsesArchiveBaseNameWhenDescriptionIsNull() {
|
||||
given(this.task.getBaseName()).willReturn("base-name");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties())
|
||||
.containsEntry("initInfoDescription", "base-name");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoDescription",
|
||||
"base-name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initInfoDescriptionUsesProjectDescriptionByDefault() {
|
||||
given(this.project.getDescription()).willReturn("Project description");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties())
|
||||
.containsEntry("initInfoDescription", "Project description");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoDescription",
|
||||
"Project description");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initInfoDescriptionUsesCorrectlyFormattedMultiLineProjectDescription() {
|
||||
given(this.project.getDescription()).willReturn("The\nproject\ndescription");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties())
|
||||
.containsEntry("initInfoDescription", "The\n# project\n# description");
|
||||
assertThat(new LaunchScriptConfiguration(this.task).getProperties()).containsEntry("initInfoDescription",
|
||||
"The\n# project\n# description");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -45,23 +45,20 @@ public class MavenIntegrationTests {
|
||||
@Test
|
||||
public void bootJarCanBeUploaded() throws FileNotFoundException, IOException {
|
||||
BuildResult result = this.gradleBuild.build("uploadBootArchives");
|
||||
assertThat(result.task(":uploadBootArchives").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(result.task(":uploadBootArchives").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(artifactWithSuffix("jar")).isFile();
|
||||
assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example")
|
||||
.artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0")
|
||||
.noPackaging().noDependencies());
|
||||
.artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0").noPackaging().noDependencies());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bootWarCanBeUploaded() throws IOException {
|
||||
BuildResult result = this.gradleBuild.build("uploadBootArchives");
|
||||
assertThat(result.task(":uploadBootArchives").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(result.task(":uploadBootArchives").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(artifactWithSuffix("war")).isFile();
|
||||
assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example")
|
||||
.artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0")
|
||||
.packaging("war").noDependencies());
|
||||
assertThat(artifactWithSuffix("pom"))
|
||||
.is(pomWith().groupId("com.example").artifactId(this.gradleBuild.getProjectDir().getName())
|
||||
.version("1.0").packaging("war").noDependencies());
|
||||
}
|
||||
|
||||
private File artifactWithSuffix(String suffix) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -49,8 +49,7 @@ public class MavenPublishingIntegrationTests {
|
||||
assertThat(result.task(":publish").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(artifactWithSuffix("jar")).isFile();
|
||||
assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example")
|
||||
.artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0")
|
||||
.noPackaging().noDependencies());
|
||||
.artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0").noPackaging().noDependencies());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -58,9 +57,9 @@ public class MavenPublishingIntegrationTests {
|
||||
BuildResult result = this.gradleBuild.build("publish");
|
||||
assertThat(result.task(":publish").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(artifactWithSuffix("war")).isFile();
|
||||
assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example")
|
||||
.artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0")
|
||||
.packaging("war").noDependencies());
|
||||
assertThat(artifactWithSuffix("pom"))
|
||||
.is(pomWith().groupId("com.example").artifactId(this.gradleBuild.getProjectDir().getName())
|
||||
.version("1.0").packaging("war").noDependencies());
|
||||
}
|
||||
|
||||
private File artifactWithSuffix(String suffix) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -44,8 +44,8 @@ class PomCondition extends Condition<File> {
|
||||
}
|
||||
|
||||
private PomCondition(Set<String> expectedContents, Set<String> notExpectedContents) {
|
||||
super(new TextDescription("Pom file containing %s and not containing %s",
|
||||
expectedContents, notExpectedContents));
|
||||
super(new TextDescription("Pom file containing %s and not containing %s", expectedContents,
|
||||
notExpectedContents));
|
||||
this.expectedContents = expectedContents;
|
||||
this.notExpectedContents = notExpectedContents;
|
||||
}
|
||||
@@ -73,8 +73,8 @@ class PomCondition extends Condition<File> {
|
||||
|
||||
@Override
|
||||
public Description description() {
|
||||
return new TextDescription("Pom file containing %s and not containing %s",
|
||||
this.expectedContents, this.notExpectedContents);
|
||||
return new TextDescription("Pom file containing %s and not containing %s", this.expectedContents,
|
||||
this.notExpectedContents);
|
||||
}
|
||||
|
||||
PomCondition groupId(String groupId) {
|
||||
@@ -83,8 +83,7 @@ class PomCondition extends Condition<File> {
|
||||
}
|
||||
|
||||
PomCondition artifactId(String artifactId) {
|
||||
this.expectedContents
|
||||
.add(String.format("<artifactId>%s</artifactId>", artifactId));
|
||||
this.expectedContents.add(String.format("<artifactId>%s</artifactId>", artifactId));
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -48,12 +48,9 @@ public class BootRunIntegrationTests {
|
||||
new File(this.gradleBuild.getProjectDir(), "src/main/resources").mkdirs();
|
||||
BuildResult result = this.gradleBuild.build("bootRun");
|
||||
assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(result.getOutput())
|
||||
.contains("1. " + canonicalPathOf("build/classes/java/main"));
|
||||
assertThat(result.getOutput())
|
||||
.contains("2. " + canonicalPathOf("build/resources/main"));
|
||||
assertThat(result.getOutput())
|
||||
.doesNotContain(canonicalPathOf("src/main/resources"));
|
||||
assertThat(result.getOutput()).contains("1. " + canonicalPathOf("build/classes/java/main"));
|
||||
assertThat(result.getOutput()).contains("2. " + canonicalPathOf("build/resources/main"));
|
||||
assertThat(result.getOutput()).doesNotContain(canonicalPathOf("src/main/resources"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -61,54 +58,42 @@ public class BootRunIntegrationTests {
|
||||
copyApplication();
|
||||
BuildResult result = this.gradleBuild.build("bootRun");
|
||||
assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(result.getOutput())
|
||||
.contains("1. " + canonicalPathOf("src/main/resources"));
|
||||
assertThat(result.getOutput())
|
||||
.contains("2. " + canonicalPathOf("build/classes/java/main"));
|
||||
assertThat(result.getOutput())
|
||||
.doesNotContain(canonicalPathOf("build/resources/main"));
|
||||
assertThat(result.getOutput()).contains("1. " + canonicalPathOf("src/main/resources"));
|
||||
assertThat(result.getOutput()).contains("2. " + canonicalPathOf("build/classes/java/main"));
|
||||
assertThat(result.getOutput()).doesNotContain(canonicalPathOf("build/resources/main"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void springBootExtensionMainClassNameIsUsed() throws IOException {
|
||||
BuildResult result = this.gradleBuild.build("echoMainClassName");
|
||||
assertThat(result.task(":echoMainClassName").getOutcome())
|
||||
.isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
assertThat(result.getOutput())
|
||||
.contains("Main class name = com.example.CustomMainClass");
|
||||
assertThat(result.task(":echoMainClassName").getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
assertThat(result.getOutput()).contains("Main class name = com.example.CustomMainClass");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applicationPluginMainClassNameIsUsed() throws IOException {
|
||||
BuildResult result = this.gradleBuild.build("echoMainClassName");
|
||||
assertThat(result.task(":echoMainClassName").getOutcome())
|
||||
.isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
assertThat(result.getOutput())
|
||||
.contains("Main class name = com.example.CustomMainClass");
|
||||
assertThat(result.task(":echoMainClassName").getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
assertThat(result.getOutput()).contains("Main class name = com.example.CustomMainClass");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applicationPluginMainClassNameIsNotUsedWhenItIsNull() throws IOException {
|
||||
copyApplication();
|
||||
BuildResult result = this.gradleBuild.build("echoMainClassName");
|
||||
assertThat(result.task(":echoMainClassName").getOutcome())
|
||||
.isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(result.getOutput())
|
||||
.contains("Main class name = com.example.BootRunApplication");
|
||||
assertThat(result.task(":echoMainClassName").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
|
||||
assertThat(result.getOutput()).contains("Main class name = com.example.BootRunApplication");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applicationPluginJvmArgumentsAreUsed() throws IOException {
|
||||
BuildResult result = this.gradleBuild.build("echoJvmArguments");
|
||||
assertThat(result.task(":echoJvmArguments").getOutcome())
|
||||
.isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
assertThat(result.getOutput())
|
||||
.contains("JVM arguments = [-Dcom.foo=bar, -Dcom.bar=baz]");
|
||||
assertThat(result.task(":echoJvmArguments").getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE);
|
||||
assertThat(result.getOutput()).contains("JVM arguments = [-Dcom.foo=bar, -Dcom.bar=baz]");
|
||||
}
|
||||
|
||||
private void copyApplication() throws IOException {
|
||||
File output = new File(this.gradleBuild.getProjectDir(),
|
||||
"src/main/java/com/example");
|
||||
File output = new File(this.gradleBuild.getProjectDir(), "src/main/java/com/example");
|
||||
output.mkdirs();
|
||||
FileSystemUtils.copyRecursively(new File("src/test/java/com/example"), output);
|
||||
}
|
||||
|
||||
@@ -59,8 +59,7 @@ import org.springframework.util.FileCopyUtils;
|
||||
*/
|
||||
public class GradleBuild implements TestRule {
|
||||
|
||||
private static final Pattern GRADLE_VERSION_PATTERN = Pattern
|
||||
.compile("\\[Gradle .+\\]");
|
||||
private static final Pattern GRADLE_VERSION_PATTERN = Pattern.compile("\\[Gradle .+\\]");
|
||||
|
||||
private final TemporaryFolder temp = new TemporaryFolder();
|
||||
|
||||
@@ -116,8 +115,7 @@ public class GradleBuild implements TestRule {
|
||||
|
||||
private URL getScriptForTestMethod(Description description) {
|
||||
String name = description.getTestClass().getSimpleName() + "-"
|
||||
+ removeGradleVersion(description.getMethodName())
|
||||
+ this.dsl.getExtension();
|
||||
+ removeGradleVersion(description.getMethodName()) + this.dsl.getExtension();
|
||||
return description.getTestClass().getResource(name);
|
||||
}
|
||||
|
||||
@@ -138,10 +136,8 @@ public class GradleBuild implements TestRule {
|
||||
}
|
||||
|
||||
private List<File> pluginClasspath() {
|
||||
return Arrays.asList(new File("bin"), new File("build/classes/java/main"),
|
||||
new File("build/resources/main"),
|
||||
new File(pathOfJarContaining(LaunchScript.class)),
|
||||
new File(pathOfJarContaining(ClassVisitor.class)),
|
||||
return Arrays.asList(new File("bin"), new File("build/classes/java/main"), new File("build/resources/main"),
|
||||
new File(pathOfJarContaining(LaunchScript.class)), new File(pathOfJarContaining(ClassVisitor.class)),
|
||||
new File(pathOfJarContaining(DependencyManagementPlugin.class)),
|
||||
new File(pathOfJarContaining(PropertiesKt.class)),
|
||||
new File(pathOfJarContaining(KotlinCompilerRunner.class)),
|
||||
@@ -155,8 +151,7 @@ public class GradleBuild implements TestRule {
|
||||
}
|
||||
|
||||
public GradleBuild script(String script) {
|
||||
this.script = script.endsWith(this.dsl.getExtension()) ? script
|
||||
: script + this.dsl.getExtension();
|
||||
this.script = script.endsWith(this.dsl.getExtension()) ? script : script + this.dsl.getExtension();
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -181,10 +176,8 @@ public class GradleBuild implements TestRule {
|
||||
public GradleRunner prepareRunner(String... arguments) throws IOException {
|
||||
String scriptContent = FileCopyUtils.copyToString(new FileReader(this.script))
|
||||
.replace("{version}", getBootVersion())
|
||||
.replace("{dependency-management-plugin-version}",
|
||||
getDependencyManagementPluginVersion());
|
||||
FileCopyUtils.copy(scriptContent, new FileWriter(
|
||||
new File(this.projectDir, "build" + this.dsl.getExtension())));
|
||||
.replace("{dependency-management-plugin-version}", getDependencyManagementPluginVersion());
|
||||
FileCopyUtils.copy(scriptContent, new FileWriter(new File(this.projectDir, "build" + this.dsl.getExtension())));
|
||||
GradleRunner gradleRunner = GradleRunner.create().withProjectDir(this.projectDir)
|
||||
.withPluginClasspath(pluginClasspath());
|
||||
if (this.dsl != Dsl.KOTLIN) {
|
||||
@@ -223,29 +216,24 @@ public class GradleBuild implements TestRule {
|
||||
|
||||
private static String getBootVersion() {
|
||||
return evaluateExpression(
|
||||
"/*[local-name()='project']/*[local-name()='parent']/*[local-name()='version']"
|
||||
+ "/text()");
|
||||
"/*[local-name()='project']/*[local-name()='parent']/*[local-name()='version']" + "/text()");
|
||||
}
|
||||
|
||||
private static String getDependencyManagementPluginVersion() {
|
||||
try (FileReader pomReader = new FileReader(".flattened-pom.xml")) {
|
||||
Document pom = DocumentBuilderFactory.newInstance().newDocumentBuilder()
|
||||
.parse(new InputSource(pomReader));
|
||||
Document pom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(pomReader));
|
||||
NodeList dependencyElements = pom.getElementsByTagName("dependency");
|
||||
for (int i = 0; i < dependencyElements.getLength(); i++) {
|
||||
Element dependency = (Element) dependencyElements.item(i);
|
||||
if (dependency.getElementsByTagName("artifactId").item(0).getTextContent()
|
||||
.equals("dependency-management-plugin")) {
|
||||
return dependency.getElementsByTagName("version").item(0)
|
||||
.getTextContent();
|
||||
return dependency.getElementsByTagName("version").item(0).getTextContent();
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
"dependency management plugin version not found");
|
||||
throw new IllegalStateException("dependency management plugin version not found");
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(
|
||||
"Failed to find dependency management plugin version", ex);
|
||||
throw new IllegalStateException("Failed to find dependency management plugin version", ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -58,12 +58,11 @@ public final class BuildPropertiesWriter {
|
||||
}
|
||||
File parent = file.getParentFile();
|
||||
if (!parent.isDirectory() && !parent.mkdirs()) {
|
||||
throw new IllegalStateException("Cannot create parent directory for '"
|
||||
+ this.outputFile.getAbsolutePath() + "'");
|
||||
throw new IllegalStateException(
|
||||
"Cannot create parent directory for '" + this.outputFile.getAbsolutePath() + "'");
|
||||
}
|
||||
if (!file.createNewFile()) {
|
||||
throw new IllegalStateException("Cannot create target file '"
|
||||
+ this.outputFile.getAbsolutePath() + "'");
|
||||
throw new IllegalStateException("Cannot create target file '" + this.outputFile.getAbsolutePath() + "'");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,12 +73,10 @@ public final class BuildPropertiesWriter {
|
||||
properties.put("build.name", project.getName());
|
||||
properties.put("build.version", project.getVersion());
|
||||
if (project.getTime() != null) {
|
||||
properties.put("build.time",
|
||||
DateTimeFormatter.ISO_INSTANT.format(project.getTime()));
|
||||
properties.put("build.time", DateTimeFormatter.ISO_INSTANT.format(project.getTime()));
|
||||
}
|
||||
if (project.getAdditionalProperties() != null) {
|
||||
project.getAdditionalProperties()
|
||||
.forEach((name, value) -> properties.put("build." + name, value));
|
||||
project.getAdditionalProperties().forEach((name, value) -> properties.put("build." + name, value));
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
@@ -101,8 +98,8 @@ public final class BuildPropertiesWriter {
|
||||
|
||||
private final Map<String, String> additionalProperties;
|
||||
|
||||
public ProjectDetails(String group, String artifact, String version, String name,
|
||||
Instant time, Map<String, String> additionalProperties) {
|
||||
public ProjectDetails(String group, String artifact, String version, String name, Instant time,
|
||||
Map<String, String> additionalProperties) {
|
||||
this.group = group;
|
||||
this.artifact = artifact;
|
||||
this.name = name;
|
||||
@@ -112,8 +109,7 @@ public final class BuildPropertiesWriter {
|
||||
this.additionalProperties = additionalProperties;
|
||||
}
|
||||
|
||||
private static void validateAdditionalProperties(
|
||||
Map<String, String> additionalProperties) {
|
||||
private static void validateAdditionalProperties(Map<String, String> additionalProperties) {
|
||||
if (additionalProperties != null) {
|
||||
additionalProperties.forEach((name, value) -> {
|
||||
if (value == null) {
|
||||
@@ -152,8 +148,7 @@ public final class BuildPropertiesWriter {
|
||||
/**
|
||||
* Exception thrown when an additional property with a null value is encountered.
|
||||
*/
|
||||
public static class NullAdditionalPropertyValueException
|
||||
extends IllegalArgumentException {
|
||||
public static class NullAdditionalPropertyValueException extends IllegalArgumentException {
|
||||
|
||||
public NullAdditionalPropertyValueException(String name) {
|
||||
super("Additional property '" + name + "' is illegal as its value is null");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -42,8 +42,7 @@ public class DefaultLaunchScript implements LaunchScript {
|
||||
|
||||
private static final int BUFFER_SIZE = 4096;
|
||||
|
||||
private static final Pattern PLACEHOLDER_PATTERN = Pattern
|
||||
.compile("\\{\\{(\\w+)(:.*?)?\\}\\}(?!\\})");
|
||||
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{(\\w+)(:.*?)?\\}\\}(?!\\})");
|
||||
|
||||
private static final Set<String> FILE_PATH_KEYS = Collections
|
||||
.unmodifiableSet(Collections.singleton("inlinedConfScript"));
|
||||
@@ -79,8 +78,7 @@ public class DefaultLaunchScript implements LaunchScript {
|
||||
}
|
||||
}
|
||||
|
||||
private void copy(InputStream inputStream, OutputStream outputStream)
|
||||
throws IOException {
|
||||
private void copy(InputStream inputStream, OutputStream outputStream) throws IOException {
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
int bytesRead;
|
||||
while ((bytesRead = inputStream.read(buffer)) != -1) {
|
||||
@@ -89,8 +87,7 @@ public class DefaultLaunchScript implements LaunchScript {
|
||||
outputStream.flush();
|
||||
}
|
||||
|
||||
private String expandPlaceholders(String content, Map<?, ?> properties)
|
||||
throws IOException {
|
||||
private String expandPlaceholders(String content, Map<?, ?> properties) throws IOException {
|
||||
StringBuffer expanded = new StringBuffer();
|
||||
Matcher matcher = PLACEHOLDER_PATTERN.matcher(content);
|
||||
while (matcher.find()) {
|
||||
@@ -107,8 +104,7 @@ public class DefaultLaunchScript implements LaunchScript {
|
||||
}
|
||||
}
|
||||
else {
|
||||
value = (defaultValue != null) ? defaultValue.substring(1)
|
||||
: matcher.group(0);
|
||||
value = (defaultValue != null) ? defaultValue.substring(1) : matcher.group(0);
|
||||
}
|
||||
matcher.appendReplacement(expanded, value.replace("$", "\\$"));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -38,8 +38,7 @@ public abstract class FileUtils {
|
||||
* @param outputDirectory the output directory
|
||||
* @param originDirectory the origin directory
|
||||
*/
|
||||
public static void removeDuplicatesFromOutputDirectory(File outputDirectory,
|
||||
File originDirectory) {
|
||||
public static void removeDuplicatesFromOutputDirectory(File outputDirectory, File originDirectory) {
|
||||
if (originDirectory.isDirectory()) {
|
||||
for (String name : originDirectory.list()) {
|
||||
File targetFile = new File(outputDirectory, name);
|
||||
@@ -48,8 +47,7 @@ public abstract class FileUtils {
|
||||
targetFile.delete();
|
||||
}
|
||||
else {
|
||||
FileUtils.removeDuplicatesFromOutputDirectory(targetFile,
|
||||
new File(originDirectory, name));
|
||||
FileUtils.removeDuplicatesFromOutputDirectory(targetFile, new File(originDirectory, name));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,8 +62,8 @@ public abstract class FileUtils {
|
||||
*/
|
||||
public static String sha1Hash(File file) throws IOException {
|
||||
try {
|
||||
try (DigestInputStream inputStream = new DigestInputStream(
|
||||
new FileInputStream(file), MessageDigest.getInstance("SHA-1"))) {
|
||||
try (DigestInputStream inputStream = new DigestInputStream(new FileInputStream(file),
|
||||
MessageDigest.getInstance("SHA-1"))) {
|
||||
byte[] buffer = new byte[4098];
|
||||
while (inputStream.read(buffer) != -1) {
|
||||
// Read the entire stream
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -82,8 +82,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
* @throws IOException if the file cannot be opened
|
||||
* @throws FileNotFoundException if the file cannot be found
|
||||
*/
|
||||
public JarWriter(File file, LaunchScript launchScript)
|
||||
throws FileNotFoundException, IOException {
|
||||
public JarWriter(File file, LaunchScript launchScript) throws FileNotFoundException, IOException {
|
||||
FileOutputStream fileOutputStream = new FileOutputStream(file);
|
||||
if (launchScript != null) {
|
||||
fileOutputStream.write(launchScript.toByteArray());
|
||||
@@ -96,8 +95,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
private void setExecutableFilePermission(File file) {
|
||||
try {
|
||||
Path path = file.toPath();
|
||||
Set<PosixFilePermission> permissions = new HashSet<>(
|
||||
Files.getPosixFilePermissions(path));
|
||||
Set<PosixFilePermission> permissions = new HashSet<>(Files.getPosixFilePermissions(path));
|
||||
permissions.add(PosixFilePermission.OWNER_EXECUTE);
|
||||
Files.setPosixFilePermissions(path, permissions);
|
||||
}
|
||||
@@ -129,14 +127,13 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
this.writeEntries(jarFile, new IdentityEntryTransformer(), unpackHandler);
|
||||
}
|
||||
|
||||
void writeEntries(JarFile jarFile, EntryTransformer entryTransformer,
|
||||
UnpackHandler unpackHandler) throws IOException {
|
||||
void writeEntries(JarFile jarFile, EntryTransformer entryTransformer, UnpackHandler unpackHandler)
|
||||
throws IOException {
|
||||
Enumeration<JarEntry> entries = jarFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
JarArchiveEntry entry = new JarArchiveEntry(entries.nextElement());
|
||||
setUpEntry(jarFile, entry);
|
||||
try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(
|
||||
jarFile.getInputStream(entry))) {
|
||||
try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(jarFile.getInputStream(entry))) {
|
||||
EntryWriter entryWriter = new InputStreamEntryWriter(inputStream, true);
|
||||
JarArchiveEntry transformedEntry = entryTransformer.transform(entry);
|
||||
if (transformedEntry != null) {
|
||||
@@ -147,8 +144,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
}
|
||||
|
||||
private void setUpEntry(JarFile jarFile, JarArchiveEntry entry) throws IOException {
|
||||
try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(
|
||||
jarFile.getInputStream(entry))) {
|
||||
try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(jarFile.getInputStream(entry))) {
|
||||
if (inputStream.hasZipHeader() && entry.getMethod() != ZipEntry.STORED) {
|
||||
new CrcAndSize(inputStream).setupStoredEntry(entry);
|
||||
}
|
||||
@@ -176,8 +172,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
* @param library the library
|
||||
* @throws IOException if the write fails
|
||||
*/
|
||||
public void writeNestedLibrary(String destination, Library library)
|
||||
throws IOException {
|
||||
public void writeNestedLibrary(String destination, Library library) throws IOException {
|
||||
File file = library.getFile();
|
||||
JarArchiveEntry entry = new JarArchiveEntry(destination + library.getName());
|
||||
entry.setTime(getNestedLibraryTime(file));
|
||||
@@ -222,13 +217,11 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
@Override
|
||||
public void writeLoaderClasses(String loaderJarResourceName) throws IOException {
|
||||
URL loaderJar = getClass().getClassLoader().getResource(loaderJarResourceName);
|
||||
try (JarInputStream inputStream = new JarInputStream(
|
||||
new BufferedInputStream(loaderJar.openStream()))) {
|
||||
try (JarInputStream inputStream = new JarInputStream(new BufferedInputStream(loaderJar.openStream()))) {
|
||||
JarEntry entry;
|
||||
while ((entry = inputStream.getNextJarEntry()) != null) {
|
||||
if (entry.getName().endsWith(".class")) {
|
||||
writeEntry(new JarArchiveEntry(entry),
|
||||
new InputStreamEntryWriter(inputStream, false));
|
||||
writeEntry(new JarArchiveEntry(entry), new InputStreamEntryWriter(inputStream, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -243,8 +236,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
this.jarOutput.close();
|
||||
}
|
||||
|
||||
private void writeEntry(JarArchiveEntry entry, EntryWriter entryWriter)
|
||||
throws IOException {
|
||||
private void writeEntry(JarArchiveEntry entry, EntryWriter entryWriter) throws IOException {
|
||||
writeEntry(entry, entryWriter, NEVER_UNPACK);
|
||||
}
|
||||
|
||||
@@ -256,8 +248,8 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
* @param unpackHandler handles possible unpacking for the entry
|
||||
* @throws IOException in case of I/O errors
|
||||
*/
|
||||
private void writeEntry(JarArchiveEntry entry, EntryWriter entryWriter,
|
||||
UnpackHandler unpackHandler) throws IOException {
|
||||
private void writeEntry(JarArchiveEntry entry, EntryWriter entryWriter, UnpackHandler unpackHandler)
|
||||
throws IOException {
|
||||
String parent = entry.getName();
|
||||
if (parent.endsWith("/")) {
|
||||
parent = parent.substring(0, parent.length() - 1);
|
||||
@@ -283,16 +275,15 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
private EntryWriter addUnpackCommentIfNecessary(JarArchiveEntry entry,
|
||||
EntryWriter entryWriter, UnpackHandler unpackHandler) throws IOException {
|
||||
private EntryWriter addUnpackCommentIfNecessary(JarArchiveEntry entry, EntryWriter entryWriter,
|
||||
UnpackHandler unpackHandler) throws IOException {
|
||||
if (entryWriter == null || !unpackHandler.requiresUnpack(entry.getName())) {
|
||||
return entryWriter;
|
||||
}
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
entryWriter.write(output);
|
||||
entry.setComment("UNPACK:" + unpackHandler.sha1Hash(entry.getName()));
|
||||
return new InputStreamEntryWriter(new ByteArrayInputStream(output.toByteArray()),
|
||||
true);
|
||||
return new InputStreamEntryWriter(new ByteArrayInputStream(output.toByteArray()), true);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -357,8 +348,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
super(in);
|
||||
this.header = new byte[4];
|
||||
this.headerLength = in.read(this.header);
|
||||
this.headerStream = new ByteArrayInputStream(this.header, 0,
|
||||
this.headerLength);
|
||||
this.headerStream = new ByteArrayInputStream(this.header, 0, this.headerLength);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -381,8 +371,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable {
|
||||
|
||||
@Override
|
||||
public int read(byte[] b, int off, int len) throws IOException {
|
||||
int read = (this.headerStream != null) ? this.headerStream.read(b, off, len)
|
||||
: -1;
|
||||
int read = (this.headerStream != null) ? this.headerStream.read(b, off, len) : -1;
|
||||
if (read <= 0) {
|
||||
return readRemainder(b, off, len);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user