Upgrade to spring-javaformat 0.0.11
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -55,8 +55,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 Map<String, String> annotations;
|
||||
|
||||
@@ -69,16 +68,11 @@ 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("AutoConfigureBefore",
|
||||
"org.springframework.boot.autoconfigure.AutoConfigureBefore");
|
||||
annotations.put("AutoConfigureAfter",
|
||||
"org.springframework.boot.autoconfigure.AutoConfigureAfter");
|
||||
annotations.put("AutoConfigureOrder",
|
||||
"org.springframework.boot.autoconfigure.AutoConfigureOrder");
|
||||
annotations.put("Configuration", "org.springframework.context.annotation.Configuration");
|
||||
annotations.put("ConditionalOnClass", "org.springframework.boot.autoconfigure.condition.ConditionalOnClass");
|
||||
annotations.put("AutoConfigureBefore", "org.springframework.boot.autoconfigure.AutoConfigureBefore");
|
||||
annotations.put("AutoConfigureAfter", "org.springframework.boot.autoconfigure.AutoConfigureAfter");
|
||||
annotations.put("AutoConfigureOrder", "org.springframework.boot.autoconfigure.AutoConfigureOrder");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -87,8 +81,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());
|
||||
}
|
||||
@@ -103,36 +96,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 = getQualifiedName(element);
|
||||
AnnotationMirror annotation = getAnnotation(element, annotationName);
|
||||
if (qualifiedName != null && annotation != null) {
|
||||
List<Object> values = getValues(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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,8 +146,8 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor {
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<Object> getValues(AnnotationMirror annotation) {
|
||||
List<Object> result = new ArrayList<Object>();
|
||||
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation
|
||||
.getElementValues().entrySet()) {
|
||||
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation.getElementValues()
|
||||
.entrySet()) {
|
||||
String attributeName = entry.getKey().getSimpleName().toString();
|
||||
if ("name".equals(attributeName) || "value".equals(attributeName)) {
|
||||
Object value = entry.getValue().getValue();
|
||||
@@ -189,8 +176,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor {
|
||||
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();
|
||||
@@ -212,8 +198,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);
|
||||
OutputStream outputStream = file.openOutputStream();
|
||||
try {
|
||||
this.properties.store(outputStream, null);
|
||||
|
||||
@@ -56,16 +56,14 @@ public class AutoConfigureAnnotationProcessorTests {
|
||||
Properties properties = compile(TestClassConfiguration.class);
|
||||
assertThat(properties).hasSize(3);
|
||||
assertThat(properties).containsEntry(
|
||||
"org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration.ConditionalOnClass",
|
||||
"org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration.ConditionalOnClass",
|
||||
"java.io.InputStream,org.springframework.boot.autoconfigureprocessor."
|
||||
+ "TestClassConfiguration$Nested");
|
||||
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");
|
||||
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");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -73,38 +71,29 @@ public class AutoConfigureAnnotationProcessorTests {
|
||||
Properties properties = compile(TestMethodConfiguration.class);
|
||||
List<String> matching = new ArrayList<String>();
|
||||
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 {
|
||||
|
||||
@@ -22,8 +22,7 @@ package org.springframework.boot.autoconfigureprocessor;
|
||||
* @author Madhura Bhave
|
||||
*/
|
||||
@TestConfiguration
|
||||
@TestConditionalOnClass(name = "java.io.InputStream",
|
||||
value = TestClassConfiguration.Nested.class)
|
||||
@TestConditionalOnClass(name = "java.io.InputStream", value = TestClassConfiguration.Nested.class)
|
||||
public class TestClassConfiguration {
|
||||
|
||||
@TestAutoConfigureOrder
|
||||
|
||||
@@ -29,14 +29,12 @@ 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.autoconfigureprocessor.TestAutoConfigureBefore",
|
||||
"org.springframework.boot.autoconfigureprocessor.TestAutoConfigureAfter",
|
||||
"org.springframework.boot.autoconfigureprocessor.TestAutoConfigureOrder" })
|
||||
public class TestConditionMetadataAnnotationProcessor
|
||||
extends AutoConfigureAnnotationProcessor {
|
||||
public class TestConditionMetadataAnnotationProcessor extends AutoConfigureAnnotationProcessor {
|
||||
|
||||
private final File outputLocation;
|
||||
|
||||
|
||||
@@ -57,8 +57,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);
|
||||
}
|
||||
|
||||
@@ -74,8 +73,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.");
|
||||
}
|
||||
@@ -96,8 +95,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);
|
||||
@@ -107,16 +105,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 = getSource(metadata, 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) {
|
||||
@@ -138,20 +134,17 @@ 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());
|
||||
}
|
||||
|
||||
private ConfigurationMetadataSource getSource(RawConfigurationMetadata metadata,
|
||||
ConfigurationMetadataItem item) {
|
||||
private ConfigurationMetadataSource getSource(RawConfigurationMetadata metadata, ConfigurationMetadataItem item) {
|
||||
if (item.getSourceType() != null) {
|
||||
return metadata.getSource(item.getSourceType());
|
||||
}
|
||||
@@ -165,8 +158,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);
|
||||
@@ -187,8 +179,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -73,8 +73,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 + '\'' + '}';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -36,8 +36,7 @@ class DescriptionExtractor {
|
||||
if (dot != -1) {
|
||||
BreakIterator breakIterator = BreakIterator.getSentenceInstance(Locale.US);
|
||||
breakIterator.setText(description);
|
||||
String text = description
|
||||
.substring(breakIterator.first(), breakIterator.next()).trim();
|
||||
String text = description.substring(breakIterator.first(), breakIterator.next()).trim();
|
||||
return removeSpaceBetweenLine(text);
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -40,8 +40,7 @@ class JsonReader {
|
||||
|
||||
private final DescriptionExtractor descriptionExtractor = new DescriptionExtractor();
|
||||
|
||||
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<ConfigurationMetadataSource>();
|
||||
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<ConfigurationMetadataItem>();
|
||||
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<ConfigurationMetadataHint>();
|
||||
if (!root.has("hints")) {
|
||||
return result;
|
||||
@@ -108,8 +104,7 @@ class JsonReader {
|
||||
source.setType(json.optString("type", null));
|
||||
String description = json.optString("description", null);
|
||||
source.setDescription(description);
|
||||
source.setShortDescription(
|
||||
this.descriptionExtractor.getShortDescription(description));
|
||||
source.setShortDescription(this.descriptionExtractor.getShortDescription(description));
|
||||
source.setSourceType(json.optString("sourceType", null));
|
||||
source.setSourceMethod(json.optString("sourceMethod", null));
|
||||
return source;
|
||||
@@ -121,8 +116,7 @@ class JsonReader {
|
||||
item.setType(json.optString("type", null));
|
||||
String description = json.optString("description", null);
|
||||
item.setDescription(description);
|
||||
item.setShortDescription(
|
||||
this.descriptionExtractor.getShortDescription(description));
|
||||
item.setShortDescription(this.descriptionExtractor.getShortDescription(description));
|
||||
item.setDefaultValue(readItemValue(json.opt("defaultValue")));
|
||||
item.setDeprecation(parseDeprecation(json));
|
||||
item.setSourceType(json.optString("sourceType", null));
|
||||
@@ -141,8 +135,7 @@ class JsonReader {
|
||||
valueHint.setValue(readItemValue(value.get("value")));
|
||||
String description = value.optString("description", null);
|
||||
valueHint.setDescription(description);
|
||||
valueHint.setShortDescription(
|
||||
this.descriptionExtractor.getShortDescription(description));
|
||||
valueHint.setShortDescription(this.descriptionExtractor.getShortDescription(description));
|
||||
hint.getValueHints().add(valueHint);
|
||||
}
|
||||
}
|
||||
@@ -157,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);
|
||||
@@ -171,11 +163,9 @@ 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)));
|
||||
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 Deprecation() : null);
|
||||
|
||||
@@ -33,8 +33,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<ConfigurationMetadataSource>(sources);
|
||||
this.items = new ArrayList<ConfigurationMetadataItem>(items);
|
||||
|
||||
@@ -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<String, ConfigurationMetadataGroup>();
|
||||
|
||||
@@ -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,16 +91,12 @@ public class SimpleConfigurationMetadataRepository
|
||||
}
|
||||
else {
|
||||
// Merge properties
|
||||
for (Map.Entry<String, ConfigurationMetadataProperty> entry : group
|
||||
.getProperties().entrySet()) {
|
||||
putIfAbsent(existingGroup.getProperties(), entry.getKey(),
|
||||
entry.getValue());
|
||||
for (Map.Entry<String, ConfigurationMetadataProperty> entry : group.getProperties().entrySet()) {
|
||||
putIfAbsent(existingGroup.getProperties(), entry.getKey(), entry.getValue());
|
||||
}
|
||||
// Merge sources
|
||||
for (Map.Entry<String, ConfigurationMetadataSource> entry : group
|
||||
.getSources().entrySet()) {
|
||||
putIfAbsent(existingGroup.getSources(), entry.getKey(),
|
||||
entry.getValue());
|
||||
for (Map.Entry<String, ConfigurationMetadataSource> entry : group.getSources().entrySet()) {
|
||||
putIfAbsent(existingGroup.getSources(), entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 + '\'' + '}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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 + '}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -37,16 +37,15 @@ public abstract class AbstractConfigurationMetadataTests {
|
||||
@Rule
|
||||
public final ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
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);
|
||||
@@ -61,8 +60,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -29,8 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
extends AbstractConfigurationMetadataTests {
|
||||
public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurationMetadataTests {
|
||||
|
||||
@Test
|
||||
public void nullResource() throws IOException {
|
||||
@@ -42,12 +41,10 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
public void simpleRepository() throws IOException {
|
||||
InputStream foo = getInputStreamFor("foo");
|
||||
try {
|
||||
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);
|
||||
}
|
||||
finally {
|
||||
@@ -59,12 +56,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
public void hintsOnMaps() throws IOException {
|
||||
InputStream map = getInputStreamFor("map");
|
||||
try {
|
||||
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);
|
||||
}
|
||||
finally {
|
||||
@@ -77,14 +73,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
InputStream foo = getInputStreamFor("foo");
|
||||
InputStream bar = getInputStreamFor("bar");
|
||||
try {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(foo, bar).build();
|
||||
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);
|
||||
}
|
||||
finally {
|
||||
@@ -98,13 +92,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
InputStream foo = getInputStreamFor("foo");
|
||||
InputStream root = getInputStreamFor("root");
|
||||
try {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(foo, root).build();
|
||||
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);
|
||||
}
|
||||
finally {
|
||||
@@ -118,18 +111,16 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
InputStream foo = getInputStreamFor("foo");
|
||||
InputStream foo2 = getInputStreamFor("foo2");
|
||||
try {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(foo, foo2).build();
|
||||
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);
|
||||
}
|
||||
finally {
|
||||
@@ -142,8 +133,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
public void emptyGroups() throws IOException {
|
||||
InputStream in = getInputStreamFor("empty-groups");
|
||||
try {
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create(in).build();
|
||||
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(in).build();
|
||||
validateEmptyGroup(repo);
|
||||
assertThat(repo.getAllGroups()).hasSize(1);
|
||||
contains(repo.getAllProperties(), "name", "title");
|
||||
@@ -159,13 +149,10 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
|
||||
InputStream foo = getInputStreamFor("foo");
|
||||
InputStream bar = getInputStreamFor("bar");
|
||||
try {
|
||||
ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder
|
||||
.create();
|
||||
ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo)
|
||||
.build();
|
||||
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
|
||||
@@ -183,78 +170,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) {
|
||||
@@ -270,11 +242,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) {
|
||||
|
||||
@@ -33,22 +33,21 @@ public class DescriptionExtractorTests {
|
||||
|
||||
@Test
|
||||
public void extractShortDescription() {
|
||||
String description = this.extractor
|
||||
.getShortDescription("My short " + "description. More stuff.");
|
||||
String description = this.extractor.getShortDescription("My short " + "description. More stuff.");
|
||||
assertThat(description).isEqualTo("My short description.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractShortDescriptionNewLineBeforeDot() {
|
||||
String description = this.extractor.getShortDescription(
|
||||
"My short" + NEW_LINE + "description." + NEW_LINE + "More stuff.");
|
||||
String description = this.extractor
|
||||
.getShortDescription("My short" + NEW_LINE + "description." + NEW_LINE + "More stuff.");
|
||||
assertThat(description).isEqualTo("My short description.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractShortDescriptionNewLineBeforeDotWithSpaces() {
|
||||
String description = this.extractor.getShortDescription(
|
||||
"My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff.");
|
||||
String description = this.extractor
|
||||
.getShortDescription("My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff.");
|
||||
assertThat(description).isEqualTo("My short description.");
|
||||
}
|
||||
|
||||
@@ -60,8 +59,7 @@ public class DescriptionExtractorTests {
|
||||
|
||||
@Test
|
||||
public void extractShortDescriptionNoDotMultipleLines() {
|
||||
String description = this.extractor
|
||||
.getShortDescription("My short description " + NEW_LINE + " More stuff");
|
||||
String description = this.extractor.getShortDescription("My short description " + NEW_LINE + " More stuff");
|
||||
assertThat(description).isEqualTo("My short description");
|
||||
}
|
||||
|
||||
|
||||
@@ -82,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();
|
||||
@@ -94,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
|
||||
@@ -126,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();
|
||||
@@ -153,44 +149,35 @@ 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().getReplacement())
|
||||
.isEqualTo("server.spring.port");
|
||||
assertThat(item.getDeprecation().getReason()).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().getReplacement()).isNull();
|
||||
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()).isEqualTo(null);
|
||||
|
||||
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(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(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);
|
||||
}
|
||||
|
||||
RawConfigurationMetadata readFor(String path) throws IOException {
|
||||
|
||||
@@ -111,25 +111,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);
|
||||
@@ -148,8 +144,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) {
|
||||
@@ -161,8 +156,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,20 +167,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);
|
||||
@@ -196,10 +184,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);
|
||||
@@ -207,18 +193,15 @@ 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) {
|
||||
for (Map.Entry<String, ExecutableElement> entry : members.getPublicGetters()
|
||||
.entrySet()) {
|
||||
private void processSimpleTypes(String prefix, TypeElement element, ExecutableElement source,
|
||||
TypeElementMembers members, Map<String, Object> fieldValues) {
|
||||
for (Map.Entry<String, ExecutableElement> entry : members.getPublicGetters().entrySet()) {
|
||||
String name = entry.getKey();
|
||||
ExecutableElement getter = entry.getValue();
|
||||
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);
|
||||
@@ -227,18 +210,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) {
|
||||
@@ -246,13 +226,11 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
reason = (String) elementValues.get("reason");
|
||||
replacement = (String) elementValues.get("replacement");
|
||||
}
|
||||
return new ItemDeprecation(("".equals(reason) ? null : reason),
|
||||
("".equals(replacement) ? null : replacement));
|
||||
return new ItemDeprecation(("".equals(reason) ? null : reason), ("".equals(replacement) ? null : 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) {
|
||||
for (Map.Entry<String, VariableElement> entry : members.getFields().entrySet()) {
|
||||
String name = entry.getKey();
|
||||
VariableElement field = entry.getValue();
|
||||
@@ -260,8 +238,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
continue;
|
||||
}
|
||||
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);
|
||||
@@ -272,34 +249,30 @@ 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) {
|
||||
for (Map.Entry<String, ExecutableElement> entry : members.getPublicGetters()
|
||||
.entrySet()) {
|
||||
private void processNestedTypes(String prefix, TypeElement element, ExecutableElement source,
|
||||
TypeElementMembers members) {
|
||||
for (Map.Entry<String, ExecutableElement> entry : members.getPublicGetters().entrySet()) {
|
||||
String name = entry.getKey();
|
||||
ExecutableElement getter = entry.getValue();
|
||||
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) {
|
||||
for (Map.Entry<String, VariableElement> entry : members.getFields().entrySet()) {
|
||||
String name = entry.getKey();
|
||||
VariableElement field = entry.getValue();
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -309,8 +282,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -322,16 +294,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);
|
||||
}
|
||||
@@ -344,39 +313,32 @@ 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());
|
||||
if (returnElement != null && returnElement instanceof TypeElement
|
||||
&& annotation == null && isNested) {
|
||||
AnnotationMirror annotation = getAnnotation(getter, configurationPropertiesAnnotation());
|
||||
if (returnElement != null && 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);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isNested(Element returnType, VariableElement field,
|
||||
TypeElement element) {
|
||||
private boolean isNested(Element returnType, VariableElement field, TypeElement element) {
|
||||
if (hasAnnotation(field, nestedConfigurationPropertyAnnotation())) {
|
||||
return true;
|
||||
}
|
||||
return this.typeUtils.isEnclosedIn(returnType, element)
|
||||
&& returnType.getKind() != ElementKind.ENUM;
|
||||
return this.typeUtils.isEnclosedIn(returnType, element) && returnType.getKind() != ElementKind.ENUM;
|
||||
}
|
||||
|
||||
private boolean isDeprecated(Element element) {
|
||||
if (isElementDeprecated(element)) {
|
||||
return true;
|
||||
}
|
||||
if (element != null && (element instanceof VariableElement
|
||||
|| element instanceof ExecutableElement)) {
|
||||
if (element != null && (element instanceof VariableElement || element instanceof ExecutableElement)) {
|
||||
return isElementDeprecated(element.getEnclosingElement());
|
||||
}
|
||||
return false;
|
||||
@@ -417,10 +379,9 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
|
||||
|
||||
private Map<String, Object> getAnnotationElementValues(AnnotationMirror annotation) {
|
||||
Map<String, Object> values = new LinkedHashMap<String, Object>();
|
||||
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation
|
||||
.getElementValues().entrySet()) {
|
||||
values.put(entry.getKey().getSimpleName().toString(),
|
||||
entry.getValue().getValue());
|
||||
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation.getElementValues()
|
||||
.entrySet()) {
|
||||
values.put(entry.getKey().getSimpleName().toString(), entry.getValue().getValue());
|
||||
}
|
||||
return values;
|
||||
}
|
||||
@@ -435,8 +396,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());
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -88,8 +88,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 {
|
||||
@@ -98,46 +97,40 @@ public class MetadataStore {
|
||||
}
|
||||
|
||||
private FileObject getMetadataResource() throws IOException {
|
||||
FileObject resource = this.environment.getFiler()
|
||||
.getResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH);
|
||||
FileObject resource = this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH);
|
||||
return resource;
|
||||
}
|
||||
|
||||
private FileObject createMetadataResource() throws IOException {
|
||||
FileObject resource = this.environment.getFiler()
|
||||
.createResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH);
|
||||
FileObject resource = this.environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "",
|
||||
METADATA_PATH);
|
||||
return resource;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -59,8 +59,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;
|
||||
@@ -68,17 +67,14 @@ 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 {
|
||||
Map<String, Object> fieldValues = this.fieldValuesParser
|
||||
.getFieldValues(element);
|
||||
Map<String, Object> fieldValues = this.fieldValuesParser.getFieldValues(element);
|
||||
for (Map.Entry<String, Object> entry : fieldValues.entrySet()) {
|
||||
if (!this.fieldValues.containsKey(entry.getKey())) {
|
||||
this.fieldValues.put(entry.getKey(), entry.getValue());
|
||||
@@ -90,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);
|
||||
}
|
||||
}
|
||||
@@ -104,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<ExecutableElement>();
|
||||
this.publicSetters.put(propertyName, matchingSetters);
|
||||
@@ -118,8 +112,7 @@ class TypeElementMembers {
|
||||
}
|
||||
}
|
||||
|
||||
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)) {
|
||||
@@ -131,27 +124,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;
|
||||
}
|
||||
@@ -179,8 +169,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,14 +83,12 @@ class TypeUtils {
|
||||
this.mapType = getDeclaredType(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];
|
||||
for (int i = 0; i < typeArgs.length; i++) {
|
||||
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);
|
||||
}
|
||||
@@ -139,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 = javadoc.replaceAll("[\r\n]+", "").trim();
|
||||
}
|
||||
@@ -150,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) {
|
||||
@@ -184,8 +180,7 @@ class TypeUtils {
|
||||
public String visitDeclared(DeclaredType type, Void none) {
|
||||
TypeElement enclosingElement = getEnclosingTypeElement(type);
|
||||
if (enclosingElement != null) {
|
||||
return getQualifiedName(enclosingElement) + "$"
|
||||
+ type.asElement().getSimpleName().toString();
|
||||
return getQualifiedName(enclosingElement) + "$" + type.asElement().getSimpleName().toString();
|
||||
}
|
||||
String qualifiedName = getQualifiedName(type.asElement());
|
||||
if (type.getTypeArguments().isEmpty()) {
|
||||
@@ -228,14 +223,12 @@ class TypeUtils {
|
||||
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();
|
||||
}
|
||||
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) {
|
||||
|
||||
@@ -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(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();
|
||||
}
|
||||
|
||||
@@ -122,8 +122,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;
|
||||
|
||||
@@ -67,8 +67,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);
|
||||
}
|
||||
|
||||
@@ -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 GET_CLASS_TREE_MEMBERS = findMethod(
|
||||
findClass("com.sun.source.tree.ClassTree"), "getMembers");
|
||||
private final Method GET_CLASS_TREE_MEMBERS = 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,16 +56,13 @@ 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")) {
|
||||
if ((Integer) args[1] == 0) {
|
||||
Iterable members = (Iterable) Tree.this.GET_CLASS_TREE_MEMBERS
|
||||
.invoke(args[0]);
|
||||
Iterable members = (Iterable) Tree.this.GET_CLASS_TREE_MEMBERS.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -169,8 +169,7 @@ public class ConfigurationMetadata {
|
||||
|
||||
private List<ItemMetadata> getCandidates(String name) {
|
||||
List<ItemMetadata> candidates = this.items.get(name);
|
||||
return (candidates != null) ? new ArrayList<ItemMetadata>(candidates)
|
||||
: new ArrayList<ItemMetadata>();
|
||||
return (candidates != null) ? new ArrayList<ItemMetadata>(candidates) : new ArrayList<ItemMetadata>();
|
||||
}
|
||||
|
||||
private boolean nullSafeEquals(Object o1, Object o2) {
|
||||
@@ -194,8 +193,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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -44,10 +44,8 @@ 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<ValueHint>(values)
|
||||
: new ArrayList<ValueHint>();
|
||||
this.providers = (providers != null) ? new ArrayList<ValueProvider>(providers)
|
||||
: new ArrayList<ValueProvider>();
|
||||
this.values = (values != null) ? new ArrayList<ValueHint>(values) : new ArrayList<ValueHint>();
|
||||
this.providers = (providers != null) ? new ArrayList<ValueProvider>(providers) : new ArrayList<ValueProvider>();
|
||||
}
|
||||
|
||||
private String toCanonicalName(String name) {
|
||||
@@ -78,14 +76,12 @@ public class ItemHint implements Comparable<ItemHint> {
|
||||
}
|
||||
|
||||
public static ItemHint newHint(String name, ValueHint... values) {
|
||||
return new ItemHint(name, Arrays.asList(values),
|
||||
Collections.<ValueProvider>emptyList());
|
||||
return new ItemHint(name, Arrays.asList(values), Collections.<ValueProvider>emptyList());
|
||||
}
|
||||
|
||||
@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 + '}';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,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 + '\'' + '}';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -142,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 + '}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -42,9 +42,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) {
|
||||
super();
|
||||
this.itemType = itemType;
|
||||
this.name = buildName(prefix, name);
|
||||
@@ -132,8 +131,7 @@ public final class ItemMetadata implements Comparable<ItemMetadata> {
|
||||
this.deprecation = deprecation;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -148,10 +146,8 @@ public final class ItemMetadata implements Comparable<ItemMetadata> {
|
||||
return false;
|
||||
}
|
||||
ItemMetadata other = (ItemMetadata) o;
|
||||
return nullSafeEquals(this.itemType, other.itemType)
|
||||
&& nullSafeEquals(this.name, other.name)
|
||||
&& nullSafeEquals(this.type, other.type)
|
||||
&& nullSafeEquals(this.description, other.description)
|
||||
return nullSafeEquals(this.itemType, other.itemType) && nullSafeEquals(this.name, other.name)
|
||||
&& nullSafeEquals(this.type, other.type) && nullSafeEquals(this.description, other.description)
|
||||
&& nullSafeEquals(this.sourceType, other.sourceType)
|
||||
&& nullSafeEquals(this.sourceMethod, other.sourceMethod)
|
||||
&& nullSafeEquals(this.defaultValue, other.defaultValue)
|
||||
@@ -201,17 +197,14 @@ 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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -32,8 +32,7 @@ import org.springframework.boot.configurationprocessor.metadata.ItemMetadata.Ite
|
||||
*/
|
||||
class JsonConverter {
|
||||
|
||||
public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType)
|
||||
throws Exception {
|
||||
public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) throws Exception {
|
||||
JSONArray jsonArray = new JSONArray();
|
||||
for (ItemMetadata item : metadata.getItems()) {
|
||||
if (item.isOfItemType(itemType)) {
|
||||
@@ -115,8 +114,7 @@ class JsonConverter {
|
||||
return providers;
|
||||
}
|
||||
|
||||
private JSONObject getItemHintProvider(ItemHint.ValueProvider provider)
|
||||
throws Exception {
|
||||
private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) throws Exception {
|
||||
JSONObject result = new JSONOrderedObject();
|
||||
result.put("name", provider.getName());
|
||||
if (provider.getParameters() != null && !provider.getParameters().isEmpty()) {
|
||||
@@ -129,8 +127,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);
|
||||
}
|
||||
|
||||
@@ -44,8 +44,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 JSONOrderedObject();
|
||||
JsonConverter converter = new JsonConverter();
|
||||
@@ -77,8 +76,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");
|
||||
@@ -90,8 +88,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);
|
||||
@@ -99,8 +96,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 {
|
||||
@@ -109,8 +106,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);
|
||||
|
||||
@@ -114,15 +114,12 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
@Test
|
||||
public void simpleProperties() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withGroup("simple").fromSource(SimpleProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimpleProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class)
|
||||
.fromSource(SimpleProperties.class)
|
||||
.withDescription("The name of this simple properties.")
|
||||
.fromSource(SimpleProperties.class).withDescription("The name of this simple properties.")
|
||||
.withDefaultValue("boot").withDeprecation(null, null));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class)
|
||||
.fromSource(SimpleProperties.class).withDescription("A simple flag.")
|
||||
.withDeprecation(null, null));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).fromSource(SimpleProperties.class)
|
||||
.withDescription("A simple flag.").withDeprecation(null, null));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.comparator"));
|
||||
assertThat(metadata).doesNotHave(Metadata.withProperty("simple.counter"));
|
||||
assertThat(metadata).doesNotHave(Metadata.withProperty("simple.size"));
|
||||
@@ -131,78 +128,54 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
@Test
|
||||
public void simplePrefixValueProperties() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class);
|
||||
assertThat(metadata).has(Metadata.withGroup("simple")
|
||||
.fromSource(SimplePrefixValueProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.name", String.class)
|
||||
.fromSource(SimplePrefixValueProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimplePrefixValueProperties.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.name", String.class).fromSource(SimplePrefixValueProperties.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void simpleTypeProperties() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(SimpleTypeProperties.class);
|
||||
assertThat(metadata).has(
|
||||
Metadata.withGroup("simple.type").fromSource(SimpleTypeProperties.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-string", String.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-byte", Byte.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-char", Character.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("simple.type.my-primitive-char", Character.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-boolean", Boolean.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-short", Short.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("simple.type.my-primitive-short", Short.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-integer", Integer.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("simple.type.my-primitive-integer", Integer.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-long", Long.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-primitive-long", Long.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-double", Double.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("simple.type.my-primitive-double", Double.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.type.my-float", Float.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("simple.type.my-primitive-float", Float.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("simple.type").fromSource(SimpleTypeProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-string", String.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-byte", Byte.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-char", Character.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-char", Character.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-boolean", Boolean.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-short", Short.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-short", Short.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-integer", Integer.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-integer", Integer.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-long", Long.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-long", Long.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-double", Double.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-double", Double.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-float", Float.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-float", Float.class));
|
||||
assertThat(metadata.getItems().size()).isEqualTo(18);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hierarchicalProperties() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(HierarchicalProperties.class);
|
||||
assertThat(metadata).has(Metadata.withGroup("hierarchical")
|
||||
.fromSource(HierarchicalProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class)
|
||||
.fromSource(HierarchicalProperties.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("hierarchical.second", String.class)
|
||||
.fromSource(HierarchicalProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class)
|
||||
.fromSource(HierarchicalProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("hierarchical").fromSource(HierarchicalProperties.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("hierarchical.first", String.class).fromSource(HierarchicalProperties.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("hierarchical.second", String.class).fromSource(HierarchicalProperties.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("hierarchical.third", String.class).fromSource(HierarchicalProperties.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void descriptionProperties() {
|
||||
ConfigurationMetadata metadata = compile(DescriptionProperties.class);
|
||||
assertThat(metadata).has(Metadata.withGroup("description")
|
||||
.fromSource(DescriptionProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("description").fromSource(DescriptionProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("description.simple", String.class)
|
||||
.fromSource(DescriptionProperties.class)
|
||||
.withDescription("A simple description."));
|
||||
assertThat(metadata).has(Metadata
|
||||
.withProperty("description.multi-line", String.class)
|
||||
.fromSource(DescriptionProperties.class).withDescription("A simple description."));
|
||||
assertThat(metadata).has(Metadata.withProperty("description.multi-line", String.class)
|
||||
.fromSource(DescriptionProperties.class).withDescription(
|
||||
"This is a lengthy description that spans across multiple lines to showcase that the line separators are cleaned automatically."));
|
||||
}
|
||||
@@ -213,11 +186,10 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
Class<?> type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class;
|
||||
ConfigurationMetadata metadata = compile(type);
|
||||
assertThat(metadata).has(Metadata.withGroup("deprecated").fromSource(type));
|
||||
assertThat(metadata).has(Metadata.withProperty("deprecated.name", String.class)
|
||||
.fromSource(type).withDeprecation(null, null));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("deprecated.description", String.class)
|
||||
.fromSource(type).withDeprecation(null, null));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("deprecated.name", String.class).fromSource(type).withDeprecation(null, null));
|
||||
assertThat(metadata).has(Metadata.withProperty("deprecated.description", String.class).fromSource(type)
|
||||
.withDeprecation(null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -225,11 +197,8 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
Class<?> type = DeprecatedSingleProperty.class;
|
||||
ConfigurationMetadata metadata = compile(type);
|
||||
assertThat(metadata).has(Metadata.withGroup("singledeprecated").fromSource(type));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("singledeprecated.new-name", String.class)
|
||||
.fromSource(type));
|
||||
assertThat(metadata).has(Metadata
|
||||
.withProperty("singledeprecated.name", String.class).fromSource(type)
|
||||
assertThat(metadata).has(Metadata.withProperty("singledeprecated.new-name", String.class).fromSource(type));
|
||||
assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class).fromSource(type)
|
||||
.withDeprecation("renamed", "singledeprecated.new-name"));
|
||||
}
|
||||
|
||||
@@ -238,12 +207,10 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
Class<?> type = DeprecatedUnrelatedMethodPojo.class;
|
||||
ConfigurationMetadata metadata = compile(type);
|
||||
assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("not.deprecated.counter", Integer.class).withNoDeprecation().fromSource(type));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("not.deprecated.counter", Integer.class)
|
||||
.withNoDeprecation().fromSource(type));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("not.deprecated.flag", Boolean.class)
|
||||
.withNoDeprecation().fromSource(type));
|
||||
.has(Metadata.withProperty("not.deprecated.flag", Boolean.class).withNoDeprecation().fromSource(type));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -251,10 +218,8 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
Class<?> type = BoxingPojo.class;
|
||||
ConfigurationMetadata metadata = compile(type);
|
||||
assertThat(metadata).has(Metadata.withGroup("boxing").fromSource(type));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("boxing.flag", Boolean.class).fromSource(type));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("boxing.counter", Integer.class).fromSource(type));
|
||||
assertThat(metadata).has(Metadata.withProperty("boxing.flag", Boolean.class).fromSource(type));
|
||||
assertThat(metadata).has(Metadata.withProperty("boxing.counter", Integer.class).fromSource(type));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -263,17 +228,13 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
// getter and setter
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.integers-to-names",
|
||||
"java.util.Map<java.lang.Integer,java.lang.String>"));
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.longs",
|
||||
"java.util.Collection<java.lang.Long>"));
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.floats",
|
||||
"java.util.List<java.lang.Float>"));
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.longs", "java.util.Collection<java.lang.Long>"));
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.floats", "java.util.List<java.lang.Float>"));
|
||||
// getter only
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.names-to-integers",
|
||||
"java.util.Map<java.lang.String,java.lang.Integer>"));
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.bytes",
|
||||
"java.util.Collection<java.lang.Byte>"));
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.doubles",
|
||||
"java.util.List<java.lang.Double>"));
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.bytes", "java.util.Collection<java.lang.Byte>"));
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.doubles", "java.util.List<java.lang.Double>"));
|
||||
assertThat(metadata).has(Metadata.withProperty("collection.names-to-holders",
|
||||
"java.util.Map<java.lang.String,org.springframework.boot.configurationsample.simple.SimpleCollectionProperties.Holder<java.lang.String>>"));
|
||||
}
|
||||
@@ -281,47 +242,43 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
@Test
|
||||
public void parseArrayConfig() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(SimpleArrayProperties.class);
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withGroup("array").ofType(SimpleArrayProperties.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("array.primitive", "java.lang.Integer[]"));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("array.simple", "java.lang.String[]"));
|
||||
assertThat(metadata).has(Metadata.withGroup("array").ofType(SimpleArrayProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("array.primitive", "java.lang.Integer[]"));
|
||||
assertThat(metadata).has(Metadata.withProperty("array.simple", "java.lang.String[]"));
|
||||
assertThat(metadata).has(Metadata.withProperty("array.inner",
|
||||
"org.springframework.boot.configurationsample.simple.SimpleArrayProperties$Holder[]"));
|
||||
assertThat(metadata).has(Metadata.withProperty("array.name-to-integer",
|
||||
"java.util.Map<java.lang.String,java.lang.Integer>[]"));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("array.name-to-integer", "java.util.Map<java.lang.String,java.lang.Integer>[]"));
|
||||
assertThat(metadata.getItems()).hasSize(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void simpleMethodConfig() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(SimpleMethodConfig.class);
|
||||
assertThat(metadata).has(Metadata.withGroup("foo").fromSource(SimpleMethodConfig.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withGroup("foo").fromSource(SimpleMethodConfig.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.name", String.class)
|
||||
.fromSource(SimpleMethodConfig.Foo.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class)
|
||||
.fromSource(SimpleMethodConfig.Foo.class));
|
||||
.has(Metadata.withProperty("foo.name", String.class).fromSource(SimpleMethodConfig.Foo.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("foo.flag", Boolean.class).fromSource(SimpleMethodConfig.Foo.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidMethodConfig() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(InvalidMethodConfig.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("something.name", String.class)
|
||||
.fromSource(InvalidMethodConfig.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("something.name", String.class).fromSource(InvalidMethodConfig.class));
|
||||
assertThat(metadata).isNotEqualTo(Metadata.withProperty("invalid.name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void methodAndClassConfig() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(MethodAndClassConfig.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("conflict.name", String.class)
|
||||
.fromSource(MethodAndClassConfig.Foo.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class)
|
||||
.fromSource(MethodAndClassConfig.Foo.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("conflict.value", String.class)
|
||||
.fromSource(MethodAndClassConfig.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("conflict.name", String.class).fromSource(MethodAndClassConfig.Foo.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("conflict.flag", Boolean.class).fromSource(MethodAndClassConfig.Foo.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("conflict.value", String.class).fromSource(MethodAndClassConfig.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -336,11 +293,9 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
ConfigurationMetadata metadata = compile(type);
|
||||
assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.name", String.class)
|
||||
.fromSource(DeprecatedMethodConfig.Foo.class)
|
||||
.withDeprecation(null, null));
|
||||
.fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class)
|
||||
.fromSource(DeprecatedMethodConfig.Foo.class)
|
||||
.withDeprecation(null, null));
|
||||
.fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -350,12 +305,10 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
ConfigurationMetadata metadata = compile(type);
|
||||
assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.name", String.class)
|
||||
.fromSource(
|
||||
org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class)
|
||||
.fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class)
|
||||
.withDeprecation(null, null));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class)
|
||||
.fromSource(
|
||||
org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class)
|
||||
.fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class)
|
||||
.withDeprecation(null, null));
|
||||
}
|
||||
|
||||
@@ -368,20 +321,17 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
@Test
|
||||
public void innerClassProperties() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(InnerClassProperties.class);
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withGroup("config").fromSource(InnerClassProperties.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class)
|
||||
.fromSource(InnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("config").fromSource(InnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class)
|
||||
.fromSource(InnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.first.name"));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.first.bar.name"));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withGroup("config.the-second", InnerClassProperties.Foo.class)
|
||||
.fromSource(InnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("config.the-second", InnerClassProperties.Foo.class)
|
||||
.fromSource(InnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.the-second.name"));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.the-second.bar.name"));
|
||||
assertThat(metadata).has(Metadata.withGroup("config.third")
|
||||
.ofType(SimplePojo.class).fromSource(InnerClassProperties.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withGroup("config.third").ofType(SimplePojo.class).fromSource(InnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.third.value"));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.fourth"));
|
||||
assertThat(metadata).isNotEqualTo(Metadata.withGroup("config.fourth"));
|
||||
@@ -398,16 +348,12 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
@Test
|
||||
public void nestedClassChildProperties() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(ClassWithNestedProperties.class);
|
||||
assertThat(metadata).has(Metadata.withGroup("nestedChildProps")
|
||||
.fromSource(ClassWithNestedProperties.NestedChildClass.class));
|
||||
assertThat(metadata).has(Metadata
|
||||
.withProperty("nestedChildProps.child-class-property", Integer.class)
|
||||
.fromSource(ClassWithNestedProperties.NestedChildClass.class)
|
||||
.withDefaultValue(20));
|
||||
assertThat(metadata).has(Metadata
|
||||
.withProperty("nestedChildProps.parent-class-property", Integer.class)
|
||||
.fromSource(ClassWithNestedProperties.NestedChildClass.class)
|
||||
.withDefaultValue(10));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withGroup("nestedChildProps").fromSource(ClassWithNestedProperties.NestedChildClass.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("nestedChildProps.child-class-property", Integer.class)
|
||||
.fromSource(ClassWithNestedProperties.NestedChildClass.class).withDefaultValue(20));
|
||||
assertThat(metadata).has(Metadata.withProperty("nestedChildProps.parent-class-property", Integer.class)
|
||||
.fromSource(ClassWithNestedProperties.NestedChildClass.class).withDefaultValue(10));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -454,40 +400,36 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
@Test
|
||||
public void genericTypes() throws IOException {
|
||||
ConfigurationMetadata metadata = compile(GenericConfig.class);
|
||||
assertThat(metadata).has(Metadata.withGroup("generic").ofType(
|
||||
"org.springframework.boot.configurationsample.specific.GenericConfig"));
|
||||
assertThat(metadata).has(Metadata.withGroup("generic.foo").ofType(
|
||||
"org.springframework.boot.configurationsample.specific.GenericConfig$Foo"));
|
||||
assertThat(metadata).has(Metadata.withGroup("generic.foo.bar").ofType(
|
||||
"org.springframework.boot.configurationsample.specific.GenericConfig$Bar"));
|
||||
assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz").ofType(
|
||||
"org.springframework.boot.configurationsample.specific.GenericConfig$Bar$Biz"));
|
||||
assertThat(metadata).has(Metadata.withProperty("generic.foo.name")
|
||||
.ofType(String.class).fromSource(GenericConfig.Foo.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar")
|
||||
.ofType("java.util.Map<java.lang.String,org.springframework.boot.configurationsample.specific.GenericConfig.Bar<java.lang.Integer>>")
|
||||
assertThat(metadata).has(Metadata.withGroup("generic")
|
||||
.ofType("org.springframework.boot.configurationsample.specific.GenericConfig"));
|
||||
assertThat(metadata).has(Metadata.withGroup("generic.foo")
|
||||
.ofType("org.springframework.boot.configurationsample.specific.GenericConfig$Foo"));
|
||||
assertThat(metadata).has(Metadata.withGroup("generic.foo.bar")
|
||||
.ofType("org.springframework.boot.configurationsample.specific.GenericConfig$Bar"));
|
||||
assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz")
|
||||
.ofType("org.springframework.boot.configurationsample.specific.GenericConfig$Bar$Biz"));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("generic.foo.name").ofType(String.class).fromSource(GenericConfig.Foo.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar").ofType(
|
||||
"java.util.Map<java.lang.String,org.springframework.boot.configurationsample.specific.GenericConfig.Bar<java.lang.Integer>>")
|
||||
.fromSource(GenericConfig.Foo.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-integer")
|
||||
.ofType("java.util.Map<java.lang.String,java.lang.Integer>")
|
||||
.fromSource(GenericConfig.Foo.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name")
|
||||
.ofType("java.lang.String").fromSource(GenericConfig.Bar.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name")
|
||||
.ofType("java.lang.String").fromSource(GenericConfig.Bar.Biz.class));
|
||||
.ofType("java.util.Map<java.lang.String,java.lang.Integer>").fromSource(GenericConfig.Foo.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name").ofType("java.lang.String")
|
||||
.fromSource(GenericConfig.Bar.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name").ofType("java.lang.String")
|
||||
.fromSource(GenericConfig.Bar.Biz.class));
|
||||
assertThat(metadata.getItems()).hasSize(9);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wildcardTypes() throws IOException {
|
||||
ConfigurationMetadata metadata = compile(WildcardConfig.class);
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("wildcard.string-to-number")
|
||||
.ofType("java.util.Map<java.lang.String,? extends java.lang.Number>")
|
||||
.fromSource(WildcardConfig.class));
|
||||
.ofType("java.util.Map<java.lang.String,? extends java.lang.Number>").fromSource(WildcardConfig.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("wildcard.integers")
|
||||
.ofType("java.util.List<? super java.lang.Integer>")
|
||||
.fromSource(WildcardConfig.class));
|
||||
.ofType("java.util.List<? super java.lang.Integer>").fromSource(WildcardConfig.class));
|
||||
assertThat(metadata.getItems()).hasSize(3);
|
||||
}
|
||||
|
||||
@@ -506,63 +448,51 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
@Test
|
||||
public void lombokExplicitProperties() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(LombokExplicitProperties.class);
|
||||
assertSimpleLombokProperties(metadata, LombokExplicitProperties.class,
|
||||
"explicit");
|
||||
assertSimpleLombokProperties(metadata, LombokExplicitProperties.class, "explicit");
|
||||
assertThat(metadata.getItems()).hasSize(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lombokAccessLevelProperties() {
|
||||
ConfigurationMetadata metadata = compile(LombokAccessLevelProperties.class);
|
||||
assertAccessLevelLombokProperties(metadata, LombokAccessLevelProperties.class,
|
||||
"accesslevel", 2);
|
||||
assertAccessLevelLombokProperties(metadata, LombokAccessLevelProperties.class, "accesslevel", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lombokAccessLevelOverwriteDataProperties() {
|
||||
ConfigurationMetadata metadata = compile(
|
||||
LombokAccessLevelOverwriteDataProperties.class);
|
||||
assertAccessLevelOverwriteLombokProperties(metadata,
|
||||
LombokAccessLevelOverwriteDataProperties.class,
|
||||
ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteDataProperties.class);
|
||||
assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteDataProperties.class,
|
||||
"accesslevel.overwrite.data");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lombokAccessLevelOverwriteExplicitProperties() {
|
||||
ConfigurationMetadata metadata = compile(
|
||||
LombokAccessLevelOverwriteExplicitProperties.class);
|
||||
assertAccessLevelOverwriteLombokProperties(metadata,
|
||||
LombokAccessLevelOverwriteExplicitProperties.class,
|
||||
ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteExplicitProperties.class);
|
||||
assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteExplicitProperties.class,
|
||||
"accesslevel.overwrite.explicit");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lombokAccessLevelOverwriteDefaultProperties() {
|
||||
ConfigurationMetadata metadata = compile(
|
||||
LombokAccessLevelOverwriteDefaultProperties.class);
|
||||
assertAccessLevelOverwriteLombokProperties(metadata,
|
||||
LombokAccessLevelOverwriteDefaultProperties.class,
|
||||
ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteDefaultProperties.class);
|
||||
assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteDefaultProperties.class,
|
||||
"accesslevel.overwrite.default");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lombokInnerClassProperties() throws Exception {
|
||||
ConfigurationMetadata metadata = compile(LombokInnerClassProperties.class);
|
||||
assertThat(metadata).has(Metadata.withGroup("config")
|
||||
.fromSource(LombokInnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("config.first")
|
||||
.ofType(LombokInnerClassProperties.Foo.class)
|
||||
assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("config.first").ofType(LombokInnerClassProperties.Foo.class)
|
||||
.fromSource(LombokInnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.first.name"));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.first.bar.name"));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withGroup("config.second", LombokInnerClassProperties.Foo.class)
|
||||
.fromSource(LombokInnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("config.second", LombokInnerClassProperties.Foo.class)
|
||||
.fromSource(LombokInnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.second.name"));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.second.bar.name"));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withGroup("config.third").ofType(SimpleLombokPojo.class)
|
||||
.fromSource(LombokInnerClassProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("config.third").ofType(SimpleLombokPojo.class)
|
||||
.fromSource(LombokInnerClassProperties.class));
|
||||
// For some reason the annotation processor resolves a type for SimpleLombokPojo
|
||||
// that is resolved (compiled) and the source annotations are gone. Because we
|
||||
// don't see the @Data annotation anymore, no field is harvested. What is crazy is
|
||||
@@ -575,14 +505,11 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
|
||||
@Test
|
||||
public void lombokInnerClassWithGetterProperties() throws IOException {
|
||||
ConfigurationMetadata metadata = compile(
|
||||
LombokInnerClassWithGetterProperties.class);
|
||||
assertThat(metadata).has(Metadata.withGroup("config")
|
||||
.fromSource(LombokInnerClassWithGetterProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("config.first")
|
||||
.ofType(LombokInnerClassWithGetterProperties.Foo.class)
|
||||
.fromSourceMethod("getFirst()")
|
||||
.fromSource(LombokInnerClassWithGetterProperties.class));
|
||||
ConfigurationMetadata metadata = compile(LombokInnerClassWithGetterProperties.class);
|
||||
assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassWithGetterProperties.class));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withGroup("config.first").ofType(LombokInnerClassWithGetterProperties.Foo.class)
|
||||
.fromSourceMethod("getFirst()").fromSource(LombokInnerClassWithGetterProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("config.first.name"));
|
||||
assertThat(metadata.getItems()).hasSize(3);
|
||||
}
|
||||
@@ -594,84 +521,72 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
writeAdditionalMetadata(property);
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.comparator"));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo", String.class)
|
||||
.fromSource(AdditionalMetadata.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo", String.class).fromSource(AdditionalMetadata.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mergingOfAdditionalPropertyMatchingGroup() throws Exception {
|
||||
ItemMetadata property = ItemMetadata.newProperty(null, "simple",
|
||||
"java.lang.String", null, null, null, null, null);
|
||||
ItemMetadata property = ItemMetadata.newProperty(null, "simple", "java.lang.String", null, null, null, null,
|
||||
null);
|
||||
writeAdditionalMetadata(property);
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withGroup("simple").fromSource(SimpleProperties.class));
|
||||
assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimpleProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple", String.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mergeExistingPropertyDefaultValue() throws Exception {
|
||||
ItemMetadata property = ItemMetadata.newProperty("simple", "flag", null, null,
|
||||
null, null, true, null);
|
||||
ItemMetadata property = ItemMetadata.newProperty("simple", "flag", null, null, null, null, true, null);
|
||||
writeAdditionalMetadata(property);
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class)
|
||||
.fromSource(SimpleProperties.class).withDescription("A simple flag.")
|
||||
.withDeprecation(null, null).withDefaultValue(true));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).fromSource(SimpleProperties.class)
|
||||
.withDescription("A simple flag.").withDeprecation(null, null).withDefaultValue(true));
|
||||
assertThat(metadata.getItems()).hasSize(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mergeExistingPropertyDescription() throws Exception {
|
||||
ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null,
|
||||
null, null, "A nice comparator.", null, null);
|
||||
ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, null, null, "A nice comparator.",
|
||||
null, null);
|
||||
writeAdditionalMetadata(property);
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.comparator", "java.util.Comparator<?>")
|
||||
.fromSource(SimpleProperties.class)
|
||||
.withDescription("A nice comparator."));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.comparator", "java.util.Comparator<?>")
|
||||
.fromSource(SimpleProperties.class).withDescription("A nice comparator."));
|
||||
assertThat(metadata.getItems()).hasSize(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mergeExistingPropertyDeprecation() throws Exception {
|
||||
ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null,
|
||||
null, null, null, null, new ItemDeprecation("Don't use this.",
|
||||
"simple.complex-comparator", "error"));
|
||||
ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, null, null, null, null,
|
||||
new ItemDeprecation("Don't use this.", "simple.complex-comparator", "error"));
|
||||
writeAdditionalMetadata(property);
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty("simple.comparator", "java.util.Comparator<?>")
|
||||
.fromSource(SimpleProperties.class).withDeprecation(
|
||||
"Don't use this.", "simple.complex-comparator", "error"));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("simple.comparator", "java.util.Comparator<?>").fromSource(SimpleProperties.class)
|
||||
.withDeprecation("Don't use this.", "simple.complex-comparator", "error"));
|
||||
assertThat(metadata.getItems()).hasSize(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mergeExistingPropertyDeprecationOverride() throws Exception {
|
||||
ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null,
|
||||
null, null, null, null,
|
||||
ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, null, null, null, null,
|
||||
new ItemDeprecation("Don't use this.", "single.name"));
|
||||
writeAdditionalMetadata(property);
|
||||
ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class);
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("singledeprecated.name", String.class.getName())
|
||||
.fromSource(DeprecatedSingleProperty.class)
|
||||
.withDeprecation("Don't use this.", "single.name"));
|
||||
assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class.getName())
|
||||
.fromSource(DeprecatedSingleProperty.class).withDeprecation("Don't use this.", "single.name"));
|
||||
assertThat(metadata.getItems()).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mergeExistingPropertyDeprecationOverrideLevel() throws Exception {
|
||||
ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null,
|
||||
null, null, null, null, new ItemDeprecation(null, null, "error"));
|
||||
ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, null, null, null, null,
|
||||
new ItemDeprecation(null, null, "error"));
|
||||
writeAdditionalMetadata(property);
|
||||
ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class);
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("singledeprecated.name", String.class.getName())
|
||||
.fromSource(DeprecatedSingleProperty.class).withDeprecation(
|
||||
"renamed", "singledeprecated.new-name", "error"));
|
||||
assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class.getName())
|
||||
.fromSource(DeprecatedSingleProperty.class)
|
||||
.withDeprecation("renamed", "singledeprecated.new-name", "error"));
|
||||
assertThat(metadata.getItems()).hasSize(3);
|
||||
}
|
||||
|
||||
@@ -687,65 +602,55 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
|
||||
@Test
|
||||
public void mergingOfSimpleHint() throws Exception {
|
||||
writeAdditionalHints(ItemHint.newHint("simple.the-name",
|
||||
new ItemHint.ValueHint("boot", "Bla bla"),
|
||||
writeAdditionalHints(ItemHint.newHint("simple.the-name", new ItemHint.ValueHint("boot", "Bla bla"),
|
||||
new ItemHint.ValueHint("spring", null)));
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class)
|
||||
.fromSource(SimpleProperties.class)
|
||||
.withDescription("The name of this simple properties.")
|
||||
.fromSource(SimpleProperties.class).withDescription("The name of this simple properties.")
|
||||
.withDefaultValue("boot").withDeprecation(null, null));
|
||||
assertThat(metadata).has(Metadata.withHint("simple.the-name")
|
||||
.withValue(0, "boot", "Bla bla").withValue(1, "spring", null));
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla").withValue(1, "spring", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mergingOfHintWithNonCanonicalName() throws Exception {
|
||||
writeAdditionalHints(ItemHint.newHint("simple.theName",
|
||||
new ItemHint.ValueHint("boot", "Bla bla")));
|
||||
writeAdditionalHints(ItemHint.newHint("simple.theName", new ItemHint.ValueHint("boot", "Bla bla")));
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class)
|
||||
.fromSource(SimpleProperties.class)
|
||||
.withDescription("The name of this simple properties.")
|
||||
.fromSource(SimpleProperties.class).withDescription("The name of this simple properties.")
|
||||
.withDefaultValue("boot").withDeprecation(null, null));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla"));
|
||||
assertThat(metadata).has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mergingOfHintWithProvider() throws Exception {
|
||||
writeAdditionalHints(new ItemHint("simple.theName",
|
||||
Collections.<ItemHint.ValueHint>emptyList(),
|
||||
writeAdditionalHints(new ItemHint("simple.theName", Collections.<ItemHint.ValueHint>emptyList(),
|
||||
Arrays.asList(
|
||||
new ItemHint.ValueProvider("first",
|
||||
Collections.<String, Object>singletonMap("target",
|
||||
"org.foo")),
|
||||
Collections.<String, Object>singletonMap("target", "org.foo")),
|
||||
new ItemHint.ValueProvider("second", null))));
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class)
|
||||
.fromSource(SimpleProperties.class)
|
||||
.withDescription("The name of this simple properties.")
|
||||
.fromSource(SimpleProperties.class).withDescription("The name of this simple properties.")
|
||||
.withDefaultValue("boot").withDeprecation(null, null));
|
||||
assertThat(metadata).has(Metadata.withHint("simple.the-name")
|
||||
.withProvider("first", "target", "org.foo").withProvider("second"));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withHint("simple.the-name").withProvider("first", "target", "org.foo").withProvider("second"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mergingOfAdditionalDeprecation() throws Exception {
|
||||
writePropertyDeprecation(ItemMetadata.newProperty("simple", "wrongName",
|
||||
"java.lang.String", null, null, null, null,
|
||||
new ItemDeprecation("Lame name.", "simple.the-name")));
|
||||
writePropertyDeprecation(ItemMetadata.newProperty("simple", "wrongName", "java.lang.String", null, null, null,
|
||||
null, new ItemDeprecation("Lame name.", "simple.the-name")));
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class)
|
||||
.withDeprecation("Lame name.", "simple.the-name"));
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class).withDeprecation("Lame name.",
|
||||
"simple.the-name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mergingOfAdditionalMetadata() throws Exception {
|
||||
File metaInfFolder = new File(this.compiler.getOutputLocation(), "META-INF");
|
||||
metaInfFolder.mkdirs();
|
||||
File additionalMetadataFile = new File(metaInfFolder,
|
||||
"additional-spring-configuration-metadata.json");
|
||||
File additionalMetadataFile = new File(metaInfFolder, "additional-spring-configuration-metadata.json");
|
||||
additionalMetadataFile.createNewFile();
|
||||
JSONObject property = new JSONObject();
|
||||
property.put("name", "foo");
|
||||
@@ -761,28 +666,21 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
writer.close();
|
||||
ConfigurationMetadata metadata = compile(SimpleProperties.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("simple.comparator"));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo", String.class)
|
||||
.fromSource(AdditionalMetadata.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo", String.class).fromSource(AdditionalMetadata.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void incrementalBuild() throws Exception {
|
||||
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class,
|
||||
BarProperties.class);
|
||||
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class);
|
||||
assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isFalse();
|
||||
ConfigurationMetadata metadata = project.fullBuild();
|
||||
assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isTrue();
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
|
||||
metadata = project.incrementalBuild(BarProperties.class);
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
|
||||
project.addSourceCode(BarProperties.class,
|
||||
BarProperties.class.getResourceAsStream("BarProperties.snippet"));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
|
||||
project.addSourceCode(BarProperties.class, BarProperties.class.getResourceAsStream("BarProperties.snippet"));
|
||||
metadata = project.incrementalBuild(BarProperties.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("bar.extra"));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.counter"));
|
||||
@@ -796,13 +694,11 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
|
||||
@Test
|
||||
public void incrementalBuildAnnotationRemoved() throws Exception {
|
||||
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class,
|
||||
BarProperties.class);
|
||||
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class);
|
||||
ConfigurationMetadata metadata = project.fullBuild();
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.counter"));
|
||||
assertThat(metadata).has(Metadata.withProperty("bar.counter"));
|
||||
project.replaceText(BarProperties.class, "@ConfigurationProperties",
|
||||
"//@ConfigurationProperties");
|
||||
project.replaceText(BarProperties.class, "@ConfigurationProperties", "//@ConfigurationProperties");
|
||||
metadata = project.incrementalBuild(BarProperties.class);
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.counter"));
|
||||
assertThat(metadata).isNotEqualTo(Metadata.withProperty("bar.counter"));
|
||||
@@ -810,51 +706,42 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
|
||||
@Test
|
||||
public void incrementalBuildTypeRenamed() throws Exception {
|
||||
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class,
|
||||
BarProperties.class);
|
||||
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class);
|
||||
ConfigurationMetadata metadata = project.fullBuild();
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
|
||||
assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter")
|
||||
.fromSource(RenamedBarProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
|
||||
assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter").fromSource(RenamedBarProperties.class));
|
||||
project.delete(BarProperties.class);
|
||||
project.add(RenamedBarProperties.class);
|
||||
metadata = project.incrementalBuild(RenamedBarProperties.class);
|
||||
assertThat(metadata).has(
|
||||
Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
|
||||
assertThat(metadata).doesNotHave(
|
||||
Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("bar.counter")
|
||||
.fromSource(RenamedBarProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
|
||||
assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
|
||||
assertThat(metadata).has(Metadata.withProperty("bar.counter").fromSource(RenamedBarProperties.class));
|
||||
}
|
||||
|
||||
private void assertSimpleLombokProperties(ConfigurationMetadata metadata,
|
||||
Class<?> source, String prefix) {
|
||||
private void assertSimpleLombokProperties(ConfigurationMetadata metadata, Class<?> source, String prefix) {
|
||||
assertThat(metadata).has(Metadata.withGroup(prefix).fromSource(source));
|
||||
assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".id"));
|
||||
assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class)
|
||||
.fromSource(source).withDescription("Name description."));
|
||||
assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class).fromSource(source)
|
||||
.withDescription("Name description."));
|
||||
assertThat(metadata).has(Metadata.withProperty(prefix + ".description"));
|
||||
assertThat(metadata).has(Metadata.withProperty(prefix + ".counter"));
|
||||
assertThat(metadata).has(Metadata.withProperty(prefix + ".number")
|
||||
.fromSource(source).withDefaultValue(0).withDeprecation(null, null));
|
||||
assertThat(metadata).has(Metadata.withProperty(prefix + ".number").fromSource(source).withDefaultValue(0)
|
||||
.withDeprecation(null, null));
|
||||
assertThat(metadata).has(Metadata.withProperty(prefix + ".items"));
|
||||
assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".ignored"));
|
||||
}
|
||||
|
||||
private void assertAccessLevelOverwriteLombokProperties(
|
||||
ConfigurationMetadata metadata, Class<?> source, String prefix) {
|
||||
private void assertAccessLevelOverwriteLombokProperties(ConfigurationMetadata metadata, Class<?> source,
|
||||
String prefix) {
|
||||
assertAccessLevelLombokProperties(metadata, source, prefix, 7);
|
||||
}
|
||||
|
||||
private void assertAccessLevelLombokProperties(ConfigurationMetadata metadata,
|
||||
Class<?> source, String prefix, int countNameFields) {
|
||||
private void assertAccessLevelLombokProperties(ConfigurationMetadata metadata, Class<?> source, String prefix,
|
||||
int countNameFields) {
|
||||
assertThat(metadata).has(Metadata.withGroup(prefix).fromSource(source));
|
||||
for (int i = 0; i < countNameFields; i++) {
|
||||
assertThat(metadata)
|
||||
.has(Metadata.withProperty(prefix + ".name" + i, String.class));
|
||||
assertThat(metadata).has(Metadata.withProperty(prefix + ".name" + i, String.class));
|
||||
}
|
||||
assertThat(metadata.getItems()).hasSize(1 + countNameFields);
|
||||
}
|
||||
@@ -917,8 +804,7 @@ public class ConfigurationMetadataAnnotationProcessorTests {
|
||||
private File createAdditionalMetadataFile() throws IOException {
|
||||
File metaInfFolder = new File(this.compiler.getOutputLocation(), "META-INF");
|
||||
metaInfFolder.mkdirs();
|
||||
File additionalMetadataFile = new File(metaInfFolder,
|
||||
"additional-spring-configuration-metadata.json");
|
||||
File additionalMetadataFile = new File(metaInfFolder, "additional-spring-configuration-metadata.json");
|
||||
additionalMetadataFile.createNewFile();
|
||||
return additionalMetadataFile;
|
||||
}
|
||||
|
||||
@@ -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,87 +138,73 @@ 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.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;
|
||||
@@ -244,8 +229,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;
|
||||
@@ -271,12 +255,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;
|
||||
@@ -285,8 +267,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;
|
||||
@@ -295,11 +276,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);
|
||||
}
|
||||
|
||||
@@ -307,17 +286,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) {
|
||||
@@ -364,8 +339,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;
|
||||
@@ -381,8 +355,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;
|
||||
|
||||
@@ -38,8 +38,7 @@ public class MetadataStoreTests {
|
||||
@Rule
|
||||
public final TemporaryFolder temp = new TemporaryFolder();
|
||||
|
||||
private final MetadataStore metadataStore = new MetadataStore(
|
||||
mock(ProcessingEnvironment.class));
|
||||
private final MetadataStore metadataStore = new MetadataStore(mock(ProcessingEnvironment.class));
|
||||
|
||||
@Test
|
||||
public void additionalMetadataIsLocatedInMavenBuild() throws IOException {
|
||||
@@ -47,13 +46,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
|
||||
@@ -63,13 +60,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
|
||||
@@ -79,13 +74,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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -73,11 +72,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();
|
||||
|
||||
@@ -65,8 +65,7 @@ public class TestProject {
|
||||
|
||||
private Set<File> sourceFiles = new LinkedHashSet<File>();
|
||||
|
||||
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
|
||||
@@ -135,15 +134,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -84,14 +84,12 @@ 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();
|
||||
}
|
||||
|
||||
@SupportedAnnotationTypes({
|
||||
"org.springframework.boot.configurationsample.ConfigurationProperties" })
|
||||
@SupportedAnnotationTypes({ "org.springframework.boot.configurationsample.ConfigurationProperties" })
|
||||
@SupportedSourceVersion(SourceVersion.RELEASE_6)
|
||||
private class TestProcessor extends AbstractProcessor {
|
||||
|
||||
@@ -105,14 +103,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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -39,50 +39,35 @@ 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.<String, Object>singletonMap("target",
|
||||
"foo")),
|
||||
new ItemHint.ValueProvider("first", Collections.<String, Object>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"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -271,8 +271,7 @@ public class SpringBootPluginExtension {
|
||||
return this.embeddedLaunchScriptProperties;
|
||||
}
|
||||
|
||||
public void setEmbeddedLaunchScriptProperties(
|
||||
Map<String, String> embeddedLaunchScriptProperties) {
|
||||
public void setEmbeddedLaunchScriptProperties(Map<String, String> embeddedLaunchScriptProperties) {
|
||||
this.embeddedLaunchScriptProperties = embeddedLaunchScriptProperties;
|
||||
}
|
||||
|
||||
@@ -281,10 +280,8 @@ public class SpringBootPluginExtension {
|
||||
}
|
||||
|
||||
public void buildInfo(Closure<?> taskConfigurer) {
|
||||
BuildInfo bootBuildInfo = this.project.getTasks().create("bootBuildInfo",
|
||||
BuildInfo.class);
|
||||
this.project.getTasks().getByName(JavaPlugin.CLASSES_TASK_NAME)
|
||||
.dependsOn(bootBuildInfo);
|
||||
BuildInfo bootBuildInfo = this.project.getTasks().create("bootBuildInfo", BuildInfo.class);
|
||||
this.project.getTasks().getByName(JavaPlugin.CLASSES_TASK_NAME).dependsOn(bootBuildInfo);
|
||||
if (taskConfigurer != null) {
|
||||
taskConfigurer.setDelegate(bootBuildInfo);
|
||||
taskConfigurer.call();
|
||||
|
||||
@@ -61,8 +61,7 @@ public class AgentTasksEnhancer implements Action<Project> {
|
||||
|
||||
private void setup(Project project) {
|
||||
project.getLogger().info("Configuring agent");
|
||||
SpringBootPluginExtension extension = project.getExtensions()
|
||||
.getByType(SpringBootPluginExtension.class);
|
||||
SpringBootPluginExtension extension = project.getExtensions().getByType(SpringBootPluginExtension.class);
|
||||
this.noverify = extension.getNoverify();
|
||||
this.agent = getAgent(project, extension);
|
||||
if (this.agent == null) {
|
||||
@@ -116,8 +115,7 @@ public class AgentTasksEnhancer implements Action<Project> {
|
||||
if (this.noverify != null && this.noverify) {
|
||||
exec.jvmArgs("-noverify");
|
||||
}
|
||||
Iterable<?> defaultJvmArgs = exec.getConventionMapping()
|
||||
.getConventionValue(null, "jvmArgs", false);
|
||||
Iterable<?> defaultJvmArgs = exec.getConventionMapping().getConventionValue(null, "jvmArgs", false);
|
||||
if (defaultJvmArgs != null) {
|
||||
exec.jvmArgs(defaultJvmArgs);
|
||||
}
|
||||
|
||||
@@ -46,15 +46,14 @@ import org.springframework.boot.loader.tools.BuildPropertiesWriter.ProjectDetail
|
||||
public class BuildInfo extends DefaultTask {
|
||||
|
||||
@OutputFile
|
||||
private File outputFile = getProject().file(new File(getProject().getBuildDir(),
|
||||
"resources/main/META-INF/build-info.properties"));
|
||||
private File outputFile = getProject()
|
||||
.file(new File(getProject().getBuildDir(), "resources/main/META-INF/build-info.properties"));
|
||||
|
||||
@Input
|
||||
private String projectGroup = getProject().getGroup().toString();
|
||||
|
||||
@Input
|
||||
private String projectArtifact = ((Jar) getProject().getTasks()
|
||||
.getByName(JavaPlugin.JAR_TASK_NAME)).getBaseName();
|
||||
private String projectArtifact = ((Jar) getProject().getTasks().getByName(JavaPlugin.JAR_TASK_NAME)).getBaseName();
|
||||
|
||||
@Input
|
||||
private String projectVersion = getProject().getVersion().toString();
|
||||
@@ -69,9 +68,8 @@ public class BuildInfo extends DefaultTask {
|
||||
public void generateBuildProperties() {
|
||||
try {
|
||||
new BuildPropertiesWriter(this.outputFile)
|
||||
.writeBuildProperties(new ProjectDetails(this.projectGroup,
|
||||
this.projectArtifact, this.projectVersion, this.projectName,
|
||||
coerceToStringValues(this.additionalProperties)));
|
||||
.writeBuildProperties(new ProjectDetails(this.projectGroup, this.projectArtifact,
|
||||
this.projectVersion, this.projectName, coerceToStringValues(this.additionalProperties)));
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new TaskExecutionException(this, ex);
|
||||
|
||||
@@ -33,8 +33,8 @@ import org.springframework.boot.gradle.PluginFeatures;
|
||||
*/
|
||||
public class DependencyManagementPluginFeatures implements PluginFeatures {
|
||||
|
||||
private static final String SPRING_BOOT_VERSION = DependencyManagementPluginFeatures.class
|
||||
.getPackage().getImplementationVersion();
|
||||
private static final String SPRING_BOOT_VERSION = DependencyManagementPluginFeatures.class.getPackage()
|
||||
.getImplementationVersion();
|
||||
|
||||
private static final String SPRING_BOOT_BOM = "org.springframework.boot:spring-boot-starter-parent:"
|
||||
+ SPRING_BOOT_VERSION;
|
||||
|
||||
@@ -30,13 +30,11 @@ import org.slf4j.LoggerFactory;
|
||||
@Deprecated
|
||||
public class DeprecatedSpringBootPlugin extends SpringBootPlugin {
|
||||
|
||||
private static final Logger logger = LoggerFactory
|
||||
.getLogger(DeprecatedSpringBootPlugin.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(DeprecatedSpringBootPlugin.class);
|
||||
|
||||
@Override
|
||||
public void apply(Project project) {
|
||||
logger.warn("The plugin id 'spring-boot' is deprecated. Please use "
|
||||
+ "'org.springframework.boot' instead.");
|
||||
logger.warn("The plugin id 'spring-boot' is deprecated. Please use " + "'org.springframework.boot' instead.");
|
||||
super.apply(project);
|
||||
}
|
||||
|
||||
|
||||
@@ -40,8 +40,7 @@ public class SpringBootPlugin implements Plugin<Project> {
|
||||
|
||||
@Override
|
||||
public void apply(Project project) {
|
||||
project.getExtensions().create("springBoot", SpringBootPluginExtension.class,
|
||||
project);
|
||||
project.getExtensions().create("springBoot", SpringBootPluginExtension.class, project);
|
||||
project.getPlugins().apply(JavaPlugin.class);
|
||||
new AgentPluginFeatures().apply(project);
|
||||
new RepackagePluginFeatures().apply(project);
|
||||
|
||||
@@ -63,8 +63,7 @@ class ProjectLibraries implements Libraries {
|
||||
* @param extension the extension
|
||||
* @param excludeDevTools whether Spring Boot Devtools should be excluded
|
||||
*/
|
||||
ProjectLibraries(Project project, SpringBootPluginExtension extension,
|
||||
boolean excludeDevTools) {
|
||||
ProjectLibraries(Project project, SpringBootPluginExtension extension, boolean excludeDevTools) {
|
||||
this.project = project;
|
||||
this.extension = extension;
|
||||
this.excludeDevtools = excludeDevTools;
|
||||
@@ -73,8 +72,7 @@ class ProjectLibraries implements Libraries {
|
||||
|
||||
private static TargetConfigurationResolver createTargetConfigurationResolver() {
|
||||
try {
|
||||
return new Gradle3TargetConfigurationResolver(
|
||||
ProjectDependency.class.getMethod("getTargetConfiguration"));
|
||||
return new Gradle3TargetConfigurationResolver(ProjectDependency.class.getMethod("getTargetConfiguration"));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
return new Gradle2TargetConfigurationResolver();
|
||||
@@ -95,15 +93,13 @@ class ProjectLibraries implements Libraries {
|
||||
|
||||
@Override
|
||||
public void doWithLibraries(LibraryCallback callback) throws IOException {
|
||||
Set<GradleLibrary> custom = getLibraries(this.customConfigurationName,
|
||||
LibraryScope.CUSTOM);
|
||||
Set<GradleLibrary> custom = getLibraries(this.customConfigurationName, LibraryScope.CUSTOM);
|
||||
if (custom != null) {
|
||||
libraries(custom, callback);
|
||||
}
|
||||
else {
|
||||
Set<GradleLibrary> runtime = getLibraries("runtime", LibraryScope.RUNTIME);
|
||||
Set<GradleLibrary> provided = getLibraries(this.providedConfigurationName,
|
||||
LibraryScope.PROVIDED);
|
||||
Set<GradleLibrary> provided = getLibraries(this.providedConfigurationName, LibraryScope.PROVIDED);
|
||||
if (provided != null) {
|
||||
runtime = minus(runtime, provided);
|
||||
}
|
||||
@@ -112,47 +108,39 @@ class ProjectLibraries implements Libraries {
|
||||
}
|
||||
}
|
||||
|
||||
private Set<GradleLibrary> getLibraries(String configurationName,
|
||||
LibraryScope scope) {
|
||||
private Set<GradleLibrary> getLibraries(String configurationName, LibraryScope scope) {
|
||||
Configuration configuration = (configurationName != null)
|
||||
? this.project.getConfigurations().findByName(configurationName) : null;
|
||||
if (configuration == null) {
|
||||
return null;
|
||||
}
|
||||
Set<GradleLibrary> libraries = new LinkedHashSet<GradleLibrary>();
|
||||
for (ResolvedArtifact artifact : configuration.getResolvedConfiguration()
|
||||
.getResolvedArtifacts()) {
|
||||
for (ResolvedArtifact artifact : configuration.getResolvedConfiguration().getResolvedArtifacts()) {
|
||||
libraries.add(new ResolvedArtifactLibrary(artifact, scope));
|
||||
}
|
||||
libraries.addAll(getLibrariesForFileDependencies(configuration, scope));
|
||||
return libraries;
|
||||
}
|
||||
|
||||
private Set<GradleLibrary> getLibrariesForFileDependencies(
|
||||
Configuration configuration, LibraryScope scope) {
|
||||
private Set<GradleLibrary> getLibrariesForFileDependencies(Configuration configuration, LibraryScope scope) {
|
||||
Set<GradleLibrary> libraries = new LinkedHashSet<GradleLibrary>();
|
||||
for (Dependency dependency : configuration.getIncoming().getDependencies()) {
|
||||
if (dependency instanceof FileCollectionDependency) {
|
||||
FileCollectionDependency fileDependency = (FileCollectionDependency) dependency;
|
||||
for (File file : fileDependency.resolve()) {
|
||||
libraries.add(
|
||||
new GradleLibrary(fileDependency.getGroup(), file, scope));
|
||||
libraries.add(new GradleLibrary(fileDependency.getGroup(), file, scope));
|
||||
}
|
||||
}
|
||||
else if (dependency instanceof ProjectDependency) {
|
||||
ProjectDependency projectDependency = (ProjectDependency) dependency;
|
||||
libraries
|
||||
.addAll(getLibrariesForFileDependencies(
|
||||
this.targetConfigurationResolver
|
||||
.resolveTargetConfiguration(projectDependency),
|
||||
scope));
|
||||
libraries.addAll(getLibrariesForFileDependencies(
|
||||
this.targetConfigurationResolver.resolveTargetConfiguration(projectDependency), scope));
|
||||
}
|
||||
}
|
||||
return libraries;
|
||||
}
|
||||
|
||||
private Set<GradleLibrary> minus(Set<GradleLibrary> source,
|
||||
Set<GradleLibrary> toRemove) {
|
||||
private Set<GradleLibrary> minus(Set<GradleLibrary> source, Set<GradleLibrary> toRemove) {
|
||||
if (source == null || toRemove == null) {
|
||||
return source;
|
||||
}
|
||||
@@ -169,8 +157,7 @@ class ProjectLibraries implements Libraries {
|
||||
return result;
|
||||
}
|
||||
|
||||
private void libraries(Set<GradleLibrary> libraries, LibraryCallback callback)
|
||||
throws IOException {
|
||||
private void libraries(Set<GradleLibrary> libraries, LibraryCallback callback) throws IOException {
|
||||
if (libraries != null) {
|
||||
Set<String> duplicates = getDuplicates(libraries);
|
||||
for (GradleLibrary library : libraries) {
|
||||
@@ -261,8 +248,7 @@ class ProjectLibraries implements Libraries {
|
||||
private final ResolvedArtifact artifact;
|
||||
|
||||
ResolvedArtifactLibrary(ResolvedArtifact artifact, LibraryScope scope) {
|
||||
super(artifact.getModuleVersion().getId().getGroup(), artifact.getFile(),
|
||||
scope);
|
||||
super(artifact.getModuleVersion().getId().getGroup(), artifact.getFile(), scope);
|
||||
this.artifact = artifact;
|
||||
}
|
||||
|
||||
@@ -270,8 +256,7 @@ class ProjectLibraries implements Libraries {
|
||||
public boolean isUnpackRequired() {
|
||||
if (ProjectLibraries.this.extension.getRequiresUnpack() != null) {
|
||||
ModuleVersionIdentifier id = this.artifact.getModuleVersion().getId();
|
||||
return ProjectLibraries.this.extension.getRequiresUnpack()
|
||||
.contains(id.getGroup() + ":" + id.getName());
|
||||
return ProjectLibraries.this.extension.getRequiresUnpack().contains(id.getGroup() + ":" + id.getName());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -291,12 +276,10 @@ class ProjectLibraries implements Libraries {
|
||||
/**
|
||||
* {@link TargetConfigurationResolver} for Gradle 2.x.
|
||||
*/
|
||||
private static final class Gradle2TargetConfigurationResolver
|
||||
implements TargetConfigurationResolver {
|
||||
private static final class Gradle2TargetConfigurationResolver implements TargetConfigurationResolver {
|
||||
|
||||
@Override
|
||||
public Configuration resolveTargetConfiguration(
|
||||
ProjectDependency projectDependency) {
|
||||
public Configuration resolveTargetConfiguration(ProjectDependency projectDependency) {
|
||||
return projectDependency.getProjectConfiguration();
|
||||
}
|
||||
|
||||
@@ -305,8 +288,7 @@ class ProjectLibraries implements Libraries {
|
||||
/**
|
||||
* {@link TargetConfigurationResolver} for Gradle 3.x.
|
||||
*/
|
||||
private static final class Gradle3TargetConfigurationResolver
|
||||
implements TargetConfigurationResolver {
|
||||
private static final class Gradle3TargetConfigurationResolver implements TargetConfigurationResolver {
|
||||
|
||||
private final Method getTargetConfiguration;
|
||||
|
||||
@@ -315,14 +297,11 @@ class ProjectLibraries implements Libraries {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration resolveTargetConfiguration(
|
||||
ProjectDependency projectDependency) {
|
||||
public Configuration resolveTargetConfiguration(ProjectDependency projectDependency) {
|
||||
try {
|
||||
String configurationName = (String) this.getTargetConfiguration
|
||||
.invoke(projectDependency);
|
||||
String configurationName = (String) this.getTargetConfiguration.invoke(projectDependency);
|
||||
return projectDependency.getDependencyProject().getConfigurations()
|
||||
.getByName((configurationName != null) ? configurationName
|
||||
: Dependency.DEFAULT_CONFIGURATION);
|
||||
.getByName((configurationName != null) ? configurationName : Dependency.DEFAULT_CONFIGURATION);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new RuntimeException("Failed to get target configuration", ex);
|
||||
|
||||
@@ -58,20 +58,16 @@ public class RepackagePluginFeatures implements PluginFeatures {
|
||||
}
|
||||
|
||||
private void addRepackageTask(Project project) {
|
||||
RepackageTask task = project.getTasks().create(REPACKAGE_TASK_NAME,
|
||||
RepackageTask.class);
|
||||
RepackageTask task = project.getTasks().create(REPACKAGE_TASK_NAME, RepackageTask.class);
|
||||
task.setDescription("Repackage existing JAR and WAR "
|
||||
+ "archives so that they can be executed from the command "
|
||||
+ "line using 'java -jar'");
|
||||
+ "archives so that they can be executed from the command " + "line using 'java -jar'");
|
||||
task.setGroup(BasePlugin.BUILD_GROUP);
|
||||
Configuration runtimeConfiguration = project.getConfigurations()
|
||||
.getByName(JavaPlugin.RUNTIME_CONFIGURATION_NAME);
|
||||
TaskDependency runtimeProjectDependencyJarTasks = runtimeConfiguration
|
||||
.getTaskDependencyFromProjectDependency(true, JavaPlugin.JAR_TASK_NAME);
|
||||
task.dependsOn(
|
||||
project.getConfigurations().getByName(Dependency.ARCHIVES_CONFIGURATION)
|
||||
.getAllArtifacts().getBuildDependencies(),
|
||||
runtimeProjectDependencyJarTasks);
|
||||
task.dependsOn(project.getConfigurations().getByName(Dependency.ARCHIVES_CONFIGURATION).getAllArtifacts()
|
||||
.getBuildDependencies(), runtimeProjectDependencyJarTasks);
|
||||
registerOutput(project, task);
|
||||
ensureTaskRunsOnAssembly(project, task);
|
||||
ensureMainClassHasBeenFound(project, task);
|
||||
@@ -81,8 +77,7 @@ public class RepackagePluginFeatures implements PluginFeatures {
|
||||
project.afterEvaluate(new Action<Project>() {
|
||||
@Override
|
||||
public void execute(Project project) {
|
||||
project.getTasks().withType(Jar.class,
|
||||
new RegisterInputsOutputsAction(task));
|
||||
project.getTasks().withType(Jar.class, new RegisterInputsOutputsAction(task));
|
||||
Object withJar = task.getWithJarTask();
|
||||
if (withJar != null) {
|
||||
task.dependsOn(withJar);
|
||||
@@ -104,8 +99,7 @@ public class RepackagePluginFeatures implements PluginFeatures {
|
||||
* @param project the source project
|
||||
*/
|
||||
private void registerRepackageTaskProperty(Project project) {
|
||||
project.getExtensions().getExtraProperties().set("BootRepackage",
|
||||
RepackageTask.class);
|
||||
project.getExtensions().getExtraProperties().set("BootRepackage", RepackageTask.class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -140,12 +134,11 @@ public class RepackagePluginFeatures implements PluginFeatures {
|
||||
|
||||
private void setupInputOutputs(Jar jarTask, String classifier) {
|
||||
Logger logger = this.project.getLogger();
|
||||
logger.debug("Using classifier: " + classifier + " for task "
|
||||
+ this.task.getName());
|
||||
logger.debug("Using classifier: " + classifier + " for task " + this.task.getName());
|
||||
File inputFile = jarTask.getArchivePath();
|
||||
String outputName = inputFile.getName();
|
||||
outputName = StringUtils.stripFilenameExtension(outputName) + "-" + classifier
|
||||
+ "." + StringUtils.getFilenameExtension(outputName);
|
||||
outputName = StringUtils.stripFilenameExtension(outputName) + "-" + classifier + "."
|
||||
+ StringUtils.getFilenameExtension(outputName);
|
||||
File outputFile = new File(inputFile.getParentFile(), outputName);
|
||||
this.task.getInputs().file(jarTask);
|
||||
addLibraryDependencies(this.task);
|
||||
|
||||
@@ -126,27 +126,23 @@ public class RepackageTask extends DefaultTask {
|
||||
return this.embeddedLaunchScriptProperties;
|
||||
}
|
||||
|
||||
public void setEmbeddedLaunchScriptProperties(
|
||||
Map<String, String> embeddedLaunchScriptProperties) {
|
||||
public void setEmbeddedLaunchScriptProperties(Map<String, String> embeddedLaunchScriptProperties) {
|
||||
this.embeddedLaunchScriptProperties = embeddedLaunchScriptProperties;
|
||||
}
|
||||
|
||||
@TaskAction
|
||||
public void repackage() {
|
||||
Project project = getProject();
|
||||
SpringBootPluginExtension extension = project.getExtensions()
|
||||
.getByType(SpringBootPluginExtension.class);
|
||||
SpringBootPluginExtension extension = project.getExtensions().getByType(SpringBootPluginExtension.class);
|
||||
ProjectLibraries libraries = getLibraries();
|
||||
project.getTasks().withType(Jar.class, new RepackageAction(extension, libraries));
|
||||
}
|
||||
|
||||
public ProjectLibraries getLibraries() {
|
||||
Project project = getProject();
|
||||
SpringBootPluginExtension extension = project.getExtensions()
|
||||
.getByType(SpringBootPluginExtension.class);
|
||||
SpringBootPluginExtension extension = project.getExtensions().getByType(SpringBootPluginExtension.class);
|
||||
ProjectLibraries libraries = new ProjectLibraries(project, extension,
|
||||
(this.excludeDevtools != null) ? this.excludeDevtools
|
||||
: extension.isExcludeDevtools());
|
||||
(this.excludeDevtools != null) ? this.excludeDevtools : extension.isExcludeDevtools());
|
||||
if (extension.getProvidedConfiguration() != null) {
|
||||
libraries.setProvidedConfigurationName(extension.getProvidedConfiguration());
|
||||
}
|
||||
@@ -181,8 +177,7 @@ public class RepackageTask extends DefaultTask {
|
||||
}
|
||||
Object withJarTask = RepackageTask.this.withJarTask;
|
||||
if (!isTaskMatch(jarTask, withJarTask)) {
|
||||
getLogger().info(
|
||||
"Jar task not repackaged (didn't match withJarTask): " + jarTask);
|
||||
getLogger().info("Jar task not repackaged (didn't match withJarTask): " + jarTask);
|
||||
return;
|
||||
}
|
||||
File file = jarTask.getArchivePath();
|
||||
@@ -195,11 +190,10 @@ public class RepackageTask extends DefaultTask {
|
||||
if (withJarTask == null) {
|
||||
if ("".equals(task.getClassifier())) {
|
||||
Set<Object> tasksWithCustomRepackaging = new HashSet<Object>();
|
||||
for (RepackageTask repackageTask : RepackageTask.this.getProject()
|
||||
.getTasks().withType(RepackageTask.class)) {
|
||||
for (RepackageTask repackageTask : RepackageTask.this.getProject().getTasks()
|
||||
.withType(RepackageTask.class)) {
|
||||
if (repackageTask.getWithJarTask() != null) {
|
||||
tasksWithCustomRepackaging
|
||||
.add(repackageTask.getWithJarTask());
|
||||
tasksWithCustomRepackaging.add(repackageTask.getWithJarTask());
|
||||
}
|
||||
}
|
||||
return !tasksWithCustomRepackaging.contains(task);
|
||||
@@ -216,16 +210,13 @@ public class RepackageTask extends DefaultTask {
|
||||
copy(file, outputFile);
|
||||
file = outputFile;
|
||||
}
|
||||
Repackager repackager = new Repackager(file,
|
||||
this.extension.getLayoutFactory());
|
||||
repackager.addMainClassTimeoutWarningListener(
|
||||
new LoggingMainClassTimeoutWarningListener());
|
||||
Repackager repackager = new Repackager(file, this.extension.getLayoutFactory());
|
||||
repackager.addMainClassTimeoutWarningListener(new LoggingMainClassTimeoutWarningListener());
|
||||
setMainClass(repackager);
|
||||
Layout layout = this.extension.convertLayout();
|
||||
if (layout != null) {
|
||||
if (layout instanceof Layouts.Module) {
|
||||
getLogger().warn("Module layout is deprecated. Please use a custom"
|
||||
+ " LayoutFactory instead.");
|
||||
getLogger().warn("Module layout is deprecated. Please use a custom" + " LayoutFactory instead.");
|
||||
}
|
||||
repackager.setLayout(layout);
|
||||
}
|
||||
@@ -259,8 +250,7 @@ public class RepackageTask extends DefaultTask {
|
||||
else {
|
||||
Task runTask = getProject().getTasks().findByName("run");
|
||||
if (runTask != null && runTask.hasProperty("main")) {
|
||||
mainClassName = (String) getProject().getTasks().getByName("run")
|
||||
.property("main");
|
||||
mainClassName = (String) getProject().getTasks().getByName("run").property("main");
|
||||
}
|
||||
}
|
||||
if (mainClassName != null) {
|
||||
@@ -276,8 +266,8 @@ public class RepackageTask extends DefaultTask {
|
||||
if (getProject().hasProperty("mainClassName")) {
|
||||
return (String) getProject().property("mainClassName");
|
||||
}
|
||||
ExtraPropertiesExtension extraProperties = (ExtraPropertiesExtension) getProject()
|
||||
.getExtensions().getByName("ext");
|
||||
ExtraPropertiesExtension extraProperties = (ExtraPropertiesExtension) getProject().getExtensions()
|
||||
.getByName("ext");
|
||||
if (extraProperties.has("mainClassName")) {
|
||||
return (String) extraProperties.get("mainClassName");
|
||||
}
|
||||
@@ -286,8 +276,7 @@ public class RepackageTask extends DefaultTask {
|
||||
|
||||
private LaunchScript getLaunchScript() throws IOException {
|
||||
if (isExecutable() || getEmbeddedLaunchScript() != null) {
|
||||
return new DefaultLaunchScript(getEmbeddedLaunchScript(),
|
||||
getEmbeddedLaunchScriptProperties());
|
||||
return new DefaultLaunchScript(getEmbeddedLaunchScript(), getEmbeddedLaunchScriptProperties());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -298,8 +287,7 @@ public class RepackageTask extends DefaultTask {
|
||||
}
|
||||
|
||||
private File getEmbeddedLaunchScript() {
|
||||
return (RepackageTask.this.embeddedLaunchScript != null)
|
||||
? RepackageTask.this.embeddedLaunchScript
|
||||
return (RepackageTask.this.embeddedLaunchScript != null) ? RepackageTask.this.embeddedLaunchScript
|
||||
: this.extension.getEmbeddedLaunchScript();
|
||||
}
|
||||
|
||||
@@ -314,13 +302,12 @@ public class RepackageTask extends DefaultTask {
|
||||
/**
|
||||
* {@link Repackager} that also logs when searching takes too long.
|
||||
*/
|
||||
private class LoggingMainClassTimeoutWarningListener
|
||||
implements MainClassTimeoutWarningListener {
|
||||
private class LoggingMainClassTimeoutWarningListener implements MainClassTimeoutWarningListener {
|
||||
|
||||
@Override
|
||||
public void handleTimeoutWarning(long duration, String mainMethod) {
|
||||
getLogger().warn("Searching for the main-class is taking "
|
||||
+ "some time, consider using setting " + "'springBoot.mainClass'");
|
||||
getLogger().warn("Searching for the main-class is taking " + "some time, consider using setting "
|
||||
+ "'springBoot.mainClass'");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -65,8 +65,7 @@ public class BootRunTask extends JavaExec {
|
||||
private void addResourcesIfNecessary() {
|
||||
if (this.addResources) {
|
||||
SourceSet mainSourceSet = SourceSets.findMainSourceSet(getProject());
|
||||
final File outputDir = (mainSourceSet != null)
|
||||
? mainSourceSet.getOutput().getResourcesDir() : null;
|
||||
final File outputDir = (mainSourceSet != null) ? mainSourceSet.getOutput().getResourcesDir() : null;
|
||||
final Set<File> resources = new LinkedHashSet<File>();
|
||||
if (mainSourceSet != null) {
|
||||
resources.addAll(mainSourceSet.getResources().getSrcDirs());
|
||||
|
||||
@@ -60,15 +60,14 @@ public class FindMainClassTask extends DefaultTask {
|
||||
@TaskAction
|
||||
public void setMainClassNameProperty() {
|
||||
Project project = getProject();
|
||||
if (!project.hasProperty("mainClassName")
|
||||
|| project.property("mainClassName") == null) {
|
||||
if (!project.hasProperty("mainClassName") || project.property("mainClassName") == null) {
|
||||
String mainClass = findMainClass();
|
||||
if (project.hasProperty("mainClassName")) {
|
||||
project.setProperty("mainClassName", mainClass);
|
||||
}
|
||||
else {
|
||||
ExtraPropertiesExtension extraProperties = (ExtraPropertiesExtension) project
|
||||
.getExtensions().getByName("ext");
|
||||
ExtraPropertiesExtension extraProperties = (ExtraPropertiesExtension) project.getExtensions()
|
||||
.getByName("ext");
|
||||
extraProperties.set("mainClassName", mainClass);
|
||||
}
|
||||
}
|
||||
@@ -80,14 +79,13 @@ public class FindMainClassTask extends DefaultTask {
|
||||
String mainClass = null;
|
||||
|
||||
// Try the SpringBoot extension setting
|
||||
SpringBootPluginExtension bootExtension = project.getExtensions()
|
||||
.getByType(SpringBootPluginExtension.class);
|
||||
SpringBootPluginExtension bootExtension = project.getExtensions().getByType(SpringBootPluginExtension.class);
|
||||
if (bootExtension.getMainClass() != null) {
|
||||
mainClass = bootExtension.getMainClass();
|
||||
}
|
||||
|
||||
ApplicationPluginConvention application = (ApplicationPluginConvention) project
|
||||
.getConvention().getPlugins().get("application");
|
||||
ApplicationPluginConvention application = (ApplicationPluginConvention) project.getConvention().getPlugins()
|
||||
.get("application");
|
||||
|
||||
if (mainClass == null && application != null) {
|
||||
// Try the Application extension setting
|
||||
@@ -109,12 +107,10 @@ public class FindMainClassTask extends DefaultTask {
|
||||
if (mainClass == null) {
|
||||
// Search
|
||||
if (this.mainClassSourceSetOutput != null) {
|
||||
Collection<File> classesDirs = getClassesDirs(
|
||||
this.mainClassSourceSetOutput);
|
||||
Collection<File> classesDirs = getClassesDirs(this.mainClassSourceSetOutput);
|
||||
getProject().getLogger().debug("Looking for main in: " + classesDirs);
|
||||
try {
|
||||
mainClass = MainClassFinder.findSingleMainClass(classesDirs,
|
||||
SPRING_BOOT_APPLICATION_CLASS_NAME);
|
||||
mainClass = MainClassFinder.findSingleMainClass(classesDirs, SPRING_BOOT_APPLICATION_CLASS_NAME);
|
||||
getProject().getLogger().info("Computed main class: " + mainClass);
|
||||
}
|
||||
catch (IOException ex) {
|
||||
@@ -139,13 +135,11 @@ public class FindMainClassTask extends DefaultTask {
|
||||
}
|
||||
|
||||
private Collection<File> getClassesDirs(SourceSetOutput sourceSetOutput) {
|
||||
Method getClassesDirs = ReflectionUtils.findMethod(SourceSetOutput.class,
|
||||
"getClassesDirs");
|
||||
Method getClassesDirs = ReflectionUtils.findMethod(SourceSetOutput.class, "getClassesDirs");
|
||||
if (getClassesDirs == null) {
|
||||
return Arrays.asList(sourceSetOutput.getClassesDir());
|
||||
}
|
||||
FileCollection classesDirs = (FileCollection) ReflectionUtils
|
||||
.invokeMethod(getClassesDirs, sourceSetOutput);
|
||||
FileCollection classesDirs = (FileCollection) ReflectionUtils.invokeMethod(getClassesDirs, sourceSetOutput);
|
||||
return classesDirs.getFiles();
|
||||
}
|
||||
|
||||
|
||||
@@ -47,8 +47,8 @@ public class RunPluginFeatures implements PluginFeatures {
|
||||
}
|
||||
|
||||
private void mainClassNameFinder(Project project) {
|
||||
FindMainClassTask findMainClassTask = project.getTasks()
|
||||
.create(FIND_MAIN_CLASS_TASK_NAME, FindMainClassTask.class);
|
||||
FindMainClassTask findMainClassTask = project.getTasks().create(FIND_MAIN_CLASS_TASK_NAME,
|
||||
FindMainClassTask.class);
|
||||
SourceSet mainSourceSet = SourceSets.findMainSourceSet(project);
|
||||
if (mainSourceSet != null) {
|
||||
findMainClassTask.setMainClassSourceSetOutput(mainSourceSet.getOutput());
|
||||
@@ -64,24 +64,21 @@ public class RunPluginFeatures implements PluginFeatures {
|
||||
}
|
||||
|
||||
private void addBootRunTask(final Project project) {
|
||||
final JavaPluginConvention javaConvention = project.getConvention()
|
||||
.getPlugin(JavaPluginConvention.class);
|
||||
final JavaPluginConvention javaConvention = project.getConvention().getPlugin(JavaPluginConvention.class);
|
||||
|
||||
BootRunTask run = project.getTasks().create(RUN_APP_TASK_NAME, BootRunTask.class);
|
||||
run.setDescription("Run the project with support for "
|
||||
+ "auto-detecting main class and reloading static resources");
|
||||
run.setDescription(
|
||||
"Run the project with support for " + "auto-detecting main class and reloading static resources");
|
||||
run.setGroup("application");
|
||||
run.setClasspath(
|
||||
javaConvention.getSourceSets().findByName("main").getRuntimeClasspath());
|
||||
run.setClasspath(javaConvention.getSourceSets().findByName("main").getRuntimeClasspath());
|
||||
run.getConventionMapping().map("main", new Callable<Object>() {
|
||||
@Override
|
||||
public Object call() throws Exception {
|
||||
if (project.hasProperty("mainClassName")
|
||||
&& project.property("mainClassName") != null) {
|
||||
if (project.hasProperty("mainClassName") && project.property("mainClassName") != null) {
|
||||
return project.property("mainClassName");
|
||||
}
|
||||
ExtraPropertiesExtension extraPropertiesExtension = (ExtraPropertiesExtension) project
|
||||
.getExtensions().getByName("ext");
|
||||
ExtraPropertiesExtension extraPropertiesExtension = (ExtraPropertiesExtension) project.getExtensions()
|
||||
.getByName("ext");
|
||||
if (extraPropertiesExtension.has("mainClassName")
|
||||
&& extraPropertiesExtension.get("mainClassName") != null) {
|
||||
return extraPropertiesExtension.get("mainClassName");
|
||||
|
||||
@@ -43,8 +43,7 @@ final class SourceSets {
|
||||
}
|
||||
|
||||
private static Iterable<SourceSet> getJavaSourceSets(Project project) {
|
||||
JavaPluginConvention plugin = project.getConvention()
|
||||
.getPlugin(JavaPluginConvention.class);
|
||||
JavaPluginConvention plugin = project.getConvention().getPlugin(JavaPluginConvention.class);
|
||||
if (plugin == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@@ -68,12 +68,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() + "'");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,8 +84,7 @@ public final class BuildPropertiesWriter {
|
||||
properties.put("build.version", project.getVersion());
|
||||
properties.put("build.time", formatDate(new Date()));
|
||||
if (project.getAdditionalProperties() != null) {
|
||||
for (Map.Entry<String, String> entry : project.getAdditionalProperties()
|
||||
.entrySet()) {
|
||||
for (Map.Entry<String, String> entry : project.getAdditionalProperties().entrySet()) {
|
||||
properties.put("build." + entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
@@ -123,8 +121,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) {
|
||||
for (Entry<String, String> property : additionalProperties.entrySet()) {
|
||||
if (property.getValue() == null) {
|
||||
@@ -159,8 +156,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");
|
||||
|
||||
@@ -41,8 +41,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 final String content;
|
||||
|
||||
@@ -75,8 +74,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) {
|
||||
|
||||
@@ -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 {
|
||||
DigestInputStream inputStream = new DigestInputStream(
|
||||
new FileInputStream(file), MessageDigest.getInstance("SHA-1"));
|
||||
DigestInputStream inputStream = new DigestInputStream(new FileInputStream(file),
|
||||
MessageDigest.getInstance("SHA-1"));
|
||||
try {
|
||||
byte[] buffer = new byte[4098];
|
||||
while (inputStream.read(buffer) != -1) {
|
||||
|
||||
@@ -78,8 +78,7 @@ public class JarWriter implements LoaderClassesWriter {
|
||||
* @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());
|
||||
@@ -126,19 +125,16 @@ public class JarWriter implements LoaderClassesWriter {
|
||||
this.writeEntries(jarFile, new IdentityEntryTransformer());
|
||||
}
|
||||
|
||||
void writeEntries(JarFile jarFile, EntryTransformer entryTransformer)
|
||||
throws IOException {
|
||||
void writeEntries(JarFile jarFile, EntryTransformer entryTransformer) throws IOException {
|
||||
Enumeration<JarEntry> entries = jarFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
JarEntry entry = entries.nextElement();
|
||||
ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(
|
||||
jarFile.getInputStream(entry));
|
||||
ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(jarFile.getInputStream(entry));
|
||||
try {
|
||||
if (inputStream.hasZipHeader() && entry.getMethod() != ZipEntry.STORED) {
|
||||
new CrcAndSize(inputStream).setupStoredEntry(entry);
|
||||
inputStream.close();
|
||||
inputStream = new ZipHeaderPeekInputStream(
|
||||
jarFile.getInputStream(entry));
|
||||
inputStream = new ZipHeaderPeekInputStream(jarFile.getInputStream(entry));
|
||||
}
|
||||
else {
|
||||
entry.setCompressedSize(-1);
|
||||
@@ -173,8 +169,7 @@ public class JarWriter implements LoaderClassesWriter {
|
||||
* @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();
|
||||
JarEntry entry = new JarEntry(destination + library.getName());
|
||||
entry.setTime(getNestedLibraryTime(file));
|
||||
@@ -225,8 +220,7 @@ public class JarWriter implements LoaderClassesWriter {
|
||||
@Override
|
||||
public void writeLoaderClasses(String loaderJarResourceName) throws IOException {
|
||||
URL loaderJar = getClass().getClassLoader().getResource(loaderJarResourceName);
|
||||
JarInputStream inputStream = new JarInputStream(
|
||||
new BufferedInputStream(loaderJar.openStream()));
|
||||
JarInputStream inputStream = new JarInputStream(new BufferedInputStream(loaderJar.openStream()));
|
||||
JarEntry entry;
|
||||
while ((entry = inputStream.getNextJarEntry()) != null) {
|
||||
if (entry.getName().endsWith(".class")) {
|
||||
@@ -334,8 +328,7 @@ public class JarWriter implements LoaderClassesWriter {
|
||||
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
|
||||
@@ -358,8 +351,7 @@ public class JarWriter implements LoaderClassesWriter {
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
@@ -35,8 +35,7 @@ public class JavaExecutable {
|
||||
|
||||
public JavaExecutable() {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
Assert.state(StringUtils.hasLength(javaHome),
|
||||
"Unable to find java executable due to missing 'java.home'");
|
||||
Assert.state(StringUtils.hasLength(javaHome), "Unable to find java executable due to missing 'java.home'");
|
||||
this.file = findInJavaHome(javaHome);
|
||||
}
|
||||
|
||||
|
||||
@@ -31,8 +31,7 @@ abstract class JvmUtils {
|
||||
/**
|
||||
* Various search locations for tools, including the odd Java 6 OSX jar.
|
||||
*/
|
||||
private static final String[] TOOLS_LOCATIONS = { "lib/tools.jar", "../lib/tools.jar",
|
||||
"../Classes/classes.jar" };
|
||||
private static final String[] TOOLS_LOCATIONS = { "lib/tools.jar", "../lib/tools.jar", "../Classes/classes.jar" };
|
||||
|
||||
public static ClassLoader getToolsClassLoader() {
|
||||
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
|
||||
@@ -57,8 +56,7 @@ abstract class JvmUtils {
|
||||
|
||||
private static String getJavaHome() {
|
||||
try {
|
||||
return new File(System.getProperty("java.home")).toURI().toURL()
|
||||
.toExternalForm();
|
||||
return new File(System.getProperty("java.home")).toURI().toURL().toExternalForm();
|
||||
}
|
||||
catch (MalformedURLException ex) {
|
||||
throw new IllegalStateException("Cannot locate java.home", ex);
|
||||
|
||||
@@ -52,8 +52,7 @@ public final class Layouts {
|
||||
if (file.getName().toLowerCase(Locale.ENGLISH).endsWith(".war")) {
|
||||
return new War();
|
||||
}
|
||||
if (file.isDirectory()
|
||||
|| file.getName().toLowerCase(Locale.ENGLISH).endsWith(".zip")) {
|
||||
if (file.isDirectory() || file.getName().toLowerCase(Locale.ENGLISH).endsWith(".zip")) {
|
||||
return new Expanded();
|
||||
}
|
||||
throw new IllegalStateException("Unable to deduce layout for '" + file + "'");
|
||||
@@ -167,8 +166,7 @@ public final class Layouts {
|
||||
public static class Module implements Layout {
|
||||
|
||||
private static final Set<LibraryScope> LIB_DESTINATION_SCOPES = new HashSet<LibraryScope>(
|
||||
Arrays.asList(LibraryScope.COMPILE, LibraryScope.RUNTIME,
|
||||
LibraryScope.CUSTOM));
|
||||
Arrays.asList(LibraryScope.COMPILE, LibraryScope.RUNTIME, LibraryScope.CUSTOM));
|
||||
|
||||
@Override
|
||||
public String getLauncherClassName() {
|
||||
|
||||
@@ -57,8 +57,7 @@ public abstract class MainClassFinder {
|
||||
|
||||
private static final Type STRING_ARRAY_TYPE = Type.getType(String[].class);
|
||||
|
||||
private static final Type MAIN_METHOD_TYPE = Type.getMethodType(Type.VOID_TYPE,
|
||||
STRING_ARRAY_TYPE);
|
||||
private static final Type MAIN_METHOD_TYPE = Type.getMethodType(Type.VOID_TYPE, STRING_ARRAY_TYPE);
|
||||
|
||||
private static final String MAIN_METHOD_NAME = "main";
|
||||
|
||||
@@ -111,8 +110,7 @@ public abstract class MainClassFinder {
|
||||
* @return the main class or {@code null}
|
||||
* @throws IOException if the folder cannot be read
|
||||
*/
|
||||
public static String findSingleMainClass(File rootFolder, String annotationName)
|
||||
throws IOException {
|
||||
public static String findSingleMainClass(File rootFolder, String annotationName) throws IOException {
|
||||
SingleMainClassCallback callback = new SingleMainClassCallback(annotationName);
|
||||
MainClassFinder.doWithMainClasses(rootFolder, callback);
|
||||
return callback.getMainClassName();
|
||||
@@ -129,8 +127,7 @@ public abstract class MainClassFinder {
|
||||
* @throws IOException if a root folder cannot be read
|
||||
* @since 1.5.5
|
||||
*/
|
||||
public static String findSingleMainClass(Collection<File> rootFolders,
|
||||
String annotationName) throws IOException {
|
||||
public static String findSingleMainClass(Collection<File> rootFolders, String annotationName) throws IOException {
|
||||
SingleMainClassCallback callback = new SingleMainClassCallback(annotationName);
|
||||
doWithMainClasses(rootFolders, callback);
|
||||
return callback.getMainClassName();
|
||||
@@ -145,8 +142,7 @@ public abstract class MainClassFinder {
|
||||
* @return the first callback result or {@code null}
|
||||
* @throws IOException in case of I/O errors
|
||||
*/
|
||||
static <T> T doWithMainClasses(Collection<File> rootFolders,
|
||||
MainClassCallback<T> callback) throws IOException {
|
||||
static <T> T doWithMainClasses(Collection<File> rootFolders, MainClassCallback<T> callback) throws IOException {
|
||||
for (File rootFolder : rootFolders) {
|
||||
T result = doWithMainClasses(rootFolder, callback);
|
||||
if (result != null) {
|
||||
@@ -165,14 +161,12 @@ public abstract class MainClassFinder {
|
||||
* @return the first callback result or {@code null}
|
||||
* @throws IOException in case of I/O errors
|
||||
*/
|
||||
static <T> T doWithMainClasses(File rootFolder, MainClassCallback<T> callback)
|
||||
throws IOException {
|
||||
static <T> T doWithMainClasses(File rootFolder, MainClassCallback<T> callback) throws IOException {
|
||||
if (!rootFolder.exists()) {
|
||||
return null; // nothing to do
|
||||
}
|
||||
if (!rootFolder.isDirectory()) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid root folder '" + rootFolder + "'");
|
||||
throw new IllegalArgumentException("Invalid root folder '" + rootFolder + "'");
|
||||
}
|
||||
String prefix = rootFolder.getAbsolutePath() + "/";
|
||||
Deque<File> stack = new ArrayDeque<File>();
|
||||
@@ -184,10 +178,8 @@ public abstract class MainClassFinder {
|
||||
try {
|
||||
ClassDescriptor classDescriptor = createClassDescriptor(inputStream);
|
||||
if (classDescriptor != null && classDescriptor.isMainMethodFound()) {
|
||||
String className = convertToClassName(file.getAbsolutePath(),
|
||||
prefix);
|
||||
T result = callback.doWith(new MainClass(className,
|
||||
classDescriptor.getAnnotationNames()));
|
||||
String className = convertToClassName(file.getAbsolutePath(), prefix);
|
||||
T result = callback.doWith(new MainClass(className, classDescriptor.getAnnotationNames()));
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
@@ -224,15 +216,13 @@ public abstract class MainClassFinder {
|
||||
* @return the main class or {@code null}
|
||||
* @throws IOException if the jar file cannot be read
|
||||
*/
|
||||
public static String findMainClass(JarFile jarFile, String classesLocation)
|
||||
throws IOException {
|
||||
return doWithMainClasses(jarFile, classesLocation,
|
||||
new MainClassCallback<String>() {
|
||||
@Override
|
||||
public String doWith(MainClass mainClass) {
|
||||
return mainClass.getName();
|
||||
}
|
||||
});
|
||||
public static String findMainClass(JarFile jarFile, String classesLocation) throws IOException {
|
||||
return doWithMainClasses(jarFile, classesLocation, new MainClassCallback<String>() {
|
||||
@Override
|
||||
public String doWith(MainClass mainClass) {
|
||||
return mainClass.getName();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -242,8 +232,7 @@ public abstract class MainClassFinder {
|
||||
* @return the main class or {@code null}
|
||||
* @throws IOException if the jar file cannot be read
|
||||
*/
|
||||
public static String findSingleMainClass(JarFile jarFile, String classesLocation)
|
||||
throws IOException {
|
||||
public static String findSingleMainClass(JarFile jarFile, String classesLocation) throws IOException {
|
||||
return findSingleMainClass(jarFile, classesLocation, null);
|
||||
}
|
||||
|
||||
@@ -258,8 +247,8 @@ public abstract class MainClassFinder {
|
||||
* @return the main class or {@code null}
|
||||
* @throws IOException if the jar file cannot be read
|
||||
*/
|
||||
public static String findSingleMainClass(JarFile jarFile, String classesLocation,
|
||||
String annotationName) throws IOException {
|
||||
public static String findSingleMainClass(JarFile jarFile, String classesLocation, String annotationName)
|
||||
throws IOException {
|
||||
SingleMainClassCallback callback = new SingleMainClassCallback(annotationName);
|
||||
MainClassFinder.doWithMainClasses(jarFile, classesLocation, callback);
|
||||
return callback.getMainClassName();
|
||||
@@ -274,20 +263,17 @@ public abstract class MainClassFinder {
|
||||
* @return the first callback result or {@code null}
|
||||
* @throws IOException in case of I/O errors
|
||||
*/
|
||||
static <T> T doWithMainClasses(JarFile jarFile, String classesLocation,
|
||||
MainClassCallback<T> callback) throws IOException {
|
||||
static <T> T doWithMainClasses(JarFile jarFile, String classesLocation, MainClassCallback<T> callback)
|
||||
throws IOException {
|
||||
List<JarEntry> classEntries = getClassEntries(jarFile, classesLocation);
|
||||
Collections.sort(classEntries, new ClassEntryComparator());
|
||||
for (JarEntry entry : classEntries) {
|
||||
InputStream inputStream = new BufferedInputStream(
|
||||
jarFile.getInputStream(entry));
|
||||
InputStream inputStream = new BufferedInputStream(jarFile.getInputStream(entry));
|
||||
try {
|
||||
ClassDescriptor classDescriptor = createClassDescriptor(inputStream);
|
||||
if (classDescriptor != null && classDescriptor.isMainMethodFound()) {
|
||||
String className = convertToClassName(entry.getName(),
|
||||
classesLocation);
|
||||
T result = callback.doWith(new MainClass(className,
|
||||
classDescriptor.getAnnotationNames()));
|
||||
String className = convertToClassName(entry.getName(), classesLocation);
|
||||
T result = callback.doWith(new MainClass(className, classDescriptor.getAnnotationNames()));
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
@@ -310,15 +296,13 @@ public abstract class MainClassFinder {
|
||||
return name;
|
||||
}
|
||||
|
||||
private static List<JarEntry> getClassEntries(JarFile source,
|
||||
String classesLocation) {
|
||||
private static List<JarEntry> getClassEntries(JarFile source, String classesLocation) {
|
||||
classesLocation = (classesLocation != null) ? classesLocation : "";
|
||||
Enumeration<JarEntry> sourceEntries = source.entries();
|
||||
List<JarEntry> classEntries = new ArrayList<JarEntry>();
|
||||
while (sourceEntries.hasMoreElements()) {
|
||||
JarEntry entry = sourceEntries.nextElement();
|
||||
if (entry.getName().startsWith(classesLocation)
|
||||
&& entry.getName().endsWith(DOT_CLASS)) {
|
||||
if (entry.getName().startsWith(classesLocation) && entry.getName().endsWith(DOT_CLASS)) {
|
||||
classEntries.add(entry);
|
||||
}
|
||||
}
|
||||
@@ -373,10 +357,8 @@ public abstract class MainClassFinder {
|
||||
}
|
||||
|
||||
@Override
|
||||
public MethodVisitor visitMethod(int access, String name, String desc,
|
||||
String signature, String[] exceptions) {
|
||||
if (isAccess(access, Opcodes.ACC_PUBLIC, Opcodes.ACC_STATIC)
|
||||
&& MAIN_METHOD_NAME.equals(name)
|
||||
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
|
||||
if (isAccess(access, Opcodes.ACC_PUBLIC, Opcodes.ACC_STATIC) && MAIN_METHOD_NAME.equals(name)
|
||||
&& MAIN_METHOD_TYPE.getDescriptor().equals(desc)) {
|
||||
this.mainMethodFound = true;
|
||||
}
|
||||
@@ -436,8 +418,7 @@ public abstract class MainClassFinder {
|
||||
*/
|
||||
MainClass(String name, Set<String> annotationNames) {
|
||||
this.name = name;
|
||||
this.annotationNames = Collections
|
||||
.unmodifiableSet(new HashSet<String>(annotationNames));
|
||||
this.annotationNames = Collections.unmodifiableSet(new HashSet<String>(annotationNames));
|
||||
}
|
||||
|
||||
String getName() {
|
||||
@@ -482,8 +463,7 @@ public abstract class MainClassFinder {
|
||||
* Find a single main class, throwing an {@link IllegalStateException} if multiple
|
||||
* candidates exist.
|
||||
*/
|
||||
private static final class SingleMainClassCallback
|
||||
implements MainClassCallback<Object> {
|
||||
private static final class SingleMainClassCallback implements MainClassCallback<Object> {
|
||||
|
||||
private final Set<MainClass> mainClasses = new LinkedHashSet<MainClass>();
|
||||
|
||||
@@ -513,11 +493,9 @@ public abstract class MainClassFinder {
|
||||
}
|
||||
if (matchingMainClasses.size() > 1) {
|
||||
throw new IllegalStateException(
|
||||
"Unable to find a single main class from the following candidates "
|
||||
+ matchingMainClasses);
|
||||
"Unable to find a single main class from the following candidates " + matchingMainClasses);
|
||||
}
|
||||
return (matchingMainClasses.isEmpty() ? null
|
||||
: matchingMainClasses.iterator().next().getName());
|
||||
return (matchingMainClasses.isEmpty() ? null : matchingMainClasses.iterator().next().getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -82,8 +82,8 @@ public class Repackager {
|
||||
throw new IllegalArgumentException("Source file must be provided");
|
||||
}
|
||||
if (!source.exists() || !source.isFile()) {
|
||||
throw new IllegalArgumentException("Source must refer to an existing file, "
|
||||
+ "got " + source.getAbsolutePath());
|
||||
throw new IllegalArgumentException(
|
||||
"Source must refer to an existing file, " + "got " + source.getAbsolutePath());
|
||||
}
|
||||
this.source = source.getAbsoluteFile();
|
||||
this.layoutFactory = layoutFactory;
|
||||
@@ -94,8 +94,7 @@ public class Repackager {
|
||||
* main class takes too long.
|
||||
* @param listener the listener to add
|
||||
*/
|
||||
public void addMainClassTimeoutWarningListener(
|
||||
MainClassTimeoutWarningListener listener) {
|
||||
public void addMainClassTimeoutWarningListener(MainClassTimeoutWarningListener listener) {
|
||||
this.mainClassTimeoutListeners.add(listener);
|
||||
}
|
||||
|
||||
@@ -166,8 +165,7 @@ public class Repackager {
|
||||
* @throws IOException if the file cannot be repackaged
|
||||
* @since 1.3.0
|
||||
*/
|
||||
public void repackage(File destination, Libraries libraries,
|
||||
LaunchScript launchScript) throws IOException {
|
||||
public void repackage(File destination, Libraries libraries, LaunchScript launchScript) throws IOException {
|
||||
if (destination == null || destination.isDirectory()) {
|
||||
throw new IllegalArgumentException("Invalid destination");
|
||||
}
|
||||
@@ -208,8 +206,7 @@ public class Repackager {
|
||||
if (this.layoutFactory != null) {
|
||||
return this.layoutFactory;
|
||||
}
|
||||
List<LayoutFactory> factories = SpringFactoriesLoader
|
||||
.loadFactories(LayoutFactory.class, null);
|
||||
List<LayoutFactory> factories = SpringFactoriesLoader.loadFactories(LayoutFactory.class, null);
|
||||
if (factories.isEmpty()) {
|
||||
return new DefaultLayoutFactory();
|
||||
}
|
||||
@@ -229,16 +226,15 @@ public class Repackager {
|
||||
JarFile jarFile = new JarFile(this.source);
|
||||
try {
|
||||
Manifest manifest = jarFile.getManifest();
|
||||
return (manifest != null && manifest.getMainAttributes()
|
||||
.getValue(BOOT_VERSION_ATTRIBUTE) != null);
|
||||
return (manifest != null && manifest.getMainAttributes().getValue(BOOT_VERSION_ATTRIBUTE) != null);
|
||||
}
|
||||
finally {
|
||||
jarFile.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void repackage(JarFile sourceJar, File destination, Libraries libraries,
|
||||
LaunchScript launchScript) throws IOException {
|
||||
private void repackage(JarFile sourceJar, File destination, Libraries libraries, LaunchScript launchScript)
|
||||
throws IOException {
|
||||
JarWriter writer = new JarWriter(destination, launchScript);
|
||||
try {
|
||||
final List<Library> unpackLibraries = new ArrayList<Library>();
|
||||
@@ -271,15 +267,14 @@ public class Repackager {
|
||||
}
|
||||
}
|
||||
|
||||
private void repackage(JarFile sourceJar, JarWriter writer,
|
||||
final List<Library> unpackLibraries, final List<Library> standardLibraries)
|
||||
throws IOException {
|
||||
private void repackage(JarFile sourceJar, JarWriter writer, final List<Library> unpackLibraries,
|
||||
final List<Library> standardLibraries) throws IOException {
|
||||
writer.writeManifest(buildManifest(sourceJar));
|
||||
Set<String> seen = new HashSet<String>();
|
||||
writeNestedLibraries(unpackLibraries, seen, writer);
|
||||
if (this.layout instanceof RepackagingLayout) {
|
||||
writer.writeEntries(sourceJar, new RenamingEntryTransformer(
|
||||
((RepackagingLayout) this.layout).getRepackagedClassesLocation()));
|
||||
writer.writeEntries(sourceJar,
|
||||
new RenamingEntryTransformer(((RepackagingLayout) this.layout).getRepackagedClassesLocation()));
|
||||
}
|
||||
else {
|
||||
writer.writeEntries(sourceJar);
|
||||
@@ -288,15 +283,13 @@ public class Repackager {
|
||||
writeLoaderClasses(writer);
|
||||
}
|
||||
|
||||
private void writeNestedLibraries(List<Library> libraries, Set<String> alreadySeen,
|
||||
JarWriter writer) throws IOException {
|
||||
private void writeNestedLibraries(List<Library> libraries, Set<String> alreadySeen, JarWriter writer)
|
||||
throws IOException {
|
||||
for (Library library : libraries) {
|
||||
String destination = Repackager.this.layout
|
||||
.getLibraryDestination(library.getName(), library.getScope());
|
||||
String destination = Repackager.this.layout.getLibraryDestination(library.getName(), library.getScope());
|
||||
if (destination != null) {
|
||||
if (!alreadySeen.add(destination + library.getName())) {
|
||||
throw new IllegalStateException(
|
||||
"Duplicate library " + library.getName());
|
||||
throw new IllegalStateException("Duplicate library " + library.getName());
|
||||
}
|
||||
writer.writeNestedLibrary(destination, library);
|
||||
}
|
||||
@@ -352,8 +345,7 @@ public class Repackager {
|
||||
}
|
||||
String launcherClassName = this.layout.getLauncherClassName();
|
||||
if (launcherClassName != null) {
|
||||
manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE,
|
||||
launcherClassName);
|
||||
manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE, launcherClassName);
|
||||
if (startClass == null) {
|
||||
throw new IllegalStateException("Unable to find main class");
|
||||
}
|
||||
@@ -364,10 +356,8 @@ public class Repackager {
|
||||
}
|
||||
String bootVersion = getClass().getPackage().getImplementationVersion();
|
||||
manifest.getMainAttributes().putValue(BOOT_VERSION_ATTRIBUTE, bootVersion);
|
||||
manifest.getMainAttributes().putValue(BOOT_CLASSES_ATTRIBUTE,
|
||||
(this.layout instanceof RepackagingLayout)
|
||||
? ((RepackagingLayout) this.layout).getRepackagedClassesLocation()
|
||||
: this.layout.getClassesLocation());
|
||||
manifest.getMainAttributes().putValue(BOOT_CLASSES_ATTRIBUTE, (this.layout instanceof RepackagingLayout)
|
||||
? ((RepackagingLayout) this.layout).getRepackagedClassesLocation() : this.layout.getClassesLocation());
|
||||
String lib = this.layout.getLibraryDestination("", LibraryScope.COMPILE);
|
||||
if (StringUtils.hasLength(lib)) {
|
||||
manifest.getMainAttributes().putValue(BOOT_LIB_ATTRIBUTE, lib);
|
||||
@@ -388,14 +378,13 @@ public class Repackager {
|
||||
}
|
||||
|
||||
protected String findMainMethod(JarFile source) throws IOException {
|
||||
return MainClassFinder.findSingleMainClass(source,
|
||||
this.layout.getClassesLocation(), SPRING_BOOT_APPLICATION_CLASS_NAME);
|
||||
return MainClassFinder.findSingleMainClass(source, this.layout.getClassesLocation(),
|
||||
SPRING_BOOT_APPLICATION_CLASS_NAME);
|
||||
}
|
||||
|
||||
private void renameFile(File file, File dest) {
|
||||
if (!file.renameTo(dest)) {
|
||||
throw new IllegalStateException(
|
||||
"Unable to rename '" + file + "' to '" + dest + "'");
|
||||
throw new IllegalStateException("Unable to rename '" + file + "' to '" + dest + "'");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,8 +425,7 @@ public class Repackager {
|
||||
if (entry.getName().equals("META-INF/INDEX.LIST")) {
|
||||
return null;
|
||||
}
|
||||
if ((entry.getName().startsWith("META-INF/")
|
||||
&& !entry.getName().equals("META-INF/aop.xml"))
|
||||
if ((entry.getName().startsWith("META-INF/") && !entry.getName().equals("META-INF/aop.xml"))
|
||||
|| entry.getName().startsWith("BOOT-INF/")) {
|
||||
return entry;
|
||||
}
|
||||
|
||||
@@ -38,8 +38,7 @@ import org.springframework.util.ReflectionUtils;
|
||||
*/
|
||||
public class RunProcess {
|
||||
|
||||
private static final Method INHERIT_IO_METHOD = ReflectionUtils
|
||||
.findMethod(ProcessBuilder.class, "inheritIO");
|
||||
private static final Method INHERIT_IO_METHOD = ReflectionUtils.findMethod(ProcessBuilder.class, "inheritIO");
|
||||
|
||||
private static final long JUST_ENDED_LIMIT = 500;
|
||||
|
||||
@@ -75,8 +74,7 @@ public class RunProcess {
|
||||
return run(waitForProcess, Arrays.asList(args));
|
||||
}
|
||||
|
||||
protected int run(boolean waitForProcess, Collection<String> args)
|
||||
throws IOException {
|
||||
protected int run(boolean waitForProcess, Collection<String> args) throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder(this.command);
|
||||
builder.directory(this.workingDirectory);
|
||||
builder.command().addAll(args);
|
||||
@@ -129,8 +127,7 @@ public class RunProcess {
|
||||
// There's a bug in the Windows VM (https://bugs.openjdk.java.net/browse/JDK-8023130)
|
||||
// that means we need to avoid inheritIO
|
||||
private static boolean isInheritIOBroken() {
|
||||
if (!System.getProperty("os.name", "none").toLowerCase(Locale.ENGLISH)
|
||||
.contains("windows")) {
|
||||
if (!System.getProperty("os.name", "none").toLowerCase(Locale.ENGLISH).contains("windows")) {
|
||||
return false;
|
||||
}
|
||||
String runtime = System.getProperty("java.runtime.version");
|
||||
@@ -154,8 +151,7 @@ public class RunProcess {
|
||||
}
|
||||
|
||||
private void redirectOutput(Process process) {
|
||||
final BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(process.getInputStream()));
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
new Thread() {
|
||||
|
||||
@Override
|
||||
|
||||
@@ -160,8 +160,7 @@ public class DefaultLaunchScriptTests {
|
||||
public void expandVariables() throws Exception {
|
||||
File file = this.temporaryFolder.newFile();
|
||||
FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file);
|
||||
DefaultLaunchScript script = new DefaultLaunchScript(file,
|
||||
createProperties("a:e", "b:o"));
|
||||
DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o"));
|
||||
String content = new String(script.toByteArray());
|
||||
assertThat(content).isEqualTo("hello");
|
||||
}
|
||||
@@ -170,8 +169,7 @@ public class DefaultLaunchScriptTests {
|
||||
public void expandVariablesMultiLine() throws Exception {
|
||||
File file = this.temporaryFolder.newFile();
|
||||
FileCopyUtils.copy("h{{a}}l\nl{{b}}".getBytes(), file);
|
||||
DefaultLaunchScript script = new DefaultLaunchScript(file,
|
||||
createProperties("a:e", "b:o"));
|
||||
DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o"));
|
||||
String content = new String(script.toByteArray());
|
||||
assertThat(content).isEqualTo("hel\nlo");
|
||||
}
|
||||
@@ -189,8 +187,7 @@ public class DefaultLaunchScriptTests {
|
||||
public void expandVariablesWithDefaultsOverride() throws Exception {
|
||||
File file = this.temporaryFolder.newFile();
|
||||
FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file);
|
||||
DefaultLaunchScript script = new DefaultLaunchScript(file,
|
||||
createProperties("a:a"));
|
||||
DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:a"));
|
||||
String content = new String(script.toByteArray());
|
||||
assertThat(content).isEqualTo("hallo");
|
||||
}
|
||||
@@ -205,8 +202,7 @@ public class DefaultLaunchScriptTests {
|
||||
}
|
||||
|
||||
private void assertThatPlaceholderCanBeReplaced(String placeholder) throws Exception {
|
||||
DefaultLaunchScript script = new DefaultLaunchScript(null,
|
||||
createProperties(placeholder + ":__test__"));
|
||||
DefaultLaunchScript script = new DefaultLaunchScript(null, createProperties(placeholder + ":__test__"));
|
||||
String content = new String(script.toByteArray());
|
||||
assertThat(content).contains("__test__");
|
||||
}
|
||||
|
||||
@@ -60,8 +60,7 @@ public class FileUtilsTests {
|
||||
File file = new File(this.outputDirectory, "logback.xml");
|
||||
file.createNewFile();
|
||||
new File(this.originDirectory, "logback.xml").createNewFile();
|
||||
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory,
|
||||
this.originDirectory);
|
||||
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory);
|
||||
assertThat(file.exists()).isFalse();
|
||||
}
|
||||
|
||||
@@ -72,8 +71,7 @@ public class FileUtilsTests {
|
||||
File file = new File(this.outputDirectory, "sub/logback.xml");
|
||||
file.createNewFile();
|
||||
new File(this.originDirectory, "sub/logback.xml").createNewFile();
|
||||
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory,
|
||||
this.originDirectory);
|
||||
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory);
|
||||
assertThat(file.exists()).isFalse();
|
||||
}
|
||||
|
||||
@@ -84,8 +82,7 @@ public class FileUtilsTests {
|
||||
File file = new File(this.outputDirectory, "sub/logback.xml");
|
||||
file.createNewFile();
|
||||
new File(this.originDirectory, "sub/different.xml").createNewFile();
|
||||
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory,
|
||||
this.originDirectory);
|
||||
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory);
|
||||
assertThat(file.exists()).isTrue();
|
||||
}
|
||||
|
||||
@@ -94,8 +91,7 @@ public class FileUtilsTests {
|
||||
File file = new File(this.outputDirectory, "logback.xml");
|
||||
file.createNewFile();
|
||||
new File(this.originDirectory, "different.xml").createNewFile();
|
||||
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory,
|
||||
this.originDirectory);
|
||||
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory);
|
||||
assertThat(file.exists()).isTrue();
|
||||
}
|
||||
|
||||
@@ -109,8 +105,7 @@ public class FileUtilsTests {
|
||||
finally {
|
||||
outputStream.close();
|
||||
}
|
||||
assertThat(FileUtils.sha1Hash(file))
|
||||
.isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf");
|
||||
assertThat(FileUtils.sha1Hash(file)).isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -40,8 +40,7 @@ public class LayoutsTests {
|
||||
assertThat(Layouts.forFile(new File("test.jar"))).isInstanceOf(Layouts.Jar.class);
|
||||
assertThat(Layouts.forFile(new File("test.JAR"))).isInstanceOf(Layouts.Jar.class);
|
||||
assertThat(Layouts.forFile(new File("test.jAr"))).isInstanceOf(Layouts.Jar.class);
|
||||
assertThat(Layouts.forFile(new File("te.st.jar")))
|
||||
.isInstanceOf(Layouts.Jar.class);
|
||||
assertThat(Layouts.forFile(new File("te.st.jar"))).isInstanceOf(Layouts.Jar.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -49,8 +48,7 @@ public class LayoutsTests {
|
||||
assertThat(Layouts.forFile(new File("test.war"))).isInstanceOf(Layouts.War.class);
|
||||
assertThat(Layouts.forFile(new File("test.WAR"))).isInstanceOf(Layouts.War.class);
|
||||
assertThat(Layouts.forFile(new File("test.wAr"))).isInstanceOf(Layouts.War.class);
|
||||
assertThat(Layouts.forFile(new File("te.st.war")))
|
||||
.isInstanceOf(Layouts.War.class);
|
||||
assertThat(Layouts.forFile(new File("te.st.war"))).isInstanceOf(Layouts.War.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,41 +61,29 @@ public class LayoutsTests {
|
||||
@Test
|
||||
public void jarLayout() throws Exception {
|
||||
Layout layout = new Layouts.Jar();
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE))
|
||||
.isEqualTo("BOOT-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM))
|
||||
.isEqualTo("BOOT-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED))
|
||||
.isEqualTo("BOOT-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME))
|
||||
.isEqualTo("BOOT-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("BOOT-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("BOOT-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)).isEqualTo("BOOT-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)).isEqualTo("BOOT-INF/lib/");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void warLayout() throws Exception {
|
||||
Layout layout = new Layouts.War();
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE))
|
||||
.isEqualTo("WEB-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM))
|
||||
.isEqualTo("WEB-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED))
|
||||
.isEqualTo("WEB-INF/lib-provided/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME))
|
||||
.isEqualTo("WEB-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("WEB-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("WEB-INF/lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)).isEqualTo("WEB-INF/lib-provided/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)).isEqualTo("WEB-INF/lib/");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("deprecation")
|
||||
public void moduleLayout() throws Exception {
|
||||
Layout layout = new Layouts.Module();
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE))
|
||||
.isEqualTo("lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED))
|
||||
.isNull();
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME))
|
||||
.isEqualTo("lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM))
|
||||
.isEqualTo("lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)).isNull();
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)).isEqualTo("lib/");
|
||||
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("lib/");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -84,8 +84,8 @@ public class MainClassFinderTests {
|
||||
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
|
||||
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
this.thrown.expectMessage("Unable to find a single main class "
|
||||
+ "from the following candidates [a.B, a.b.c.E]");
|
||||
this.thrown
|
||||
.expectMessage("Unable to find a single main class " + "from the following candidates [a.B, a.b.c.E]");
|
||||
MainClassFinder.findSingleMainClass(this.testJarFile.getJarFile(), "");
|
||||
}
|
||||
|
||||
@@ -93,8 +93,7 @@ public class MainClassFinderTests {
|
||||
public void findSingleJarSearchPrefersAnnotatedMainClass() throws Exception {
|
||||
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
|
||||
this.testJarFile.addClass("a/b/c/E.class", AnnotatedClassWithMainMethod.class);
|
||||
String mainClass = MainClassFinder.findSingleMainClass(
|
||||
this.testJarFile.getJarFile(), "",
|
||||
String mainClass = MainClassFinder.findSingleMainClass(this.testJarFile.getJarFile(), "",
|
||||
"org.springframework.boot.loader.tools.sample.SomeApplication");
|
||||
assertThat(mainClass).isEqualTo("a.b.c.E");
|
||||
}
|
||||
@@ -103,8 +102,7 @@ public class MainClassFinderTests {
|
||||
public void findMainClassInJarSubLocation() throws Exception {
|
||||
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
|
||||
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
|
||||
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(),
|
||||
"a/");
|
||||
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "a/");
|
||||
assertThat(actual).isEqualTo("B");
|
||||
|
||||
}
|
||||
@@ -139,8 +137,8 @@ public class MainClassFinderTests {
|
||||
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
|
||||
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
this.thrown.expectMessage("Unable to find a single main class "
|
||||
+ "from the following candidates [a.B, a.b.c.E]");
|
||||
this.thrown
|
||||
.expectMessage("Unable to find a single main class " + "from the following candidates [a.B, a.b.c.E]");
|
||||
MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource());
|
||||
}
|
||||
|
||||
@@ -148,8 +146,7 @@ public class MainClassFinderTests {
|
||||
public void findSingleFolderSearchPrefersAnnotatedMainClass() throws Exception {
|
||||
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
|
||||
this.testJarFile.addClass("a/b/c/E.class", AnnotatedClassWithMainMethod.class);
|
||||
String mainClass = MainClassFinder.findSingleMainClass(
|
||||
this.testJarFile.getJarSource(),
|
||||
String mainClass = MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource(),
|
||||
"org.springframework.boot.loader.tools.sample.SomeApplication");
|
||||
assertThat(mainClass).isEqualTo("a.b.c.E");
|
||||
}
|
||||
|
||||
@@ -117,8 +117,7 @@ public class RepackagerTests {
|
||||
Manifest actualManifest = getManifest(file);
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo("org.springframework.boot.loader.JarLauncher");
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"))
|
||||
.isEqualTo("a.b.C");
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C");
|
||||
assertThat(hasLauncherClasses(file)).isTrue();
|
||||
}
|
||||
|
||||
@@ -135,8 +134,7 @@ public class RepackagerTests {
|
||||
Manifest actualManifest = getManifest(file);
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo("org.springframework.boot.loader.JarLauncher");
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"))
|
||||
.isEqualTo("a.b.C");
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C");
|
||||
assertThat(hasLauncherClasses(file)).isTrue();
|
||||
}
|
||||
|
||||
@@ -149,8 +147,7 @@ public class RepackagerTests {
|
||||
Manifest actualManifest = getManifest(file);
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo("org.springframework.boot.loader.JarLauncher");
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"))
|
||||
.isEqualTo("a.b.C");
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C");
|
||||
assertThat(hasLauncherClasses(file)).isTrue();
|
||||
}
|
||||
|
||||
@@ -164,8 +161,7 @@ public class RepackagerTests {
|
||||
Manifest actualManifest = getManifest(file);
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo("org.springframework.boot.loader.JarLauncher");
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"))
|
||||
.isEqualTo("a.b.C");
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C");
|
||||
assertThat(hasLauncherClasses(file)).isTrue();
|
||||
}
|
||||
|
||||
@@ -176,8 +172,8 @@ public class RepackagerTests {
|
||||
File file = this.testJarFile.getFile();
|
||||
Repackager repackager = new Repackager(file);
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
this.thrown.expectMessage("Unable to find a single main class "
|
||||
+ "from the following candidates [a.b.C, a.b.D]");
|
||||
this.thrown
|
||||
.expectMessage("Unable to find a single main class " + "from the following candidates [a.b.C, a.b.D]");
|
||||
repackager.repackage(NO_LIBRARIES);
|
||||
}
|
||||
|
||||
@@ -197,8 +193,7 @@ public class RepackagerTests {
|
||||
repackager.setLayout(new Layouts.None());
|
||||
repackager.repackage(file, NO_LIBRARIES);
|
||||
Manifest actualManifest = getManifest(file);
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo("a.b.C");
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Main-Class")).isEqualTo("a.b.C");
|
||||
assertThat(hasLauncherClasses(file)).isFalse();
|
||||
}
|
||||
|
||||
@@ -210,8 +205,7 @@ public class RepackagerTests {
|
||||
repackager.setLayout(new Layouts.None());
|
||||
repackager.repackage(file, NO_LIBRARIES);
|
||||
Manifest actualManifest = getManifest(file);
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo(null);
|
||||
assertThat(actualManifest.getMainAttributes().getValue("Main-Class")).isEqualTo(null);
|
||||
assertThat(hasLauncherClasses(file)).isFalse();
|
||||
}
|
||||
|
||||
@@ -232,8 +226,7 @@ public class RepackagerTests {
|
||||
Repackager repackager = new Repackager(file);
|
||||
repackager.setBackupSource(false);
|
||||
repackager.repackage(NO_LIBRARIES);
|
||||
assertThat(new File(file.getParent(), file.getName() + ".original"))
|
||||
.doesNotExist();
|
||||
assertThat(new File(file.getParent(), file.getName() + ".original")).doesNotExist();
|
||||
assertThat(hasLauncherClasses(file)).isTrue();
|
||||
}
|
||||
|
||||
@@ -244,8 +237,7 @@ public class RepackagerTests {
|
||||
File dest = this.temporaryFolder.newFile("different.jar");
|
||||
Repackager repackager = new Repackager(source);
|
||||
repackager.repackage(dest, NO_LIBRARIES);
|
||||
assertThat(new File(source.getParent(), source.getName() + ".original"))
|
||||
.doesNotExist();
|
||||
assertThat(new File(source.getParent(), source.getName() + ".original")).doesNotExist();
|
||||
assertThat(hasLauncherClasses(source)).isFalse();
|
||||
assertThat(hasLauncherClasses(dest)).isTrue();
|
||||
}
|
||||
@@ -297,8 +289,7 @@ public class RepackagerTests {
|
||||
final File libNonJarFile = this.temporaryFolder.newFile();
|
||||
FileCopyUtils.copy(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, libNonJarFile);
|
||||
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
|
||||
this.testJarFile.addFile("BOOT-INF/lib/" + libJarFileToUnpack.getName(),
|
||||
libJarFileToUnpack);
|
||||
this.testJarFile.addFile("BOOT-INF/lib/" + libJarFileToUnpack.getName(), libJarFileToUnpack);
|
||||
File file = this.testJarFile.getFile();
|
||||
libJarFile.setLastModified(JAN_1_1980);
|
||||
Repackager repackager = new Repackager(file);
|
||||
@@ -306,14 +297,12 @@ public class RepackagerTests {
|
||||
@Override
|
||||
public void doWithLibraries(LibraryCallback callback) throws IOException {
|
||||
callback.library(new Library(libJarFile, LibraryScope.COMPILE));
|
||||
callback.library(
|
||||
new Library(libJarFileToUnpack, LibraryScope.COMPILE, true));
|
||||
callback.library(new Library(libJarFileToUnpack, LibraryScope.COMPILE, true));
|
||||
callback.library(new Library(libNonJarFile, LibraryScope.COMPILE));
|
||||
}
|
||||
});
|
||||
assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFile.getName())).isTrue();
|
||||
assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName()))
|
||||
.isTrue();
|
||||
assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName())).isTrue();
|
||||
assertThat(hasEntry(file, "BOOT-INF/lib/" + libNonJarFile.getName())).isFalse();
|
||||
JarEntry entry = getEntry(file, "BOOT-INF/lib/" + libJarFile.getName());
|
||||
assertThat(entry.getTime()).isEqualTo(JAN_1_1985);
|
||||
@@ -353,8 +342,7 @@ public class RepackagerTests {
|
||||
final LibraryScope scope = mock(LibraryScope.class);
|
||||
given(layout.getLauncherClassName()).willReturn("testLauncher");
|
||||
given(layout.getLibraryDestination(anyString(), eq(scope))).willReturn("test/");
|
||||
given(layout.getLibraryDestination(anyString(), eq(LibraryScope.COMPILE)))
|
||||
.willReturn("test-lib/");
|
||||
given(layout.getLibraryDestination(anyString(), eq(LibraryScope.COMPILE))).willReturn("test-lib/");
|
||||
repackager.setLayout(layout);
|
||||
repackager.repackage(new Libraries() {
|
||||
|
||||
@@ -365,10 +353,8 @@ public class RepackagerTests {
|
||||
|
||||
});
|
||||
assertThat(hasEntry(file, "test/" + libJarFile.getName())).isTrue();
|
||||
assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib"))
|
||||
.isEqualTo("test-lib/");
|
||||
assertThat(getManifest(file).getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo("testLauncher");
|
||||
assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo("test-lib/");
|
||||
assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")).isEqualTo("testLauncher");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -391,10 +377,8 @@ public class RepackagerTests {
|
||||
}
|
||||
|
||||
});
|
||||
assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib"))
|
||||
.isNull();
|
||||
assertThat(getManifest(file).getMainAttributes().getValue("Main-Class"))
|
||||
.isEqualTo("testLauncher");
|
||||
assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")).isNull();
|
||||
assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")).isEqualTo("testLauncher");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -404,8 +388,7 @@ public class RepackagerTests {
|
||||
Repackager repackager = new Repackager(file);
|
||||
repackager.repackage(NO_LIBRARIES);
|
||||
Manifest actualManifest = getManifest(file);
|
||||
assertThat(actualManifest.getMainAttributes())
|
||||
.containsKey(new Attributes.Name("Spring-Boot-Version"));
|
||||
assertThat(actualManifest.getMainAttributes()).containsKey(new Attributes.Name("Spring-Boot-Version"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -415,24 +398,23 @@ public class RepackagerTests {
|
||||
Repackager repackager = new Repackager(file);
|
||||
repackager.repackage(NO_LIBRARIES);
|
||||
Manifest actualManifest = getManifest(file);
|
||||
assertThat(actualManifest.getMainAttributes())
|
||||
.containsEntry(new Attributes.Name("Spring-Boot-Lib"), "BOOT-INF/lib/");
|
||||
assertThat(actualManifest.getMainAttributes()).containsEntry(
|
||||
new Attributes.Name("Spring-Boot-Classes"), "BOOT-INF/classes/");
|
||||
assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Lib"),
|
||||
"BOOT-INF/lib/");
|
||||
assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Classes"),
|
||||
"BOOT-INF/classes/");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void executableWarLayoutAttributes() throws Exception {
|
||||
this.testJarFile.addClass("WEB-INF/classes/a/b/C.class",
|
||||
ClassWithMainMethod.class);
|
||||
this.testJarFile.addClass("WEB-INF/classes/a/b/C.class", ClassWithMainMethod.class);
|
||||
File file = this.testJarFile.getFile("war");
|
||||
Repackager repackager = new Repackager(file);
|
||||
repackager.repackage(NO_LIBRARIES);
|
||||
Manifest actualManifest = getManifest(file);
|
||||
assertThat(actualManifest.getMainAttributes())
|
||||
.containsEntry(new Attributes.Name("Spring-Boot-Lib"), "WEB-INF/lib/");
|
||||
assertThat(actualManifest.getMainAttributes()).containsEntry(
|
||||
new Attributes.Name("Spring-Boot-Classes"), "WEB-INF/classes/");
|
||||
assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Lib"),
|
||||
"WEB-INF/lib/");
|
||||
assertThat(actualManifest.getMainAttributes()).containsEntry(new Attributes.Name("Spring-Boot-Classes"),
|
||||
"WEB-INF/classes/");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -461,11 +443,8 @@ public class RepackagerTests {
|
||||
});
|
||||
JarFile jarFile = new JarFile(file);
|
||||
try {
|
||||
assertThat(
|
||||
jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getMethod())
|
||||
.isEqualTo(ZipEntry.STORED);
|
||||
assertThat(jarFile.getEntry("BOOT-INF/classes/test/nested.jar").getMethod())
|
||||
.isEqualTo(ZipEntry.STORED);
|
||||
assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getMethod()).isEqualTo(ZipEntry.STORED);
|
||||
assertThat(jarFile.getEntry("BOOT-INF/classes/test/nested.jar").getMethod()).isEqualTo(ZipEntry.STORED);
|
||||
}
|
||||
finally {
|
||||
jarFile.close();
|
||||
@@ -485,8 +464,7 @@ public class RepackagerTests {
|
||||
assertThat(hasLauncherClasses(source)).isFalse();
|
||||
assertThat(hasLauncherClasses(dest)).isTrue();
|
||||
try {
|
||||
assertThat(Files.getPosixFilePermissions(dest.toPath()))
|
||||
.contains(PosixFilePermission.OWNER_EXECUTE);
|
||||
assertThat(Files.getPosixFilePermissions(dest.toPath())).contains(PosixFilePermission.OWNER_EXECUTE);
|
||||
}
|
||||
catch (UnsupportedOperationException ex) {
|
||||
// Probably running the test on Windows
|
||||
@@ -494,13 +472,11 @@ public class RepackagerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unpackLibrariesTakePrecedenceOverExistingSourceEntries()
|
||||
throws Exception {
|
||||
public void unpackLibrariesTakePrecedenceOverExistingSourceEntries() throws Exception {
|
||||
TestJarFile nested = new TestJarFile(this.temporaryFolder);
|
||||
nested.addClass("a/b/C.class", ClassWithoutMainMethod.class);
|
||||
final File nestedFile = nested.getFile();
|
||||
this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(),
|
||||
nested.getFile());
|
||||
this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), nested.getFile());
|
||||
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
|
||||
File file = this.testJarFile.getFile();
|
||||
Repackager repackager = new Repackager(file);
|
||||
@@ -514,9 +490,7 @@ public class RepackagerTests {
|
||||
});
|
||||
JarFile jarFile = new JarFile(file);
|
||||
try {
|
||||
assertThat(
|
||||
jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getComment())
|
||||
.startsWith("UNPACK:");
|
||||
assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getComment()).startsWith("UNPACK:");
|
||||
}
|
||||
finally {
|
||||
jarFile.close();
|
||||
@@ -524,13 +498,11 @@ public class RepackagerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void existingSourceEntriesTakePrecedenceOverStandardLibraries()
|
||||
throws Exception {
|
||||
public void existingSourceEntriesTakePrecedenceOverStandardLibraries() throws Exception {
|
||||
TestJarFile nested = new TestJarFile(this.temporaryFolder);
|
||||
nested.addClass("a/b/C.class", ClassWithoutMainMethod.class);
|
||||
final File nestedFile = nested.getFile();
|
||||
this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(),
|
||||
nested.getFile());
|
||||
this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), nested.getFile());
|
||||
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
|
||||
File file = this.testJarFile.getFile();
|
||||
Repackager repackager = new Repackager(file);
|
||||
@@ -548,8 +520,7 @@ public class RepackagerTests {
|
||||
});
|
||||
JarFile jarFile = new JarFile(file);
|
||||
try {
|
||||
assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize())
|
||||
.isEqualTo(sourceLength);
|
||||
assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize()).isEqualTo(sourceLength);
|
||||
}
|
||||
finally {
|
||||
jarFile.close();
|
||||
@@ -559,8 +530,7 @@ public class RepackagerTests {
|
||||
@Test
|
||||
public void metaInfIndexListIsRemovedFromRepackagedJar() throws Exception {
|
||||
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
|
||||
this.testJarFile.addFile("META-INF/INDEX.LIST",
|
||||
this.temporaryFolder.newFile("INDEX.LIST"));
|
||||
this.testJarFile.addFile("META-INF/INDEX.LIST", this.temporaryFolder.newFile("INDEX.LIST"));
|
||||
File source = this.testJarFile.getFile();
|
||||
File dest = this.temporaryFolder.newFile("dest.jar");
|
||||
Repackager repackager = new Repackager(source);
|
||||
@@ -598,11 +568,9 @@ public class RepackagerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void metaInfAopXmlIsMovedBeneathBootInfClassesWhenRepackaged()
|
||||
throws Exception {
|
||||
public void metaInfAopXmlIsMovedBeneathBootInfClassesWhenRepackaged() throws Exception {
|
||||
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
|
||||
this.testJarFile.addFile("META-INF/aop.xml",
|
||||
this.temporaryFolder.newFile("aop.xml"));
|
||||
this.testJarFile.addFile("META-INF/aop.xml", this.temporaryFolder.newFile("aop.xml"));
|
||||
File source = this.testJarFile.getFile();
|
||||
File dest = this.temporaryFolder.newFile("dest.jar");
|
||||
Repackager repackager = new Repackager(source);
|
||||
@@ -618,8 +586,7 @@ public class RepackagerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jarThatUsesCustomCompressionConfigurationCanBeRepackaged()
|
||||
throws IOException {
|
||||
public void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() throws IOException {
|
||||
File source = this.temporaryFolder.newFile("source.jar");
|
||||
ZipOutputStream output = new ZipOutputStream(new FileOutputStream(source)) {
|
||||
{
|
||||
|
||||
@@ -50,12 +50,11 @@ public class TestJarFile {
|
||||
addClass(filename, classToCopy, null);
|
||||
}
|
||||
|
||||
public void addClass(String filename, Class<?> classToCopy, Long time)
|
||||
throws IOException {
|
||||
public void addClass(String filename, Class<?> classToCopy, Long time) throws IOException {
|
||||
File file = getFilePath(filename);
|
||||
file.getParentFile().mkdirs();
|
||||
InputStream inputStream = getClass().getResourceAsStream(
|
||||
"/" + classToCopy.getName().replace('.', '/') + ".class");
|
||||
InputStream inputStream = getClass()
|
||||
.getResourceAsStream("/" + classToCopy.getName().replace('.', '/') + ".class");
|
||||
copyToFile(inputStream, file);
|
||||
if (time != null) {
|
||||
file.setLastModified(time);
|
||||
@@ -95,8 +94,7 @@ public class TestJarFile {
|
||||
return file;
|
||||
}
|
||||
|
||||
private void copyToFile(InputStream inputStream, File file)
|
||||
throws FileNotFoundException, IOException {
|
||||
private void copyToFile(InputStream inputStream, File file) throws FileNotFoundException, IOException {
|
||||
OutputStream outputStream = new FileOutputStream(file);
|
||||
try {
|
||||
copy(inputStream, outputStream);
|
||||
|
||||
@@ -33,12 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
public class ZipHeaderPeekInputStreamTests {
|
||||
|
||||
@Test
|
||||
public void hasZipHeaderReturnsTrueWhenStreamStartsWithZipHeader()
|
||||
throws IOException {
|
||||
public void hasZipHeaderReturnsTrueWhenStreamStartsWithZipHeader() throws IOException {
|
||||
ZipHeaderPeekInputStream in = null;
|
||||
try {
|
||||
in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(
|
||||
new byte[] { 0x50, 0x4b, 0x03, 0x04, 5, 6 }));
|
||||
in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0x50, 0x4b, 0x03, 0x04, 5, 6 }));
|
||||
assertThat(in.hasZipHeader()).isTrue();
|
||||
}
|
||||
finally {
|
||||
@@ -49,12 +47,10 @@ public class ZipHeaderPeekInputStreamTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasZipHeaderReturnsFalseWheStreamDoesNotStartWithZipHeader()
|
||||
throws IOException {
|
||||
public void hasZipHeaderReturnsFalseWheStreamDoesNotStartWithZipHeader() throws IOException {
|
||||
ZipHeaderPeekInputStream in = null;
|
||||
try {
|
||||
in = new ZipHeaderPeekInputStream(
|
||||
new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }));
|
||||
in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }));
|
||||
assertThat(in.hasZipHeader()).isFalse();
|
||||
}
|
||||
finally {
|
||||
@@ -68,8 +64,7 @@ public class ZipHeaderPeekInputStreamTests {
|
||||
public void readIndividualBytes() throws IOException {
|
||||
ZipHeaderPeekInputStream in = null;
|
||||
try {
|
||||
in = new ZipHeaderPeekInputStream(
|
||||
new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }));
|
||||
in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }));
|
||||
assertThat(in.read()).isEqualTo(0);
|
||||
assertThat(in.read()).isEqualTo(1);
|
||||
assertThat(in.read()).isEqualTo(2);
|
||||
@@ -88,8 +83,7 @@ public class ZipHeaderPeekInputStreamTests {
|
||||
public void readMultipleBytes() throws IOException {
|
||||
ZipHeaderPeekInputStream in = null;
|
||||
try {
|
||||
in = new ZipHeaderPeekInputStream(
|
||||
new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }));
|
||||
in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }));
|
||||
byte[] bytes = new byte[3];
|
||||
assertThat(in.read(bytes)).isEqualTo(3);
|
||||
assertThat(bytes).containsExactly(0, 1, 2);
|
||||
@@ -108,8 +102,7 @@ public class ZipHeaderPeekInputStreamTests {
|
||||
public void readingMoreThanEntireStreamReadsToEndOfStream() throws IOException {
|
||||
ZipHeaderPeekInputStream in = null;
|
||||
try {
|
||||
in = new ZipHeaderPeekInputStream(
|
||||
new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }));
|
||||
in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }));
|
||||
byte[] bytes = new byte[8];
|
||||
assertThat(in.read(bytes)).isEqualTo(6);
|
||||
assertThat(bytes).containsExactly(0, 1, 2, 3, 4, 5, 0, 0);
|
||||
@@ -123,12 +116,10 @@ public class ZipHeaderPeekInputStreamTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readOfSomeOfTheHeaderThenMoreThanEntireStreamReadsToEndOfStream()
|
||||
throws IOException {
|
||||
public void readOfSomeOfTheHeaderThenMoreThanEntireStreamReadsToEndOfStream() throws IOException {
|
||||
ZipHeaderPeekInputStream in = null;
|
||||
try {
|
||||
in = new ZipHeaderPeekInputStream(
|
||||
new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }));
|
||||
in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }));
|
||||
byte[] bytes = new byte[8];
|
||||
assertThat(in.read(bytes, 0, 3)).isEqualTo(3);
|
||||
assertThat(bytes).containsExactly(0, 1, 2, 0, 0, 0, 0, 0);
|
||||
@@ -143,12 +134,10 @@ public class ZipHeaderPeekInputStreamTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readMoreThanEntireStreamWhenStreamLengthIsLessThanZipHeaderLength()
|
||||
throws IOException {
|
||||
public void readMoreThanEntireStreamWhenStreamLengthIsLessThanZipHeaderLength() throws IOException {
|
||||
ZipHeaderPeekInputStream in = null;
|
||||
try {
|
||||
in = new ZipHeaderPeekInputStream(
|
||||
new ByteArrayInputStream(new byte[] { 10 }));
|
||||
in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 10 }));
|
||||
byte[] bytes = new byte[8];
|
||||
assertThat(in.read(bytes)).isEqualTo(1);
|
||||
assertThat(bytes).containsExactly(10, 0, 0, 0, 0, 0, 0, 0);
|
||||
@@ -161,12 +150,10 @@ public class ZipHeaderPeekInputStreamTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readMoreThanEntireStreamWhenStreamLengthIsSameAsHeaderLength()
|
||||
throws IOException {
|
||||
public void readMoreThanEntireStreamWhenStreamLengthIsSameAsHeaderLength() throws IOException {
|
||||
ZipHeaderPeekInputStream in = null;
|
||||
try {
|
||||
in = new ZipHeaderPeekInputStream(
|
||||
new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 }));
|
||||
in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 }));
|
||||
byte[] bytes = new byte[8];
|
||||
assertThat(in.read(bytes)).isEqualTo(4);
|
||||
assertThat(bytes).containsExactly(1, 2, 3, 4, 0, 0, 0, 0);
|
||||
|
||||
@@ -60,23 +60,21 @@ public abstract class ExecutableArchiveLauncher extends Launcher {
|
||||
mainClass = manifest.getMainAttributes().getValue("Start-Class");
|
||||
}
|
||||
if (mainClass == null) {
|
||||
throw new IllegalStateException(
|
||||
"No 'Start-Class' manifest entry specified in " + this);
|
||||
throw new IllegalStateException("No 'Start-Class' manifest entry specified in " + this);
|
||||
}
|
||||
return mainClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<Archive> getClassPathArchives() throws Exception {
|
||||
List<Archive> archives = new ArrayList<Archive>(
|
||||
this.archive.getNestedArchives(new EntryFilter() {
|
||||
List<Archive> archives = new ArrayList<Archive>(this.archive.getNestedArchives(new EntryFilter() {
|
||||
|
||||
@Override
|
||||
public boolean matches(Entry entry) {
|
||||
return isNestedArchive(entry);
|
||||
}
|
||||
@Override
|
||||
public boolean matches(Entry entry) {
|
||||
return isNestedArchive(entry);
|
||||
}
|
||||
|
||||
}));
|
||||
}));
|
||||
postProcessClassPathArchives(archives);
|
||||
return archives;
|
||||
}
|
||||
|
||||
@@ -74,8 +74,7 @@ public class LaunchedURLClassLoader extends URLClassLoader {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?> loadClass(String name, boolean resolve)
|
||||
throws ClassNotFoundException {
|
||||
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
|
||||
Handler.setUseFastConnectionExceptions(true);
|
||||
try {
|
||||
try {
|
||||
@@ -87,8 +86,8 @@ public class LaunchedURLClassLoader extends URLClassLoader {
|
||||
// This should never happen as the IllegalArgumentException indicates
|
||||
// that the package has already been defined and, therefore,
|
||||
// getPackage(name) should not return null.
|
||||
throw new AssertionError("Package " + name + " has already been "
|
||||
+ "defined but it could not be found");
|
||||
throw new AssertionError(
|
||||
"Package " + name + " has already been " + "defined but it could not be found");
|
||||
}
|
||||
}
|
||||
return super.loadClass(name, resolve);
|
||||
@@ -119,8 +118,7 @@ public class LaunchedURLClassLoader extends URLClassLoader {
|
||||
// indicates that the package has already been defined and,
|
||||
// therefore, getPackage(name) should not have returned null.
|
||||
throw new AssertionError(
|
||||
"Package " + packageName + " has already been defined "
|
||||
+ "but it could not be found");
|
||||
"Package " + packageName + " has already been defined " + "but it could not be found");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,13 +136,11 @@ public class LaunchedURLClassLoader extends URLClassLoader {
|
||||
try {
|
||||
URLConnection connection = url.openConnection();
|
||||
if (connection instanceof JarURLConnection) {
|
||||
JarFile jarFile = ((JarURLConnection) connection)
|
||||
.getJarFile();
|
||||
JarFile jarFile = ((JarURLConnection) connection).getJarFile();
|
||||
if (jarFile.getEntry(classEntryName) != null
|
||||
&& jarFile.getEntry(packageEntryName) != null
|
||||
&& jarFile.getManifest() != null) {
|
||||
definePackage(packageName, jarFile.getManifest(),
|
||||
url);
|
||||
definePackage(packageName, jarFile.getManifest(), url);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,8 +81,7 @@ public abstract class Launcher {
|
||||
* @param classLoader the classloader
|
||||
* @throws Exception if the launch fails
|
||||
*/
|
||||
protected void launch(String[] args, String mainClass, ClassLoader classLoader)
|
||||
throws Exception {
|
||||
protected void launch(String[] args, String mainClass, ClassLoader classLoader) throws Exception {
|
||||
Thread.currentThread().setContextClassLoader(classLoader);
|
||||
createMainMethodRunner(mainClass, args, classLoader).run();
|
||||
}
|
||||
@@ -94,8 +93,7 @@ public abstract class Launcher {
|
||||
* @param classLoader the classloader
|
||||
* @return the main method runner
|
||||
*/
|
||||
protected MainMethodRunner createMainMethodRunner(String mainClass, String[] args,
|
||||
ClassLoader classLoader) {
|
||||
protected MainMethodRunner createMainMethodRunner(String mainClass, String[] args, ClassLoader classLoader) {
|
||||
return new MainMethodRunner(mainClass, args);
|
||||
}
|
||||
|
||||
@@ -123,11 +121,9 @@ public abstract class Launcher {
|
||||
}
|
||||
File root = new File(path);
|
||||
if (!root.exists()) {
|
||||
throw new IllegalStateException(
|
||||
"Unable to determine code source archive from " + root);
|
||||
throw new IllegalStateException("Unable to determine code source archive from " + root);
|
||||
}
|
||||
return (root.isDirectory() ? new ExplodedArchive(root)
|
||||
: new JarFileArchive(root));
|
||||
return (root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -42,8 +42,7 @@ public class MainMethodRunner {
|
||||
}
|
||||
|
||||
public void run() throws Exception {
|
||||
Class<?> mainClass = Thread.currentThread().getContextClassLoader()
|
||||
.loadClass(this.mainClassName);
|
||||
Class<?> mainClass = Thread.currentThread().getContextClassLoader().loadClass(this.mainClassName);
|
||||
Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
|
||||
mainMethod.invoke(null, new Object[] { this.args });
|
||||
}
|
||||
|
||||
@@ -159,8 +159,7 @@ public class PropertiesLauncher extends Launcher {
|
||||
configs.add(getProperty(CONFIG_LOCATION));
|
||||
}
|
||||
else {
|
||||
String[] names = getPropertyWithDefault(CONFIG_NAME, "loader,application")
|
||||
.split(",");
|
||||
String[] names = getPropertyWithDefault(CONFIG_NAME, "loader,application").split(",");
|
||||
for (String name : names) {
|
||||
configs.add("file:" + getHomeDirectory() + "/" + name + ".properties");
|
||||
configs.add("classpath:" + name + ".properties");
|
||||
@@ -178,13 +177,11 @@ public class PropertiesLauncher extends Launcher {
|
||||
resource.close();
|
||||
}
|
||||
for (Object key : Collections.list(this.properties.propertyNames())) {
|
||||
if (config.endsWith("application.properties")
|
||||
&& ((String) key).startsWith("loader.")) {
|
||||
if (config.endsWith("application.properties") && ((String) key).startsWith("loader.")) {
|
||||
warn("Use of application.properties for PropertiesLauncher is deprecated");
|
||||
}
|
||||
String text = this.properties.getProperty((String) key);
|
||||
String value = SystemPropertyUtils
|
||||
.resolvePlaceholders(this.properties, text);
|
||||
String value = SystemPropertyUtils.resolvePlaceholders(this.properties, text);
|
||||
if (value != null) {
|
||||
this.properties.put(key, value);
|
||||
}
|
||||
@@ -273,8 +270,7 @@ public class PropertiesLauncher extends Launcher {
|
||||
// Try a URL connection content-length header...
|
||||
URLConnection connection = url.openConnection();
|
||||
try {
|
||||
connection.setUseCaches(
|
||||
connection.getClass().getSimpleName().startsWith("JNLP"));
|
||||
connection.setUseCaches(connection.getClass().getSimpleName().startsWith("JNLP"));
|
||||
if (connection instanceof HttpURLConnection) {
|
||||
HttpURLConnection httpConnection = (HttpURLConnection) connection;
|
||||
httpConnection.setRequestMethod("HEAD");
|
||||
@@ -324,8 +320,7 @@ public class PropertiesLauncher extends Launcher {
|
||||
String[] additionalArgs = args;
|
||||
args = new String[defaultArgs.length + additionalArgs.length];
|
||||
System.arraycopy(defaultArgs, 0, args, 0, defaultArgs.length);
|
||||
System.arraycopy(additionalArgs, 0, args, defaultArgs.length,
|
||||
additionalArgs.length);
|
||||
System.arraycopy(additionalArgs, 0, args, defaultArgs.length, additionalArgs.length);
|
||||
}
|
||||
return args;
|
||||
}
|
||||
@@ -334,8 +329,7 @@ public class PropertiesLauncher extends Launcher {
|
||||
protected String getMainClass() throws Exception {
|
||||
String mainClass = getProperty(MAIN, "Start-Class");
|
||||
if (mainClass == null) {
|
||||
throw new IllegalStateException(
|
||||
"No '" + MAIN + "' or 'Start-Class' specified");
|
||||
throw new IllegalStateException("No '" + MAIN + "' or 'Start-Class' specified");
|
||||
}
|
||||
return mainClass;
|
||||
}
|
||||
@@ -346,8 +340,7 @@ public class PropertiesLauncher extends Launcher {
|
||||
for (Archive archive : archives) {
|
||||
urls.add(archive.getUrl());
|
||||
}
|
||||
ClassLoader loader = new LaunchedURLClassLoader(urls.toArray(new URL[0]),
|
||||
getClass().getClassLoader());
|
||||
ClassLoader loader = new LaunchedURLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader());
|
||||
debug("Classpath: " + urls);
|
||||
String customLoaderClassName = getProperty("loader.classLoader");
|
||||
if (customLoaderClassName != null) {
|
||||
@@ -358,10 +351,8 @@ public class PropertiesLauncher extends Launcher {
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private ClassLoader wrapWithCustomClassLoader(ClassLoader parent,
|
||||
String loaderClassName) throws Exception {
|
||||
Class<ClassLoader> loaderClass = (Class<ClassLoader>) Class
|
||||
.forName(loaderClassName, true, parent);
|
||||
private ClassLoader wrapWithCustomClassLoader(ClassLoader parent, String loaderClassName) throws Exception {
|
||||
Class<ClassLoader> loaderClass = (Class<ClassLoader>) Class.forName(loaderClassName, true, parent);
|
||||
|
||||
try {
|
||||
return loaderClass.getConstructor(ClassLoader.class).newInstance(parent);
|
||||
@@ -370,8 +361,7 @@ public class PropertiesLauncher extends Launcher {
|
||||
// Ignore and try with URLs
|
||||
}
|
||||
try {
|
||||
return loaderClass.getConstructor(URL[].class, ClassLoader.class)
|
||||
.newInstance(new URL[0], parent);
|
||||
return loaderClass.getConstructor(URL[].class, ClassLoader.class).newInstance(new URL[0], parent);
|
||||
}
|
||||
catch (NoSuchMethodException ex) {
|
||||
// Ignore and try without any arguments
|
||||
@@ -387,21 +377,18 @@ public class PropertiesLauncher extends Launcher {
|
||||
return getProperty(propertyKey, manifestKey, null);
|
||||
}
|
||||
|
||||
private String getPropertyWithDefault(String propertyKey, String defaultValue)
|
||||
throws Exception {
|
||||
private String getPropertyWithDefault(String propertyKey, String defaultValue) throws Exception {
|
||||
return getProperty(propertyKey, null, defaultValue);
|
||||
}
|
||||
|
||||
private String getProperty(String propertyKey, String manifestKey,
|
||||
String defaultValue) throws Exception {
|
||||
private String getProperty(String propertyKey, String manifestKey, String defaultValue) throws Exception {
|
||||
if (manifestKey == null) {
|
||||
manifestKey = propertyKey.replace('.', '-');
|
||||
manifestKey = toCamelCase(manifestKey);
|
||||
}
|
||||
String property = SystemPropertyUtils.getProperty(propertyKey);
|
||||
if (property != null) {
|
||||
String value = SystemPropertyUtils.resolvePlaceholders(this.properties,
|
||||
property);
|
||||
String value = SystemPropertyUtils.resolvePlaceholders(this.properties, property);
|
||||
debug("Property '" + propertyKey + "' from environment: " + value);
|
||||
return value;
|
||||
}
|
||||
@@ -418,10 +405,8 @@ public class PropertiesLauncher extends Launcher {
|
||||
if (manifest != null) {
|
||||
String value = manifest.getMainAttributes().getValue(manifestKey);
|
||||
if (value != null) {
|
||||
debug("Property '" + manifestKey
|
||||
+ "' from home directory manifest: " + value);
|
||||
return SystemPropertyUtils.resolvePlaceholders(this.properties,
|
||||
value);
|
||||
debug("Property '" + manifestKey + "' from home directory manifest: " + value);
|
||||
return SystemPropertyUtils.resolvePlaceholders(this.properties, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -438,8 +423,7 @@ public class PropertiesLauncher extends Launcher {
|
||||
return SystemPropertyUtils.resolvePlaceholders(this.properties, value);
|
||||
}
|
||||
}
|
||||
return (defaultValue != null)
|
||||
? SystemPropertyUtils.resolvePlaceholders(this.properties, defaultValue)
|
||||
return (defaultValue != null) ? SystemPropertyUtils.resolvePlaceholders(this.properties, defaultValue)
|
||||
: defaultValue;
|
||||
}
|
||||
|
||||
@@ -449,8 +433,7 @@ public class PropertiesLauncher extends Launcher {
|
||||
for (String path : this.paths) {
|
||||
for (Archive archive : getClassPathArchives(path)) {
|
||||
if (archive instanceof ExplodedArchive) {
|
||||
List<Archive> nested = new ArrayList<Archive>(
|
||||
archive.getNestedArchives(new ArchiveEntryFilter()));
|
||||
List<Archive> nested = new ArrayList<Archive>(archive.getNestedArchives(new ArchiveEntryFilter()));
|
||||
nested.add(0, archive);
|
||||
lib.addAll(nested);
|
||||
}
|
||||
@@ -506,8 +489,7 @@ public class PropertiesLauncher extends Launcher {
|
||||
private List<Archive> getNestedArchives(String path) throws Exception {
|
||||
Archive parent = this.parent;
|
||||
String root = path;
|
||||
if (!root.equals("/") && root.startsWith("/")
|
||||
|| parent.getUrl().equals(this.home.toURI().toURL())) {
|
||||
if (!root.equals("/") && root.startsWith("/") || parent.getUrl().equals(this.home.toURI().toURL())) {
|
||||
// If home dir is same as parent archive, no need to add it twice.
|
||||
return null;
|
||||
}
|
||||
@@ -536,8 +518,7 @@ public class PropertiesLauncher extends Launcher {
|
||||
}
|
||||
EntryFilter filter = new PrefixMatchingArchiveFilter(root);
|
||||
List<Archive> archives = new ArrayList<Archive>(parent.getNestedArchives(filter));
|
||||
if (("".equals(root) || ".".equals(root)) && !path.endsWith(".jar")
|
||||
&& parent != this.parent) {
|
||||
if (("".equals(root) || ".".equals(root)) && !path.endsWith(".jar") && parent != this.parent) {
|
||||
// You can't find the root with an entry filter so it has to be added
|
||||
// explicitly. But don't add the root of the parent archive.
|
||||
archives.add(parent);
|
||||
|
||||
@@ -50,8 +50,7 @@ public class WarLauncher extends ExecutableArchiveLauncher {
|
||||
return entry.getName().equals(WEB_INF_CLASSES);
|
||||
}
|
||||
else {
|
||||
return entry.getName().startsWith(WEB_INF_LIB)
|
||||
|| entry.getName().startsWith(WEB_INF_LIB_PROVIDED);
|
||||
return entry.getName().startsWith(WEB_INF_LIB) || entry.getName().startsWith(WEB_INF_LIB_PROVIDED);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,8 +42,7 @@ import java.util.jar.Manifest;
|
||||
*/
|
||||
public class ExplodedArchive implements Archive {
|
||||
|
||||
private static final Set<String> SKIPPED_NAMES = new HashSet<String>(
|
||||
Arrays.asList(".", ".."));
|
||||
private static final Set<String> SKIPPED_NAMES = new HashSet<String>(Arrays.asList(".", ".."));
|
||||
|
||||
private final File root;
|
||||
|
||||
@@ -120,8 +119,7 @@ public class ExplodedArchive implements Archive {
|
||||
|
||||
protected Archive getNestedArchive(Entry entry) throws IOException {
|
||||
File file = ((FileEntry) entry).getFile();
|
||||
return (file.isDirectory() ? new ExplodedArchive(file)
|
||||
: new JarFileArchive(file));
|
||||
return (file.isDirectory() ? new ExplodedArchive(file) : new JarFileArchive(file));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -167,13 +165,11 @@ public class ExplodedArchive implements Archive {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
File file = this.current;
|
||||
if (file.isDirectory()
|
||||
&& (this.recursive || file.getParentFile().equals(this.root))) {
|
||||
if (file.isDirectory() && (this.recursive || file.getParentFile().equals(this.root))) {
|
||||
this.stack.addFirst(listFiles(file));
|
||||
}
|
||||
this.current = poll();
|
||||
String name = file.toURI().getPath()
|
||||
.substring(this.root.toURI().getPath().length());
|
||||
String name = file.toURI().getPath().substring(this.root.toURI().getPath().length());
|
||||
return new FileEntry(name, file);
|
||||
}
|
||||
|
||||
|
||||
@@ -105,8 +105,7 @@ public class JarFileArchive implements Archive {
|
||||
return new JarFileArchive(jarFile);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(
|
||||
"Failed to get nested archive for entry " + entry.getName(), ex);
|
||||
throw new IllegalStateException("Failed to get nested archive for entry " + entry.getName(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,14 +133,12 @@ public class JarFileArchive implements Archive {
|
||||
int attempts = 0;
|
||||
while (attempts++ < 1000) {
|
||||
String fileName = new File(this.jarFile.getName()).getName();
|
||||
File unpackFolder = new File(parent,
|
||||
fileName + "-spring-boot-libs-" + UUID.randomUUID());
|
||||
File unpackFolder = new File(parent, fileName + "-spring-boot-libs-" + UUID.randomUUID());
|
||||
if (unpackFolder.mkdirs()) {
|
||||
return unpackFolder;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
"Failed to create unpack folder in directory '" + parent + "'");
|
||||
throw new IllegalStateException("Failed to create unpack folder in directory '" + parent + "'");
|
||||
}
|
||||
|
||||
private void unpack(JarEntry entry, File file) throws IOException {
|
||||
|
||||
@@ -64,8 +64,7 @@ public class RandomAccessDataFile implements RandomAccessData {
|
||||
throw new IllegalArgumentException("File must not be null");
|
||||
}
|
||||
if (!file.exists()) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("File %s must exist", file.getAbsolutePath()));
|
||||
throw new IllegalArgumentException(String.format("File %s must exist", file.getAbsolutePath()));
|
||||
}
|
||||
this.file = file;
|
||||
this.filePool = new FilePool(file, concurrentReads);
|
||||
@@ -105,8 +104,7 @@ public class RandomAccessDataFile implements RandomAccessData {
|
||||
if (offset < 0 || length < 0 || offset + length > this.length) {
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
return new RandomAccessDataFile(this.file, this.filePool, this.offset + offset,
|
||||
length);
|
||||
return new RandomAccessDataFile(this.file, this.filePool, this.offset + offset, length);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -100,8 +100,8 @@ final class AsciiBytes {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < postfix.length; i++) {
|
||||
if (this.bytes[this.offset + (this.length - 1)
|
||||
- i] != postfix.bytes[postfix.offset + (postfix.length - 1) - i]) {
|
||||
if (this.bytes[this.offset + (this.length - 1) - i] != postfix.bytes[postfix.offset + (postfix.length - 1)
|
||||
- i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,8 +59,7 @@ final class Bytes {
|
||||
return fill(inputStream, bytes, 0, bytes.length);
|
||||
}
|
||||
|
||||
private static boolean fill(InputStream inputStream, byte[] bytes, int offset,
|
||||
int length) throws IOException {
|
||||
private static boolean fill(InputStream inputStream, byte[] bytes, int offset, int length) throws IOException {
|
||||
while (length > 0) {
|
||||
int read = inputStream.read(bytes, offset, length);
|
||||
if (read == -1) {
|
||||
|
||||
@@ -62,8 +62,8 @@ class CentralDirectoryEndRecord {
|
||||
this.size++;
|
||||
if (this.size > this.block.length) {
|
||||
if (this.size >= MAXIMUM_SIZE || this.size > data.getSize()) {
|
||||
throw new IOException("Unable to find ZIP central directory "
|
||||
+ "records after reading " + this.size + " bytes");
|
||||
throw new IOException(
|
||||
"Unable to find ZIP central directory " + "records after reading " + this.size + " bytes");
|
||||
}
|
||||
this.block = createBlockFromEndOfData(data, this.size + READ_BLOCK_SIZE);
|
||||
}
|
||||
@@ -71,20 +71,17 @@ class CentralDirectoryEndRecord {
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] createBlockFromEndOfData(RandomAccessData data, int size)
|
||||
throws IOException {
|
||||
private byte[] createBlockFromEndOfData(RandomAccessData data, int size) throws IOException {
|
||||
int length = (int) Math.min(data.getSize(), size);
|
||||
return Bytes.get(data.getSubsection(data.getSize() - length, length));
|
||||
}
|
||||
|
||||
private boolean isValid() {
|
||||
if (this.block.length < MINIMUM_SIZE
|
||||
|| Bytes.littleEndianValue(this.block, this.offset + 0, 4) != SIGNATURE) {
|
||||
if (this.block.length < MINIMUM_SIZE || Bytes.littleEndianValue(this.block, this.offset + 0, 4) != SIGNATURE) {
|
||||
return false;
|
||||
}
|
||||
// Total size must be the structure size + comment
|
||||
long commentLength = Bytes.littleEndianValue(this.block,
|
||||
this.offset + COMMENT_LENGTH_OFFSET, 2);
|
||||
long commentLength = Bytes.littleEndianValue(this.block, this.offset + COMMENT_LENGTH_OFFSET, 2);
|
||||
return this.size == MINIMUM_SIZE + commentLength;
|
||||
}
|
||||
|
||||
|
||||
@@ -53,8 +53,8 @@ final class CentralDirectoryFileHeader implements FileHeader {
|
||||
CentralDirectoryFileHeader() {
|
||||
}
|
||||
|
||||
CentralDirectoryFileHeader(byte[] header, int headerOffset, AsciiBytes name,
|
||||
byte[] extra, AsciiBytes comment, long localHeaderOffset) {
|
||||
CentralDirectoryFileHeader(byte[] header, int headerOffset, AsciiBytes name, byte[] extra, AsciiBytes comment,
|
||||
long localHeaderOffset) {
|
||||
super();
|
||||
this.header = header;
|
||||
this.headerOffset = headerOffset;
|
||||
@@ -64,8 +64,8 @@ final class CentralDirectoryFileHeader implements FileHeader {
|
||||
this.localHeaderOffset = localHeaderOffset;
|
||||
}
|
||||
|
||||
void load(byte[] data, int dataOffset, RandomAccessData variableData,
|
||||
int variableOffset, JarEntryFilter filter) throws IOException {
|
||||
void load(byte[] data, int dataOffset, RandomAccessData variableData, int variableOffset, JarEntryFilter filter)
|
||||
throws IOException {
|
||||
// Load fixed part
|
||||
this.header = data;
|
||||
this.headerOffset = dataOffset;
|
||||
@@ -76,8 +76,7 @@ final class CentralDirectoryFileHeader implements FileHeader {
|
||||
// Load variable part
|
||||
dataOffset += 46;
|
||||
if (variableData != null) {
|
||||
data = Bytes.get(variableData.getSubsection(variableOffset + 46,
|
||||
nameLength + extraLength + commentLength));
|
||||
data = Bytes.get(variableData.getSubsection(variableOffset + 46, nameLength + extraLength + commentLength));
|
||||
dataOffset = 0;
|
||||
}
|
||||
this.name = new AsciiBytes(data, dataOffset, (int) nameLength);
|
||||
@@ -88,12 +87,10 @@ final class CentralDirectoryFileHeader implements FileHeader {
|
||||
this.comment = NO_COMMENT;
|
||||
if (extraLength > 0) {
|
||||
this.extra = new byte[(int) extraLength];
|
||||
System.arraycopy(data, (int) (dataOffset + nameLength), this.extra, 0,
|
||||
this.extra.length);
|
||||
System.arraycopy(data, (int) (dataOffset + nameLength), this.extra, 0, this.extra.length);
|
||||
}
|
||||
if (commentLength > 0) {
|
||||
this.comment = new AsciiBytes(data,
|
||||
(int) (dataOffset + nameLength + extraLength), (int) commentLength);
|
||||
this.comment = new AsciiBytes(data, (int) (dataOffset + nameLength + extraLength), (int) commentLength);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,12 +167,11 @@ final class CentralDirectoryFileHeader implements FileHeader {
|
||||
public CentralDirectoryFileHeader clone() {
|
||||
byte[] header = new byte[46];
|
||||
System.arraycopy(this.header, this.headerOffset, header, 0, header.length);
|
||||
return new CentralDirectoryFileHeader(header, 0, this.name, header, this.comment,
|
||||
this.localHeaderOffset);
|
||||
return new CentralDirectoryFileHeader(header, 0, this.name, header, this.comment, this.localHeaderOffset);
|
||||
}
|
||||
|
||||
public static CentralDirectoryFileHeader fromRandomAccessData(RandomAccessData data,
|
||||
int offset, JarEntryFilter filter) throws IOException {
|
||||
public static CentralDirectoryFileHeader fromRandomAccessData(RandomAccessData data, int offset,
|
||||
JarEntryFilter filter) throws IOException {
|
||||
CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader();
|
||||
byte[] bytes = Bytes.get(data.getSubsection(offset, 46));
|
||||
fileHeader.load(bytes, 0, data, offset, filter);
|
||||
|
||||
@@ -46,8 +46,7 @@ class CentralDirectoryParser {
|
||||
* @return the actual archive data without any prefix bytes
|
||||
* @throws IOException on error
|
||||
*/
|
||||
public RandomAccessData parse(RandomAccessData data, boolean skipPrefixBytes)
|
||||
throws IOException {
|
||||
public RandomAccessData parse(RandomAccessData data, boolean skipPrefixBytes) throws IOException {
|
||||
CentralDirectoryEndRecord endRecord = new CentralDirectoryEndRecord(data);
|
||||
if (skipPrefixBytes) {
|
||||
data = getArchiveData(endRecord, data);
|
||||
@@ -59,22 +58,20 @@ class CentralDirectoryParser {
|
||||
return data;
|
||||
}
|
||||
|
||||
private void parseEntries(CentralDirectoryEndRecord endRecord,
|
||||
RandomAccessData centralDirectoryData) throws IOException {
|
||||
private void parseEntries(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData)
|
||||
throws IOException {
|
||||
byte[] bytes = Bytes.get(centralDirectoryData);
|
||||
CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader();
|
||||
int dataOffset = 0;
|
||||
for (int i = 0; i < endRecord.getNumberOfRecords(); i++) {
|
||||
fileHeader.load(bytes, dataOffset, null, 0, null);
|
||||
visitFileHeader(dataOffset, fileHeader);
|
||||
dataOffset += this.CENTRAL_DIRECTORY_HEADER_BASE_SIZE
|
||||
+ fileHeader.getName().length() + fileHeader.getComment().length()
|
||||
+ fileHeader.getExtra().length;
|
||||
dataOffset += this.CENTRAL_DIRECTORY_HEADER_BASE_SIZE + fileHeader.getName().length()
|
||||
+ fileHeader.getComment().length() + fileHeader.getExtra().length;
|
||||
}
|
||||
}
|
||||
|
||||
private RandomAccessData getArchiveData(CentralDirectoryEndRecord endRecord,
|
||||
RandomAccessData data) {
|
||||
private RandomAccessData getArchiveData(CentralDirectoryEndRecord endRecord, RandomAccessData data) {
|
||||
long offset = endRecord.getStartOfArchive(data);
|
||||
if (offset == 0) {
|
||||
return data;
|
||||
@@ -82,8 +79,7 @@ class CentralDirectoryParser {
|
||||
return data.getSubsection(offset, data.getSize() - offset);
|
||||
}
|
||||
|
||||
private void visitStart(CentralDirectoryEndRecord endRecord,
|
||||
RandomAccessData centralDirectoryData) {
|
||||
private void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) {
|
||||
for (CentralDirectoryVisitor visitor : this.visitors) {
|
||||
visitor.visitStart(endRecord, centralDirectoryData);
|
||||
}
|
||||
|
||||
@@ -25,8 +25,7 @@ import org.springframework.boot.loader.data.RandomAccessData;
|
||||
*/
|
||||
interface CentralDirectoryVisitor {
|
||||
|
||||
void visitStart(CentralDirectoryEndRecord endRecord,
|
||||
RandomAccessData centralDirectoryData);
|
||||
void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData);
|
||||
|
||||
void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset);
|
||||
|
||||
|
||||
@@ -55,16 +55,14 @@ public class Handler extends URLStreamHandler {
|
||||
|
||||
private static final String PARENT_DIR = "/../";
|
||||
|
||||
private static final String[] FALLBACK_HANDLERS = {
|
||||
"sun.net.www.protocol.jar.Handler" };
|
||||
private static final String[] FALLBACK_HANDLERS = { "sun.net.www.protocol.jar.Handler" };
|
||||
|
||||
private static final Method OPEN_CONNECTION_METHOD;
|
||||
|
||||
static {
|
||||
Method method = null;
|
||||
try {
|
||||
method = URLStreamHandler.class.getDeclaredMethod("openConnection",
|
||||
URL.class);
|
||||
method = URLStreamHandler.class.getDeclaredMethod("openConnection", URL.class);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
// Swallow and ignore
|
||||
@@ -92,8 +90,7 @@ public class Handler extends URLStreamHandler {
|
||||
|
||||
@Override
|
||||
protected URLConnection openConnection(URL url) throws IOException {
|
||||
if (this.jarFile != null
|
||||
&& url.toString().startsWith(this.jarFile.getUrl().toString())) {
|
||||
if (this.jarFile != null && url.toString().startsWith(this.jarFile.getUrl().toString())) {
|
||||
return JarURLConnection.get(url, this.jarFile);
|
||||
}
|
||||
try {
|
||||
@@ -104,8 +101,7 @@ public class Handler extends URLStreamHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private URLConnection openFallbackConnection(URL url, Exception reason)
|
||||
throws IOException {
|
||||
private URLConnection openFallbackConnection(URL url, Exception reason) throws IOException {
|
||||
try {
|
||||
return openConnection(getFallbackHandler(), url);
|
||||
}
|
||||
@@ -124,8 +120,7 @@ public class Handler extends URLStreamHandler {
|
||||
|
||||
private void log(boolean warning, String message, Exception cause) {
|
||||
try {
|
||||
Logger.getLogger(getClass().getName())
|
||||
.log((warning ? Level.WARNING : Level.FINEST), message, cause);
|
||||
Logger.getLogger(getClass().getName()).log((warning ? Level.WARNING : Level.FINEST), message, cause);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
if (warning) {
|
||||
@@ -151,11 +146,9 @@ public class Handler extends URLStreamHandler {
|
||||
throw new IllegalStateException("Unable to find fallback handler");
|
||||
}
|
||||
|
||||
private URLConnection openConnection(URLStreamHandler handler, URL url)
|
||||
throws Exception {
|
||||
private URLConnection openConnection(URLStreamHandler handler, URL url) throws Exception {
|
||||
if (OPEN_CONNECTION_METHOD == null) {
|
||||
throw new IllegalStateException(
|
||||
"Unable to invoke fallback open connection method");
|
||||
throw new IllegalStateException("Unable to invoke fallback open connection method");
|
||||
}
|
||||
OPEN_CONNECTION_METHOD.setAccessible(true);
|
||||
return (URLConnection) OPEN_CONNECTION_METHOD.invoke(handler, url);
|
||||
@@ -195,8 +188,7 @@ public class Handler extends URLStreamHandler {
|
||||
}
|
||||
int lastSlashIndex = file.lastIndexOf('/');
|
||||
if (lastSlashIndex == -1) {
|
||||
throw new IllegalArgumentException(
|
||||
"No / found in context URL's file '" + file + "'");
|
||||
throw new IllegalArgumentException("No / found in context URL's file '" + file + "'");
|
||||
}
|
||||
return file.substring(0, lastSlashIndex + 1) + spec;
|
||||
}
|
||||
@@ -204,8 +196,7 @@ public class Handler extends URLStreamHandler {
|
||||
private String trimToJarRoot(String file) {
|
||||
int lastSeparatorIndex = file.lastIndexOf(SEPARATOR);
|
||||
if (lastSeparatorIndex == -1) {
|
||||
throw new IllegalArgumentException(
|
||||
"No !/ found in context URL's file '" + file + "'");
|
||||
throw new IllegalArgumentException("No !/ found in context URL's file '" + file + "'");
|
||||
}
|
||||
return file.substring(0, lastSeparatorIndex);
|
||||
}
|
||||
@@ -218,8 +209,7 @@ public class Handler extends URLStreamHandler {
|
||||
query = path.substring(queryIndex + 1);
|
||||
path = path.substring(0, queryIndex);
|
||||
}
|
||||
setURL(context, JAR_PROTOCOL, null, -1, null, null, path, query,
|
||||
context.getRef());
|
||||
setURL(context, JAR_PROTOCOL, null, -1, null, null, path, query, context.getRef());
|
||||
}
|
||||
|
||||
private String normalize(String file) {
|
||||
@@ -238,8 +228,7 @@ public class Handler extends URLStreamHandler {
|
||||
while ((parentDirIndex = file.indexOf(PARENT_DIR)) >= 0) {
|
||||
int precedingSlashIndex = file.lastIndexOf('/', parentDirIndex - 1);
|
||||
if (precedingSlashIndex >= 0) {
|
||||
file = file.substring(0, precedingSlashIndex)
|
||||
+ file.substring(parentDirIndex + 3);
|
||||
file = file.substring(0, precedingSlashIndex) + file.substring(parentDirIndex + 3);
|
||||
}
|
||||
else {
|
||||
file = file.substring(parentDirIndex + 4);
|
||||
@@ -359,8 +348,7 @@ public class Handler extends URLStreamHandler {
|
||||
* which are then swallowed.
|
||||
* @param useFastConnectionExceptions if fast connection exceptions can be used.
|
||||
*/
|
||||
public static void setUseFastConnectionExceptions(
|
||||
boolean useFastConnectionExceptions) {
|
||||
public static void setUseFastConnectionExceptions(boolean useFastConnectionExceptions) {
|
||||
JarURLConnection.setUseFastExceptions(useFastConnectionExceptions);
|
||||
}
|
||||
|
||||
|
||||
@@ -55,8 +55,8 @@ class JarEntry extends java.util.jar.JarEntry implements FileHeader {
|
||||
|
||||
@Override
|
||||
public boolean hasName(String name, String suffix) {
|
||||
return getName().length() == name.length() + suffix.length()
|
||||
&& getName().startsWith(name) && getName().endsWith(suffix);
|
||||
return getName().length() == name.length() + suffix.length() && getName().startsWith(name)
|
||||
&& getName().endsWith(suffix);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -101,14 +101,13 @@ public class JarFile extends java.util.jar.JarFile {
|
||||
* @param type the type of the jar file
|
||||
* @throws IOException if the file cannot be read
|
||||
*/
|
||||
private JarFile(RandomAccessDataFile rootFile, String pathFromRoot,
|
||||
RandomAccessData data, JarFileType type) throws IOException {
|
||||
private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarFileType type)
|
||||
throws IOException {
|
||||
this(rootFile, pathFromRoot, data, null, type);
|
||||
}
|
||||
|
||||
private JarFile(RandomAccessDataFile rootFile, String pathFromRoot,
|
||||
RandomAccessData data, JarEntryFilter filter, JarFileType type)
|
||||
throws IOException {
|
||||
private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarEntryFilter filter,
|
||||
JarFileType type) throws IOException {
|
||||
super(rootFile.getFile());
|
||||
this.rootFile = rootFile;
|
||||
this.pathFromRoot = pathFromRoot;
|
||||
@@ -123,16 +122,13 @@ public class JarFile extends java.util.jar.JarFile {
|
||||
return new CentralDirectoryVisitor() {
|
||||
|
||||
@Override
|
||||
public void visitStart(CentralDirectoryEndRecord endRecord,
|
||||
RandomAccessData centralDirectoryData) {
|
||||
public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFileHeader(CentralDirectoryFileHeader fileHeader,
|
||||
int dataOffset) {
|
||||
public void visitFileHeader(CentralDirectoryFileHeader fileHeader, int dataOffset) {
|
||||
AsciiBytes name = fileHeader.getName();
|
||||
if (name.startsWith(META_INF)
|
||||
&& name.endsWith(SIGNATURE_FILE_EXTENSION)) {
|
||||
if (name.startsWith(META_INF) && name.endsWith(SIGNATURE_FILE_EXTENSION)) {
|
||||
JarFile.this.signed = true;
|
||||
}
|
||||
}
|
||||
@@ -160,8 +156,7 @@ public class JarFile extends java.util.jar.JarFile {
|
||||
manifest = new JarFile(this.getRootJarFile()).getManifest();
|
||||
}
|
||||
else {
|
||||
InputStream inputStream = getInputStream(MANIFEST_NAME,
|
||||
ResourceAccess.ONCE);
|
||||
InputStream inputStream = getInputStream(MANIFEST_NAME, ResourceAccess.ONCE);
|
||||
if (inputStream == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -214,8 +209,7 @@ public class JarFile extends java.util.jar.JarFile {
|
||||
return getInputStream(ze, ResourceAccess.PER_READ);
|
||||
}
|
||||
|
||||
public InputStream getInputStream(ZipEntry ze, ResourceAccess access)
|
||||
throws IOException {
|
||||
public InputStream getInputStream(ZipEntry ze, ResourceAccess access) throws IOException {
|
||||
if (ze instanceof JarEntry) {
|
||||
return this.entries.getInputStream((JarEntry) ze, access);
|
||||
}
|
||||
@@ -232,8 +226,7 @@ public class JarFile extends java.util.jar.JarFile {
|
||||
* @return a {@link JarFile} for the entry
|
||||
* @throws IOException if the nested jar file cannot be read
|
||||
*/
|
||||
public synchronized JarFile getNestedJarFile(final ZipEntry entry)
|
||||
throws IOException {
|
||||
public synchronized JarFile getNestedJarFile(final ZipEntry entry) throws IOException {
|
||||
return getNestedJarFile((JarEntry) entry);
|
||||
}
|
||||
|
||||
@@ -248,8 +241,7 @@ public class JarFile extends java.util.jar.JarFile {
|
||||
return createJarFileFromEntry(entry);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IOException(
|
||||
"Unable to open nested jar file '" + entry.getName() + "'", ex);
|
||||
throw new IOException("Unable to open nested jar file '" + entry.getName() + "'", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,21 +266,20 @@ public class JarFile extends java.util.jar.JarFile {
|
||||
|
||||
};
|
||||
return new JarFile(this.rootFile,
|
||||
this.pathFromRoot + "!/"
|
||||
+ entry.getName().substring(0, sourceName.length() - 1),
|
||||
this.data, filter, JarFileType.NESTED_DIRECTORY);
|
||||
this.pathFromRoot + "!/" + entry.getName().substring(0, sourceName.length() - 1), this.data, filter,
|
||||
JarFileType.NESTED_DIRECTORY);
|
||||
}
|
||||
|
||||
private JarFile createJarFileFromFileEntry(JarEntry entry) throws IOException {
|
||||
if (entry.getMethod() != ZipEntry.STORED) {
|
||||
throw new IllegalStateException("Unable to open nested entry '"
|
||||
+ entry.getName() + "'. It has been compressed and nested "
|
||||
+ "jar files must be stored without compression. Please check the "
|
||||
+ "mechanism used to create your executable jar file");
|
||||
throw new IllegalStateException(
|
||||
"Unable to open nested entry '" + entry.getName() + "'. It has been compressed and nested "
|
||||
+ "jar files must be stored without compression. Please check the "
|
||||
+ "mechanism used to create your executable jar file");
|
||||
}
|
||||
RandomAccessData entryData = this.entries.getEntryData(entry.getName());
|
||||
return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName(),
|
||||
entryData, JarFileType.NESTED_JAR);
|
||||
return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName(), entryData,
|
||||
JarFileType.NESTED_JAR);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -336,8 +327,7 @@ public class JarFile extends java.util.jar.JarFile {
|
||||
// Fallback to JarInputStream to obtain certificates, not fast but hopefully not
|
||||
// happening that often.
|
||||
try {
|
||||
JarInputStream inputStream = new JarInputStream(
|
||||
getData().getInputStream(ResourceAccess.ONCE));
|
||||
JarInputStream inputStream = new JarInputStream(getData().getInputStream(ResourceAccess.ONCE));
|
||||
try {
|
||||
java.util.jar.JarEntry certEntry = inputStream.getNextJarEntry();
|
||||
while (certEntry != null) {
|
||||
@@ -382,8 +372,8 @@ public class JarFile extends java.util.jar.JarFile {
|
||||
*/
|
||||
public static void registerUrlProtocolHandler() {
|
||||
String handlers = System.getProperty(PROTOCOL_HANDLER, "");
|
||||
System.setProperty(PROTOCOL_HANDLER, ("".equals(handlers) ? HANDLERS_PACKAGE
|
||||
: handlers + "|" + HANDLERS_PACKAGE));
|
||||
System.setProperty(PROTOCOL_HANDLER,
|
||||
("".equals(handlers) ? HANDLERS_PACKAGE : handlers + "|" + HANDLERS_PACKAGE));
|
||||
resetCachedUrlHandlers();
|
||||
}
|
||||
|
||||
|
||||
@@ -70,8 +70,7 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> {
|
||||
.synchronizedMap(new LinkedHashMap<Integer, FileHeader>(16, 0.75f, true) {
|
||||
|
||||
@Override
|
||||
protected boolean removeEldestEntry(
|
||||
Map.Entry<Integer, FileHeader> eldest) {
|
||||
protected boolean removeEldestEntry(Map.Entry<Integer, FileHeader> eldest) {
|
||||
if (JarFileEntries.this.jarFile.isSigned()) {
|
||||
return false;
|
||||
}
|
||||
@@ -86,8 +85,7 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitStart(CentralDirectoryEndRecord endRecord,
|
||||
RandomAccessData centralDirectoryData) {
|
||||
public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) {
|
||||
int maxSize = endRecord.getNumberOfRecords();
|
||||
this.centralDirectoryData = centralDirectoryData;
|
||||
this.hashCodes = new int[maxSize];
|
||||
@@ -103,8 +101,7 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> {
|
||||
}
|
||||
}
|
||||
|
||||
private void add(AsciiBytes name, CentralDirectoryFileHeader fileHeader,
|
||||
int dataOffset) {
|
||||
private void add(AsciiBytes name, CentralDirectoryFileHeader fileHeader, int dataOffset) {
|
||||
this.hashCodes[this.size] = name.hashCode();
|
||||
this.centralDirectoryOffsets[this.size] = dataOffset;
|
||||
this.positions[this.size] = this.size;
|
||||
@@ -178,14 +175,12 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> {
|
||||
return getEntry(name, JarEntry.class, true);
|
||||
}
|
||||
|
||||
public InputStream getInputStream(String name, ResourceAccess access)
|
||||
throws IOException {
|
||||
public InputStream getInputStream(String name, ResourceAccess access) throws IOException {
|
||||
FileHeader entry = getEntry(name, FileHeader.class, false);
|
||||
return getInputStream(entry, access);
|
||||
}
|
||||
|
||||
public InputStream getInputStream(FileHeader entry, ResourceAccess access)
|
||||
throws IOException {
|
||||
public InputStream getInputStream(FileHeader entry, ResourceAccess access) throws IOException {
|
||||
if (entry == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -209,16 +204,14 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> {
|
||||
// local directory to the central directory. We need to re-read
|
||||
// here to skip them
|
||||
RandomAccessData data = this.jarFile.getData();
|
||||
byte[] localHeader = Bytes.get(
|
||||
data.getSubsection(entry.getLocalHeaderOffset(), LOCAL_FILE_HEADER_SIZE));
|
||||
byte[] localHeader = Bytes.get(data.getSubsection(entry.getLocalHeaderOffset(), LOCAL_FILE_HEADER_SIZE));
|
||||
long nameLength = Bytes.littleEndianValue(localHeader, 26, 2);
|
||||
long extraLength = Bytes.littleEndianValue(localHeader, 28, 2);
|
||||
return data.getSubsection(entry.getLocalHeaderOffset() + LOCAL_FILE_HEADER_SIZE
|
||||
+ nameLength + extraLength, entry.getCompressedSize());
|
||||
return data.getSubsection(entry.getLocalHeaderOffset() + LOCAL_FILE_HEADER_SIZE + nameLength + extraLength,
|
||||
entry.getCompressedSize());
|
||||
}
|
||||
|
||||
private <T extends FileHeader> T getEntry(String name, Class<T> type,
|
||||
boolean cacheEntry) {
|
||||
private <T extends FileHeader> T getEntry(String name, Class<T> type, boolean cacheEntry) {
|
||||
int hashCode = AsciiBytes.hashCode(name);
|
||||
T entry = getEntry(hashCode, name, NO_SUFFIX, type, cacheEntry);
|
||||
if (entry == null) {
|
||||
@@ -228,8 +221,8 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> {
|
||||
return entry;
|
||||
}
|
||||
|
||||
private <T extends FileHeader> T getEntry(int hashCode, String name, String suffix,
|
||||
Class<T> type, boolean cacheEntry) {
|
||||
private <T extends FileHeader> T getEntry(int hashCode, String name, String suffix, Class<T> type,
|
||||
boolean cacheEntry) {
|
||||
int index = getFirstIndex(hashCode);
|
||||
while (index >= 0 && index < this.size && this.hashCodes[index] == hashCode) {
|
||||
T entry = getEntry(index, type, cacheEntry);
|
||||
@@ -242,16 +235,12 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable<JarEntry> {
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T extends FileHeader> T getEntry(int index, Class<T> type,
|
||||
boolean cacheEntry) {
|
||||
private <T extends FileHeader> T getEntry(int index, Class<T> type, boolean cacheEntry) {
|
||||
try {
|
||||
FileHeader cached = this.entriesCache.get(index);
|
||||
FileHeader entry = (cached != null) ? cached
|
||||
: CentralDirectoryFileHeader.fromRandomAccessData(
|
||||
this.centralDirectoryData,
|
||||
this.centralDirectoryOffsets[index], this.filter);
|
||||
if (CentralDirectoryFileHeader.class.equals(entry.getClass())
|
||||
&& type.equals(JarEntry.class)) {
|
||||
FileHeader entry = (cached != null) ? cached : CentralDirectoryFileHeader
|
||||
.fromRandomAccessData(this.centralDirectoryData, this.centralDirectoryOffsets[index], this.filter);
|
||||
if (CentralDirectoryFileHeader.class.equals(entry.getClass()) && type.equals(JarEntry.class)) {
|
||||
entry = new JarEntry(this.jarFile, (CentralDirectoryFileHeader) entry);
|
||||
}
|
||||
if (cacheEntry && cached != entry) {
|
||||
|
||||
@@ -72,8 +72,7 @@ final class JarURLConnection extends java.net.JarURLConnection {
|
||||
|
||||
private static final String READ_ACTION = "read";
|
||||
|
||||
private static final JarURLConnection NOT_FOUND_CONNECTION = JarURLConnection
|
||||
.notFound();
|
||||
private static final JarURLConnection NOT_FOUND_CONNECTION = JarURLConnection.notFound();
|
||||
|
||||
private final JarFile jarFile;
|
||||
|
||||
@@ -85,8 +84,7 @@ final class JarURLConnection extends java.net.JarURLConnection {
|
||||
|
||||
private JarEntry jarEntry;
|
||||
|
||||
private JarURLConnection(URL url, JarFile jarFile, JarEntryName jarEntryName)
|
||||
throws IOException {
|
||||
private JarURLConnection(URL url, JarFile jarFile, JarEntryName jarEntryName) throws IOException {
|
||||
// What we pass to super is ultimately ignored
|
||||
super(EMPTY_JAR_URL);
|
||||
this.url = url;
|
||||
@@ -163,8 +161,7 @@ final class JarURLConnection extends java.net.JarURLConnection {
|
||||
if (this.jarFile == null) {
|
||||
throw FILE_NOT_FOUND_EXCEPTION;
|
||||
}
|
||||
if (this.jarEntryName.isEmpty()
|
||||
&& this.jarFile.getType() == JarFile.JarFileType.DIRECT) {
|
||||
if (this.jarEntryName.isEmpty() && this.jarFile.getType() == JarFile.JarFileType.DIRECT) {
|
||||
throw new IOException("no entry name specified");
|
||||
}
|
||||
connect();
|
||||
@@ -177,13 +174,11 @@ final class JarURLConnection extends java.net.JarURLConnection {
|
||||
return inputStream;
|
||||
}
|
||||
|
||||
private void throwFileNotFound(Object entry, JarFile jarFile)
|
||||
throws FileNotFoundException {
|
||||
private void throwFileNotFound(Object entry, JarFile jarFile) throws FileNotFoundException {
|
||||
if (Boolean.TRUE.equals(useFastExceptions.get())) {
|
||||
throw FILE_NOT_FOUND_EXCEPTION;
|
||||
}
|
||||
throw new FileNotFoundException(
|
||||
"JAR entry " + entry + " not found in " + jarFile.getName());
|
||||
throw new FileNotFoundException("JAR entry " + entry + " not found in " + jarFile.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -229,8 +224,7 @@ final class JarURLConnection extends java.net.JarURLConnection {
|
||||
throw FILE_NOT_FOUND_EXCEPTION;
|
||||
}
|
||||
if (this.permission == null) {
|
||||
this.permission = new FilePermission(
|
||||
this.jarFile.getRootJarFile().getFile().getPath(), READ_ACTION);
|
||||
this.permission = new FilePermission(this.jarFile.getRootJarFile().getFile().getPath(), READ_ACTION);
|
||||
}
|
||||
return this.permission;
|
||||
}
|
||||
@@ -272,8 +266,7 @@ final class JarURLConnection extends java.net.JarURLConnection {
|
||||
}
|
||||
JarEntryName jarEntryName = JarEntryName.get(spec, index);
|
||||
if (Boolean.TRUE.equals(useFastExceptions.get())) {
|
||||
if (!jarEntryName.isEmpty()
|
||||
&& !jarFile.containsEntry(jarEntryName.toString())) {
|
||||
if (!jarEntryName.isEmpty() && !jarFile.containsEntry(jarEntryName.toString())) {
|
||||
return NOT_FOUND_CONNECTION;
|
||||
}
|
||||
}
|
||||
@@ -299,8 +292,7 @@ final class JarURLConnection extends java.net.JarURLConnection {
|
||||
}
|
||||
}
|
||||
|
||||
private static JarURLConnection notFound(JarFile jarFile, JarEntryName jarEntryName)
|
||||
throws IOException {
|
||||
private static JarURLConnection notFound(JarFile jarFile, JarEntryName jarEntryName) throws IOException {
|
||||
if (Boolean.TRUE.equals(useFastExceptions.get())) {
|
||||
return NOT_FOUND_CONNECTION;
|
||||
}
|
||||
@@ -336,8 +328,7 @@ final class JarURLConnection extends java.net.JarURLConnection {
|
||||
int c = source.charAt(i);
|
||||
if (c > 127) {
|
||||
try {
|
||||
String encoded = URLEncoder.encode(String.valueOf((char) c),
|
||||
"UTF-8");
|
||||
String encoded = URLEncoder.encode(String.valueOf((char) c), "UTF-8");
|
||||
write(encoded, outputStream);
|
||||
}
|
||||
catch (UnsupportedEncodingException ex) {
|
||||
@@ -348,8 +339,7 @@ final class JarURLConnection extends java.net.JarURLConnection {
|
||||
if (c == '%') {
|
||||
if ((i + 2) >= length) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid encoded sequence \"" + source.substring(i)
|
||||
+ "\"");
|
||||
"Invalid encoded sequence \"" + source.substring(i) + "\"");
|
||||
}
|
||||
c = decodeEscapeSequence(source, i);
|
||||
i += 2;
|
||||
@@ -363,8 +353,7 @@ final class JarURLConnection extends java.net.JarURLConnection {
|
||||
int hi = Character.digit(source.charAt(i + 1), 16);
|
||||
int lo = Character.digit(source.charAt(i + 2), 16);
|
||||
if (hi == -1 || lo == -1) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid encoded sequence \"" + source.substring(i) + "\"");
|
||||
throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\"");
|
||||
}
|
||||
return ((char) ((hi << 4) + lo));
|
||||
}
|
||||
|
||||
@@ -87,8 +87,8 @@ public abstract class SystemPropertyUtils {
|
||||
return parseStringValue(properties, text, text, new HashSet<String>());
|
||||
}
|
||||
|
||||
private static String parseStringValue(Properties properties, String value,
|
||||
String current, Set<String> visitedPlaceholders) {
|
||||
private static String parseStringValue(Properties properties, String value, String current,
|
||||
Set<String> visitedPlaceholders) {
|
||||
|
||||
StringBuilder buf = new StringBuilder(current);
|
||||
|
||||
@@ -96,29 +96,24 @@ public abstract class SystemPropertyUtils {
|
||||
while (startIndex != -1) {
|
||||
int endIndex = findPlaceholderEndIndex(buf, startIndex);
|
||||
if (endIndex != -1) {
|
||||
String placeholder = buf
|
||||
.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
|
||||
String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
|
||||
String originalPlaceholder = placeholder;
|
||||
if (!visitedPlaceholders.add(originalPlaceholder)) {
|
||||
throw new IllegalArgumentException("Circular placeholder reference '"
|
||||
+ originalPlaceholder + "' in property definitions");
|
||||
throw new IllegalArgumentException(
|
||||
"Circular placeholder reference '" + originalPlaceholder + "' in property definitions");
|
||||
}
|
||||
// Recursive invocation, parsing placeholders contained in the
|
||||
// placeholder
|
||||
// key.
|
||||
placeholder = parseStringValue(properties, value, placeholder,
|
||||
visitedPlaceholders);
|
||||
placeholder = parseStringValue(properties, value, placeholder, visitedPlaceholders);
|
||||
// Now obtain the value for the fully resolved key...
|
||||
String propVal = resolvePlaceholder(properties, value, placeholder);
|
||||
if (propVal == null && VALUE_SEPARATOR != null) {
|
||||
int separatorIndex = placeholder.indexOf(VALUE_SEPARATOR);
|
||||
if (separatorIndex != -1) {
|
||||
String actualPlaceholder = placeholder.substring(0,
|
||||
separatorIndex);
|
||||
String defaultValue = placeholder
|
||||
.substring(separatorIndex + VALUE_SEPARATOR.length());
|
||||
propVal = resolvePlaceholder(properties, value,
|
||||
actualPlaceholder);
|
||||
String actualPlaceholder = placeholder.substring(0, separatorIndex);
|
||||
String defaultValue = placeholder.substring(separatorIndex + VALUE_SEPARATOR.length());
|
||||
propVal = resolvePlaceholder(properties, value, actualPlaceholder);
|
||||
if (propVal == null) {
|
||||
propVal = defaultValue;
|
||||
}
|
||||
@@ -127,17 +122,13 @@ public abstract class SystemPropertyUtils {
|
||||
if (propVal != null) {
|
||||
// Recursive invocation, parsing placeholders contained in the
|
||||
// previously resolved placeholder value.
|
||||
propVal = parseStringValue(properties, value, propVal,
|
||||
visitedPlaceholders);
|
||||
buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(),
|
||||
propVal);
|
||||
startIndex = buf.indexOf(PLACEHOLDER_PREFIX,
|
||||
startIndex + propVal.length());
|
||||
propVal = parseStringValue(properties, value, propVal, visitedPlaceholders);
|
||||
buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal);
|
||||
startIndex = buf.indexOf(PLACEHOLDER_PREFIX, startIndex + propVal.length());
|
||||
}
|
||||
else {
|
||||
// Proceed with unprocessed value.
|
||||
startIndex = buf.indexOf(PLACEHOLDER_PREFIX,
|
||||
endIndex + PLACEHOLDER_SUFFIX.length());
|
||||
startIndex = buf.indexOf(PLACEHOLDER_PREFIX, endIndex + PLACEHOLDER_SUFFIX.length());
|
||||
}
|
||||
visitedPlaceholders.remove(originalPlaceholder);
|
||||
}
|
||||
@@ -149,8 +140,7 @@ public abstract class SystemPropertyUtils {
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
private static String resolvePlaceholder(Properties properties, String text,
|
||||
String placeholderName) {
|
||||
private static String resolvePlaceholder(Properties properties, String text, String placeholderName) {
|
||||
String propVal = getProperty(placeholderName, null, text);
|
||||
if (propVal != null) {
|
||||
return propVal;
|
||||
@@ -189,8 +179,7 @@ public abstract class SystemPropertyUtils {
|
||||
}
|
||||
if (propVal == null) {
|
||||
// Try uppercase with underscores as well.
|
||||
propVal = System
|
||||
.getenv(key.toUpperCase(Locale.ENGLISH).replace('.', '_'));
|
||||
propVal = System.getenv(key.toUpperCase(Locale.ENGLISH).replace('.', '_'));
|
||||
}
|
||||
if (propVal != null) {
|
||||
return propVal;
|
||||
@@ -227,8 +216,7 @@ public abstract class SystemPropertyUtils {
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static boolean substringMatch(CharSequence str, int index,
|
||||
CharSequence substring) {
|
||||
private static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
|
||||
for (int j = 0; j < substring.length(); j++) {
|
||||
int i = index + j;
|
||||
if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {
|
||||
|
||||
@@ -50,8 +50,7 @@ public class AbstractExecutableArchiveLauncherTests {
|
||||
|
||||
protected File createJarArchive(String name, String entryPrefix) throws IOException {
|
||||
File archive = this.temp.newFile(name);
|
||||
JarOutputStream jarOutputStream = new JarOutputStream(
|
||||
new FileOutputStream(archive));
|
||||
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(archive));
|
||||
jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/"));
|
||||
jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/classes/"));
|
||||
jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/lib/"));
|
||||
@@ -80,8 +79,7 @@ public class AbstractExecutableArchiveLauncherTests {
|
||||
entryFile.mkdirs();
|
||||
}
|
||||
else {
|
||||
FileCopyUtils.copy(jarFile.getInputStream(entry),
|
||||
new FileOutputStream(entryFile));
|
||||
FileCopyUtils.copy(jarFile.getInputStream(entry), new FileOutputStream(entryFile));
|
||||
}
|
||||
}
|
||||
jarFile.close();
|
||||
|
||||
@@ -36,28 +36,22 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
public class JarLauncherTests extends AbstractExecutableArchiveLauncherTests {
|
||||
|
||||
@Test
|
||||
public void explodedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath()
|
||||
throws Exception {
|
||||
public void explodedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception {
|
||||
File explodedRoot = explode(createJarArchive("archive.jar", "BOOT-INF"));
|
||||
JarLauncher launcher = new JarLauncher(new ExplodedArchive(explodedRoot, true));
|
||||
List<Archive> archives = launcher.getClassPathArchives();
|
||||
assertThat(archives).hasSize(2);
|
||||
assertThat(getUrls(archives)).containsOnly(
|
||||
new File(explodedRoot, "BOOT-INF/classes").toURI().toURL(),
|
||||
new URL("jar:"
|
||||
+ new File(explodedRoot, "BOOT-INF/lib/foo.jar").toURI().toURL()
|
||||
+ "!/"));
|
||||
assertThat(getUrls(archives)).containsOnly(new File(explodedRoot, "BOOT-INF/classes").toURI().toURL(),
|
||||
new URL("jar:" + new File(explodedRoot, "BOOT-INF/lib/foo.jar").toURI().toURL() + "!/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void archivedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath()
|
||||
throws Exception {
|
||||
public void archivedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception {
|
||||
File jarRoot = createJarArchive("archive.jar", "BOOT-INF");
|
||||
JarLauncher launcher = new JarLauncher(new JarFileArchive(jarRoot));
|
||||
List<Archive> archives = launcher.getClassPathArchives();
|
||||
assertThat(archives).hasSize(2);
|
||||
assertThat(getUrls(archives)).containsOnly(
|
||||
new URL("jar:" + jarRoot.toURI().toURL() + "!/BOOT-INF/classes!/"),
|
||||
assertThat(getUrls(archives)).containsOnly(new URL("jar:" + jarRoot.toURI().toURL() + "!/BOOT-INF/classes!/"),
|
||||
new URL("jar:" + jarRoot.toURI().toURL() + "!/BOOT-INF/lib/foo.jar!/"));
|
||||
}
|
||||
|
||||
|
||||
@@ -43,33 +43,28 @@ public class LaunchedURLClassLoaderTests {
|
||||
@Test
|
||||
public void resolveResourceFromArchive() throws Exception {
|
||||
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
|
||||
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") },
|
||||
getClass().getClassLoader());
|
||||
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader());
|
||||
assertThat(loader.getResource("demo/Application.java")).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveResourcesFromArchive() throws Exception {
|
||||
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
|
||||
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") },
|
||||
getClass().getClassLoader());
|
||||
assertThat(loader.getResources("demo/Application.java").hasMoreElements())
|
||||
.isTrue();
|
||||
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader());
|
||||
assertThat(loader.getResources("demo/Application.java").hasMoreElements()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveRootPathFromArchive() throws Exception {
|
||||
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
|
||||
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") },
|
||||
getClass().getClassLoader());
|
||||
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader());
|
||||
assertThat(loader.getResource("")).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveRootResourcesFromArchive() throws Exception {
|
||||
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
|
||||
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") },
|
||||
getClass().getClassLoader());
|
||||
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader());
|
||||
assertThat(loader.getResources("").hasMoreElements()).isTrue();
|
||||
}
|
||||
|
||||
@@ -79,8 +74,7 @@ public class LaunchedURLClassLoaderTests {
|
||||
TestJarCreator.createTestJar(file);
|
||||
JarFile jarFile = new JarFile(file);
|
||||
URL url = jarFile.getUrl();
|
||||
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url },
|
||||
null);
|
||||
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, null);
|
||||
URL resource = loader.getResource("nested.jar!/3.dat");
|
||||
assertThat(resource.toString()).isEqualTo(url + "nested.jar!/3.dat");
|
||||
assertThat(resource.openConnection().getInputStream().read()).isEqualTo(3);
|
||||
@@ -92,8 +86,7 @@ public class LaunchedURLClassLoaderTests {
|
||||
TestJarCreator.createTestJar(file);
|
||||
JarFile jarFile = new JarFile(file);
|
||||
URL url = jarFile.getUrl();
|
||||
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url },
|
||||
null);
|
||||
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, null);
|
||||
try {
|
||||
Thread.currentThread().interrupt();
|
||||
URL resource = loader.getResource("nested.jar!/3.dat");
|
||||
|
||||
@@ -67,8 +67,7 @@ public class PropertiesLauncherTests {
|
||||
public void setup() throws IOException {
|
||||
this.contextClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
MockitoAnnotations.initMocks(this);
|
||||
System.setProperty("loader.home",
|
||||
new File("src/test/resources").getAbsolutePath());
|
||||
System.setProperty("loader.home", new File("src/test/resources").getAbsolutePath());
|
||||
}
|
||||
|
||||
@After
|
||||
@@ -87,16 +86,14 @@ public class PropertiesLauncherTests {
|
||||
public void testDefaultHome() {
|
||||
System.clearProperty("loader.home");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(launcher.getHomeDirectory())
|
||||
.isEqualTo(new File(System.getProperty("user.dir")));
|
||||
assertThat(launcher.getHomeDirectory()).isEqualTo(new File(System.getProperty("user.dir")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAlternateHome() throws Exception {
|
||||
System.setProperty("loader.home", "src/test/resources/home");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(launcher.getHomeDirectory())
|
||||
.isEqualTo(new File(System.getProperty("loader.home")));
|
||||
assertThat(launcher.getHomeDirectory()).isEqualTo(new File(System.getProperty("loader.home")));
|
||||
assertThat(launcher.getMainClass()).isEqualTo("demo.HomeApplication");
|
||||
}
|
||||
|
||||
@@ -105,8 +102,7 @@ public class PropertiesLauncherTests {
|
||||
System.setProperty("loader.home", "src/test/resources/nonexistent");
|
||||
this.expected.expectMessage("Invalid source folder");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(launcher.getHomeDirectory())
|
||||
.isNotEqualTo(new File(System.getProperty("loader.home")));
|
||||
assertThat(launcher.getHomeDirectory()).isNotEqualTo(new File(System.getProperty("loader.home")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -121,8 +117,7 @@ public class PropertiesLauncherTests {
|
||||
System.setProperty("loader.config.name", "foo");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(launcher.getMainClass()).isEqualTo("my.Application");
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
|
||||
.isEqualTo("[etc/]");
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[etc/]");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -136,16 +131,14 @@ public class PropertiesLauncherTests {
|
||||
public void testUserSpecifiedDotPath() throws Exception {
|
||||
System.setProperty("loader.path", ".");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
|
||||
.isEqualTo("[.]");
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[.]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUserSpecifiedSlashPath() throws Exception {
|
||||
System.setProperty("loader.path", "jars/");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
|
||||
.isEqualTo("[jars/]");
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/]");
|
||||
List<Archive> archives = launcher.getClassPathArchives();
|
||||
assertThat(archives).areExactly(1, endingWith("app.jar!/"));
|
||||
}
|
||||
@@ -155,8 +148,7 @@ public class PropertiesLauncherTests {
|
||||
System.setProperty("loader.path", "jars/*");
|
||||
System.setProperty("loader.main", "demo.Application");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
|
||||
.isEqualTo("[jars/]");
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/]");
|
||||
launcher.launch(new String[0]);
|
||||
waitFor("Hello World");
|
||||
}
|
||||
@@ -166,16 +158,14 @@ public class PropertiesLauncherTests {
|
||||
System.setProperty("loader.path", "jars/app.jar");
|
||||
System.setProperty("loader.main", "demo.Application");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
|
||||
.isEqualTo("[jars/app.jar]");
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/app.jar]");
|
||||
launcher.launch(new String[0]);
|
||||
waitFor("Hello World");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUserSpecifiedRootOfJarPath() throws Exception {
|
||||
System.setProperty("loader.path",
|
||||
"jar:file:./src/test/resources/nested-jars/app.jar!/");
|
||||
System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
|
||||
.isEqualTo("[jar:file:./src/test/resources/nested-jars/app.jar!/]");
|
||||
@@ -195,8 +185,7 @@ public class PropertiesLauncherTests {
|
||||
|
||||
@Test
|
||||
public void testUserSpecifiedRootOfJarPathWithDotAndJarPrefix() throws Exception {
|
||||
System.setProperty("loader.path",
|
||||
"jar:file:./src/test/resources/nested-jars/app.jar!/./");
|
||||
System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/./");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
List<Archive> archives = launcher.getClassPathArchives();
|
||||
assertThat(archives).areExactly(1, endingWith("foo.jar!/"));
|
||||
@@ -213,8 +202,7 @@ public class PropertiesLauncherTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUserSpecifiedDirectoryContainingJarFileWithNestedArchives()
|
||||
throws Exception {
|
||||
public void testUserSpecifiedDirectoryContainingJarFileWithNestedArchives() throws Exception {
|
||||
System.setProperty("loader.path", "nested-jars");
|
||||
System.setProperty("loader.main", "demo.Application");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
@@ -227,8 +215,7 @@ public class PropertiesLauncherTests {
|
||||
System.setProperty("loader.path", "./jars/app.jar");
|
||||
System.setProperty("loader.main", "demo.Application");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
|
||||
.isEqualTo("[jars/app.jar]");
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/app.jar]");
|
||||
launcher.launch(new String[0]);
|
||||
waitFor("Hello World");
|
||||
}
|
||||
@@ -238,8 +225,7 @@ public class PropertiesLauncherTests {
|
||||
System.setProperty("loader.path", "jars/app.jar");
|
||||
System.setProperty("loader.classLoader", URLClassLoader.class.getName());
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
|
||||
.isEqualTo("[jars/app.jar]");
|
||||
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/app.jar]");
|
||||
launcher.launch(new String[0]);
|
||||
waitFor("Hello World");
|
||||
}
|
||||
@@ -308,25 +294,21 @@ public class PropertiesLauncherTests {
|
||||
public void testArgsEnhanced() throws Exception {
|
||||
System.setProperty("loader.args", "foo");
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat(Arrays.asList(launcher.getArgs("bar")).toString())
|
||||
.isEqualTo("[foo, bar]");
|
||||
assertThat(Arrays.asList(launcher.getArgs("bar")).toString()).isEqualTo("[foo, bar]");
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void testLoadPathCustomizedUsingManifest() throws Exception {
|
||||
System.setProperty("loader.home",
|
||||
this.temporaryFolder.getRoot().getAbsolutePath());
|
||||
System.setProperty("loader.home", this.temporaryFolder.getRoot().getAbsolutePath());
|
||||
Manifest manifest = new Manifest();
|
||||
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
|
||||
manifest.getMainAttributes().putValue("Loader-Path", "/foo.jar, /bar");
|
||||
File manifestFile = new File(this.temporaryFolder.getRoot(),
|
||||
"META-INF/MANIFEST.MF");
|
||||
File manifestFile = new File(this.temporaryFolder.getRoot(), "META-INF/MANIFEST.MF");
|
||||
manifestFile.getParentFile().mkdirs();
|
||||
manifest.write(new FileOutputStream(manifestFile));
|
||||
PropertiesLauncher launcher = new PropertiesLauncher();
|
||||
assertThat((List<String>) ReflectionTestUtils.getField(launcher, "paths"))
|
||||
.containsExactly("/foo.jar", "/bar/");
|
||||
assertThat((List<String>) ReflectionTestUtils.getField(launcher, "paths")).containsExactly("/foo.jar", "/bar/");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -59,8 +59,8 @@ public abstract class TestJarCreator {
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeNestedEntry(String name, boolean unpackNested,
|
||||
JarOutputStream jarOutputStream) throws Exception, IOException {
|
||||
private static void writeNestedEntry(String name, boolean unpackNested, JarOutputStream jarOutputStream)
|
||||
throws Exception, IOException {
|
||||
JarEntry nestedEntry = new JarEntry(name);
|
||||
byte[] nestedJarData = getNestedJarData();
|
||||
nestedEntry.setSize(nestedJarData.length);
|
||||
@@ -89,8 +89,7 @@ public abstract class TestJarCreator {
|
||||
return byteArrayOutputStream.toByteArray();
|
||||
}
|
||||
|
||||
private static void writeManifest(JarOutputStream jarOutputStream, String name)
|
||||
throws Exception {
|
||||
private static void writeManifest(JarOutputStream jarOutputStream, String name) throws Exception {
|
||||
writeDirEntry(jarOutputStream, "META-INF/");
|
||||
Manifest manifest = new Manifest();
|
||||
manifest.getMainAttributes().putValue("Built-By", name);
|
||||
@@ -100,14 +99,12 @@ public abstract class TestJarCreator {
|
||||
jarOutputStream.closeEntry();
|
||||
}
|
||||
|
||||
private static void writeDirEntry(JarOutputStream jarOutputStream, String name)
|
||||
throws IOException {
|
||||
private static void writeDirEntry(JarOutputStream jarOutputStream, String name) throws IOException {
|
||||
jarOutputStream.putNextEntry(new JarEntry(name));
|
||||
jarOutputStream.closeEntry();
|
||||
}
|
||||
|
||||
private static void writeEntry(JarOutputStream jarOutputStream, String name, int data)
|
||||
throws IOException {
|
||||
private static void writeEntry(JarOutputStream jarOutputStream, String name, int data) throws IOException {
|
||||
jarOutputStream.putNextEntry(new JarEntry(name));
|
||||
jarOutputStream.write(new byte[] { (byte) data });
|
||||
jarOutputStream.closeEntry();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user