Merge branch '2.0.x' into 2.1.x

Closes gh-17078
This commit is contained in:
Andy Wilkinson
2019-06-07 10:50:34 +01:00
2691 changed files with 27746 additions and 46049 deletions

View File

@@ -79,8 +79,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
static final String DEPRECATED_CONFIGURATION_PROPERTY_ANNOTATION = "org.springframework.boot."
+ "context.properties.DeprecatedConfigurationProperty";
static final String ENDPOINT_ANNOTATION = "org.springframework.boot.actuate."
+ "endpoint.annotation.Endpoint";
static final String ENDPOINT_ANNOTATION = "org.springframework.boot.actuate." + "endpoint.annotation.Endpoint";
static final String READ_OPERATION_ANNOTATION = "org.springframework.boot.actuate."
+ "endpoint.annotation.ReadOperation";
@@ -143,25 +142,21 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
super.init(env);
this.typeUtils = new TypeUtils(env);
this.metadataStore = new MetadataStore(env);
this.metadataCollector = new MetadataCollector(env,
this.metadataStore.readMetadata());
this.metadataCollector = new MetadataCollector(env, this.metadataStore.readMetadata());
try {
this.fieldValuesParser = new JavaCompilerFieldValuesParser(env);
}
catch (Throwable ex) {
this.fieldValuesParser = FieldValuesParser.NONE;
logWarning("Field value processing of @ConfigurationProperty meta-data is "
+ "not supported");
logWarning("Field value processing of @ConfigurationProperty meta-data is " + "not supported");
}
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
this.metadataCollector.processing(roundEnv);
Elements elementUtils = this.processingEnv.getElementUtils();
TypeElement annotationType = elementUtils
.getTypeElement(configurationPropertiesAnnotation());
TypeElement annotationType = elementUtils.getTypeElement(configurationPropertiesAnnotation());
if (annotationType != null) { // Is @ConfigurationProperties available
for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) {
processElement(element);
@@ -169,8 +164,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
}
TypeElement endpointType = elementUtils.getTypeElement(endpointAnnotation());
if (endpointType != null) { // Is @Endpoint available
getElementsAnnotatedOrMetaAnnotatedWith(roundEnv, endpointType)
.forEach(this::processEndpoint);
getElementsAnnotatedOrMetaAnnotatedWith(roundEnv, endpointType).forEach(this::processEndpoint);
}
if (roundEnv.processingOver()) {
try {
@@ -183,8 +177,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
return false;
}
private Map<Element, List<Element>> getElementsAnnotatedOrMetaAnnotatedWith(
RoundEnvironment roundEnv, TypeElement annotation) {
private Map<Element, List<Element>> getElementsAnnotatedOrMetaAnnotatedWith(RoundEnvironment roundEnv,
TypeElement annotation) {
DeclaredType annotationType = (DeclaredType) annotation.asType();
Map<Element, List<Element>> result = new LinkedHashMap<>();
for (Element element : roundEnv.getRootElements()) {
@@ -199,11 +193,10 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
return result;
}
private boolean collectElementsAnnotatedOrMetaAnnotatedWith(
DeclaredType annotationType, LinkedList<Element> stack) {
private boolean collectElementsAnnotatedOrMetaAnnotatedWith(DeclaredType annotationType,
LinkedList<Element> stack) {
Element element = stack.peekLast();
for (AnnotationMirror annotation : this.processingEnv.getElementUtils()
.getAllAnnotationMirrors(element)) {
for (AnnotationMirror annotation : this.processingEnv.getElementUtils().getAllAnnotationMirrors(element)) {
Element annotationElement = annotation.getAnnotationType().asElement();
if (!stack.contains(annotationElement)) {
stack.addLast(annotationElement);
@@ -220,8 +213,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
private void processElement(Element element) {
try {
AnnotationMirror annotation = getAnnotation(element,
configurationPropertiesAnnotation());
AnnotationMirror annotation = getAnnotation(element, configurationPropertiesAnnotation());
if (annotation != null) {
String prefix = getPrefix(annotation);
if (element instanceof TypeElement) {
@@ -233,8 +225,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
}
}
catch (Exception ex) {
throw new IllegalStateException(
"Error processing configuration meta-data on " + element, ex);
throw new IllegalStateException("Error processing configuration meta-data on " + element, ex);
}
}
@@ -245,20 +236,14 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
}
private void processExecutableElement(String prefix, ExecutableElement element) {
if (element.getModifiers().contains(Modifier.PUBLIC)
&& (TypeKind.VOID != element.getReturnType().getKind())) {
Element returns = this.processingEnv.getTypeUtils()
.asElement(element.getReturnType());
if (element.getModifiers().contains(Modifier.PUBLIC) && (TypeKind.VOID != element.getReturnType().getKind())) {
Element returns = this.processingEnv.getTypeUtils().asElement(element.getReturnType());
if (returns instanceof TypeElement) {
ItemMetadata group = ItemMetadata.newGroup(prefix,
this.typeUtils.getQualifiedName(returns),
this.typeUtils.getQualifiedName(element.getEnclosingElement()),
element.toString());
ItemMetadata group = ItemMetadata.newGroup(prefix, this.typeUtils.getQualifiedName(returns),
this.typeUtils.getQualifiedName(element.getEnclosingElement()), element.toString());
if (this.metadataCollector.hasSimilarGroup(group)) {
this.processingEnv.getMessager().printMessage(Kind.ERROR,
"Duplicate `@ConfigurationProperties` definition for prefix '"
+ prefix + "'",
element);
"Duplicate `@ConfigurationProperties` definition for prefix '" + prefix + "'", element);
}
else {
this.metadataCollector.add(group);
@@ -268,10 +253,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
}
}
private void processTypeElement(String prefix, TypeElement element,
ExecutableElement source) {
TypeElementMembers members = new TypeElementMembers(this.processingEnv,
this.fieldValuesParser, element);
private void processTypeElement(String prefix, TypeElement element, ExecutableElement source) {
TypeElementMembers members = new TypeElementMembers(this.processingEnv, this.fieldValuesParser, element);
Map<String, Object> fieldValues = members.getFieldValues();
processSimpleTypes(prefix, element, source, members, fieldValues);
processSimpleLombokTypes(prefix, element, source, members, fieldValues);
@@ -279,15 +262,13 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
processNestedLombokTypes(prefix, element, source, members);
}
private void processSimpleTypes(String prefix, TypeElement element,
ExecutableElement source, TypeElementMembers members,
Map<String, Object> fieldValues) {
private void processSimpleTypes(String prefix, TypeElement element, ExecutableElement source,
TypeElementMembers members, Map<String, Object> fieldValues) {
members.getPublicGetters().forEach((name, getter) -> {
TypeMirror returnType = getter.getReturnType();
ExecutableElement setter = members.getPublicSetter(name, returnType);
VariableElement field = members.getFields().get(name);
Element returnTypeElement = this.processingEnv.getTypeUtils()
.asElement(returnType);
Element returnTypeElement = this.processingEnv.getTypeUtils().asElement(returnType);
boolean isExcluded = this.typeExcludeFilter.isExcluded(returnType);
boolean isNested = isNested(returnTypeElement, field, element);
boolean isCollection = this.typeUtils.isCollectionOrMap(returnType);
@@ -296,18 +277,15 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
String sourceType = this.typeUtils.getQualifiedName(element);
String description = this.typeUtils.getJavaDoc(field);
Object defaultValue = fieldValues.get(name);
boolean deprecated = isDeprecated(getter) || isDeprecated(setter)
|| isDeprecated(source);
this.metadataCollector.add(ItemMetadata.newProperty(prefix, name,
dataType, sourceType, null, description, defaultValue,
deprecated ? getItemDeprecation(getter) : null));
boolean deprecated = isDeprecated(getter) || isDeprecated(setter) || isDeprecated(source);
this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, dataType, sourceType, null,
description, defaultValue, deprecated ? getItemDeprecation(getter) : null));
}
});
}
private ItemDeprecation getItemDeprecation(ExecutableElement getter) {
AnnotationMirror annotation = getAnnotation(getter,
deprecatedConfigurationPropertyAnnotation());
AnnotationMirror annotation = getAnnotation(getter, deprecatedConfigurationPropertyAnnotation());
String reason = null;
String replacement = null;
if (annotation != null) {
@@ -320,16 +298,14 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
return new ItemDeprecation(reason, replacement);
}
private void processSimpleLombokTypes(String prefix, TypeElement element,
ExecutableElement source, TypeElementMembers members,
Map<String, Object> fieldValues) {
private void processSimpleLombokTypes(String prefix, TypeElement element, ExecutableElement source,
TypeElementMembers members, Map<String, Object> fieldValues) {
members.getFields().forEach((name, field) -> {
if (!isLombokField(field, element)) {
return;
}
TypeMirror returnType = field.asType();
Element returnTypeElement = this.processingEnv.getTypeUtils()
.asElement(returnType);
Element returnTypeElement = this.processingEnv.getTypeUtils().asElement(returnType);
boolean isExcluded = this.typeExcludeFilter.isExcluded(returnType);
boolean isNested = isNested(returnTypeElement, field, element);
boolean isCollection = this.typeUtils.isCollectionOrMap(returnType);
@@ -340,29 +316,26 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
String description = this.typeUtils.getJavaDoc(field);
Object defaultValue = fieldValues.get(name);
boolean deprecated = isDeprecated(field) || isDeprecated(source);
this.metadataCollector.add(ItemMetadata.newProperty(prefix, name,
dataType, sourceType, null, description, defaultValue,
deprecated ? new ItemDeprecation() : null));
this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, dataType, sourceType, null,
description, defaultValue, deprecated ? new ItemDeprecation() : null));
}
});
}
private void processNestedTypes(String prefix, TypeElement element,
ExecutableElement source, TypeElementMembers members) {
private void processNestedTypes(String prefix, TypeElement element, ExecutableElement source,
TypeElementMembers members) {
members.getPublicGetters().forEach((name, getter) -> {
VariableElement field = members.getFields().get(name);
processNestedType(prefix, element, source, name, getter, field,
getter.getReturnType());
processNestedType(prefix, element, source, name, getter, field, getter.getReturnType());
});
}
private void processNestedLombokTypes(String prefix, TypeElement element,
ExecutableElement source, TypeElementMembers members) {
private void processNestedLombokTypes(String prefix, TypeElement element, ExecutableElement source,
TypeElementMembers members) {
members.getFields().forEach((name, field) -> {
if (isLombokField(field, element)) {
ExecutableElement getter = members.getPublicGetter(name, field.asType());
processNestedType(prefix, element, source, name, getter, field,
field.asType());
processNestedType(prefix, element, source, name, getter, field, field.asType());
}
});
}
@@ -372,8 +345,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
}
private boolean hasLombokSetter(VariableElement field, TypeElement element) {
return !field.getModifiers().contains(Modifier.FINAL)
&& hasLombokPublicAccessor(field, element, false);
return !field.getModifiers().contains(Modifier.FINAL) && hasLombokPublicAccessor(field, element, false);
}
/**
@@ -385,16 +357,13 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
* write accessor
* @return {@code true} if this field has a public accessor of the specified type
*/
private boolean hasLombokPublicAccessor(VariableElement field, TypeElement element,
boolean getter) {
String annotation = (getter ? LOMBOK_GETTER_ANNOTATION
: LOMBOK_SETTER_ANNOTATION);
private boolean hasLombokPublicAccessor(VariableElement field, TypeElement element, boolean getter) {
String annotation = (getter ? LOMBOK_GETTER_ANNOTATION : LOMBOK_SETTER_ANNOTATION);
AnnotationMirror lombokMethodAnnotationOnField = getAnnotation(field, annotation);
if (lombokMethodAnnotationOnField != null) {
return isAccessLevelPublic(lombokMethodAnnotationOnField);
}
AnnotationMirror lombokMethodAnnotationOnElement = getAnnotation(element,
annotation);
AnnotationMirror lombokMethodAnnotationOnElement = getAnnotation(element, annotation);
if (lombokMethodAnnotationOnElement != null) {
return isAccessLevelPublic(lombokMethodAnnotationOnElement);
}
@@ -407,19 +376,16 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
return (value == null || value.toString().equals(LOMBOK_ACCESS_LEVEL_PUBLIC));
}
private void processNestedType(String prefix, TypeElement element,
ExecutableElement source, String name, ExecutableElement getter,
VariableElement field, TypeMirror returnType) {
private void processNestedType(String prefix, TypeElement element, ExecutableElement source, String name,
ExecutableElement getter, VariableElement field, TypeMirror returnType) {
Element returnElement = this.processingEnv.getTypeUtils().asElement(returnType);
boolean isNested = isNested(returnElement, field, element);
AnnotationMirror annotation = getAnnotation(getter,
configurationPropertiesAnnotation());
AnnotationMirror annotation = getAnnotation(getter, configurationPropertiesAnnotation());
if (returnElement instanceof TypeElement && annotation == null && isNested) {
String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, name);
this.metadataCollector.add(ItemMetadata.newGroup(nestedPrefix,
this.typeUtils.getQualifiedName(returnElement),
this.typeUtils.getQualifiedName(element),
(getter != null) ? getter.toString() : null));
this.metadataCollector
.add(ItemMetadata.newGroup(nestedPrefix, this.typeUtils.getQualifiedName(returnElement),
this.typeUtils.getQualifiedName(element), (getter != null) ? getter.toString() : null));
processTypeElement(nestedPrefix, (TypeElement) returnElement, source);
}
}
@@ -433,8 +399,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
}
}
catch (Exception ex) {
throw new IllegalStateException(
"Error processing configuration meta-data on " + element, ex);
throw new IllegalStateException("Error processing configuration meta-data on " + element, ex);
}
}
@@ -444,27 +409,22 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
if (endpointId == null || "".equals(endpointId)) {
return; // Can't process that endpoint
}
String endpointKey = ItemMetadata.newItemMetadataPrefix("management.endpoint.",
endpointId);
String endpointKey = ItemMetadata.newItemMetadataPrefix("management.endpoint.", endpointId);
Boolean enabledByDefault = (Boolean) elementValues.get("enableByDefault");
String type = this.typeUtils.getQualifiedName(element);
this.metadataCollector.add(ItemMetadata.newGroup(endpointKey, type, type, null));
this.metadataCollector.add(ItemMetadata.newProperty(endpointKey, "enabled",
Boolean.class.getName(), type, null,
this.metadataCollector.add(ItemMetadata.newProperty(endpointKey, "enabled", Boolean.class.getName(), type, null,
String.format("Whether to enable the %s endpoint.", endpointId),
(enabledByDefault != null) ? enabledByDefault : true, null));
if (hasMainReadOperation(element)) {
this.metadataCollector.add(ItemMetadata.newProperty(endpointKey,
"cache.time-to-live", Duration.class.getName(), type, null,
"Maximum time that a response can be cached.", "0ms", null));
this.metadataCollector.add(ItemMetadata.newProperty(endpointKey, "cache.time-to-live",
Duration.class.getName(), type, null, "Maximum time that a response can be cached.", "0ms", null));
}
}
private boolean hasMainReadOperation(TypeElement element) {
for (ExecutableElement method : ElementFilter
.methodsIn(element.getEnclosedElements())) {
if (hasAnnotation(method, readOperationAnnotation())
&& (TypeKind.VOID != method.getReturnType().getKind())
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
if (hasAnnotation(method, readOperationAnnotation()) && (TypeKind.VOID != method.getReturnType().getKind())
&& hasNoOrOptionalParameters(method)) {
return true;
}
@@ -481,16 +441,14 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
return true;
}
private boolean isNested(Element returnType, VariableElement field,
TypeElement element) {
private boolean isNested(Element returnType, VariableElement field, TypeElement element) {
if (hasAnnotation(field, nestedConfigurationPropertyAnnotation())) {
return true;
}
if (isCyclePresent(returnType, element)) {
return false;
}
return (isParentTheSame(returnType, element))
&& returnType.getKind() != ElementKind.ENUM;
return (isParentTheSame(returnType, element)) && returnType.getKind() != ElementKind.ENUM;
}
private boolean isCyclePresent(Element returnType, Element element) {
@@ -562,8 +520,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
private Map<String, Object> getAnnotationElementValues(AnnotationMirror annotation) {
Map<String, Object> values = new LinkedHashMap<>();
annotation.getElementValues().forEach((name, value) -> values
.put(name.getSimpleName().toString(), value.getValue()));
annotation.getElementValues()
.forEach((name, value) -> values.put(name.getSimpleName().toString(), value.getValue()));
return values;
}
@@ -577,8 +535,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
return null;
}
private ConfigurationMetadata mergeAdditionalMetadata(
ConfigurationMetadata metadata) {
private ConfigurationMetadata mergeAdditionalMetadata(ConfigurationMetadata metadata) {
try {
ConfigurationMetadata merged = new ConfigurationMetadata(metadata);
merged.merge(this.metadataStore.readAdditionalMetadata());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,8 +65,7 @@ public class MetadataStore {
public void writeMetadata(ConfigurationMetadata metadata) throws IOException {
if (!metadata.getItems().isEmpty()) {
try (OutputStream outputStream = createMetadataResource()
.openOutputStream()) {
try (OutputStream outputStream = createMetadataResource().openOutputStream()) {
new JsonMarshaller().write(metadata, outputStream);
}
}
@@ -85,8 +84,7 @@ public class MetadataStore {
}
catch (Exception ex) {
throw new InvalidConfigurationMetadataException(
"Invalid additional meta-data in '" + METADATA_PATH + "': "
+ ex.getMessage(),
"Invalid additional meta-data in '" + METADATA_PATH + "': " + ex.getMessage(),
Diagnostic.Kind.ERROR);
}
finally {
@@ -95,30 +93,27 @@ public class MetadataStore {
}
private FileObject getMetadataResource() throws IOException {
return this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "",
METADATA_PATH);
return this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH);
}
private FileObject createMetadataResource() throws IOException {
return this.environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT,
"", METADATA_PATH);
return this.environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PATH);
}
private InputStream getAdditionalMetadataStream() throws IOException {
// Most build systems will have copied the file to the class output location
FileObject fileObject = this.environment.getFiler()
.getResource(StandardLocation.CLASS_OUTPUT, "", ADDITIONAL_METADATA_PATH);
FileObject fileObject = this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "",
ADDITIONAL_METADATA_PATH);
File file = locateAdditionalMetadataFile(new File(fileObject.toUri()));
return (file.exists() ? new FileInputStream(file)
: fileObject.toUri().toURL().openStream());
return (file.exists() ? new FileInputStream(file) : fileObject.toUri().toURL().openStream());
}
File locateAdditionalMetadataFile(File standardLocation) throws IOException {
if (standardLocation.exists()) {
return standardLocation;
}
String locations = this.environment.getOptions().get(
ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION);
String locations = this.environment.getOptions()
.get(ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION);
if (locations != null) {
for (String location : locations.split(",")) {
File candidate = new File(location, ADDITIONAL_METADATA_PATH);
@@ -127,22 +122,18 @@ public class MetadataStore {
}
}
}
return new File(locateGradleResourcesFolder(standardLocation),
ADDITIONAL_METADATA_PATH);
return new File(locateGradleResourcesFolder(standardLocation), ADDITIONAL_METADATA_PATH);
}
private File locateGradleResourcesFolder(File standardAdditionalMetadataLocation)
throws FileNotFoundException {
private File locateGradleResourcesFolder(File standardAdditionalMetadataLocation) throws FileNotFoundException {
String path = standardAdditionalMetadataLocation.getPath();
int index = path.lastIndexOf(CLASSES_FOLDER);
if (index < 0) {
throw new FileNotFoundException();
}
String buildFolderPath = path.substring(0, index);
File classOutputLocation = standardAdditionalMetadataLocation.getParentFile()
.getParentFile();
return new File(buildFolderPath,
RESOURCES_FOLDER + '/' + classOutputLocation.getName());
File classOutputLocation = standardAdditionalMetadataLocation.getParentFile().getParentFile();
return new File(buildFolderPath, RESOURCES_FOLDER + '/' + classOutputLocation.getName());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -60,8 +60,7 @@ class TypeElementMembers {
private final FieldValuesParser fieldValuesParser;
TypeElementMembers(ProcessingEnvironment env, FieldValuesParser fieldValuesParser,
TypeElement element) {
TypeElementMembers(ProcessingEnvironment env, FieldValuesParser fieldValuesParser, TypeElement element) {
this.env = env;
this.typeUtils = new TypeUtils(this.env);
this.fieldValuesParser = fieldValuesParser;
@@ -69,12 +68,10 @@ class TypeElementMembers {
}
private void process(TypeElement element) {
for (ExecutableElement method : ElementFilter
.methodsIn(element.getEnclosedElements())) {
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
processMethod(method);
}
for (VariableElement field : ElementFilter
.fieldsIn(element.getEnclosedElements())) {
for (VariableElement field : ElementFilter.fieldsIn(element.getEnclosedElements())) {
processField(field);
}
try {
@@ -89,8 +86,7 @@ class TypeElementMembers {
}
Element superType = this.env.getTypeUtils().asElement(element.getSuperclass());
if (superType != null && superType instanceof TypeElement
&& !OBJECT_CLASS_NAME.equals(superType.toString())) {
if (superType != null && superType instanceof TypeElement && !OBJECT_CLASS_NAME.equals(superType.toString())) {
process((TypeElement) superType);
}
}
@@ -103,8 +99,7 @@ class TypeElementMembers {
}
else if (isSetter(method)) {
String propertyName = getAccessorName(name);
List<ExecutableElement> matchingSetters = this.publicSetters
.get(propertyName);
List<ExecutableElement> matchingSetters = this.publicSetters.get(propertyName);
if (matchingSetters == null) {
matchingSetters = new ArrayList<>();
this.publicSetters.put(propertyName, matchingSetters);
@@ -119,13 +114,11 @@ class TypeElementMembers {
private boolean isPublic(ExecutableElement method) {
Set<Modifier> modifiers = method.getModifiers();
return modifiers.contains(Modifier.PUBLIC)
&& !modifiers.contains(Modifier.ABSTRACT)
return modifiers.contains(Modifier.PUBLIC) && !modifiers.contains(Modifier.ABSTRACT)
&& !modifiers.contains(Modifier.STATIC);
}
private ExecutableElement getMatchingSetter(List<ExecutableElement> candidates,
TypeMirror type) {
private ExecutableElement getMatchingSetter(List<ExecutableElement> candidates, TypeMirror type) {
for (ExecutableElement candidate : candidates) {
TypeMirror paramType = candidate.getParameters().get(0).asType();
if (this.env.getTypeUtils().isSameType(paramType, type)) {
@@ -137,27 +130,24 @@ class TypeElementMembers {
private boolean isGetter(ExecutableElement method) {
String name = method.getSimpleName().toString();
return ((name.startsWith("get") && name.length() > 3)
|| (name.startsWith("is") && name.length() > 2))
&& method.getParameters().isEmpty()
&& (TypeKind.VOID != method.getReturnType().getKind());
return ((name.startsWith("get") && name.length() > 3) || (name.startsWith("is") && name.length() > 2))
&& method.getParameters().isEmpty() && (TypeKind.VOID != method.getReturnType().getKind());
}
private boolean isSetter(ExecutableElement method) {
final String name = method.getSimpleName().toString();
return (name.startsWith("set") && name.length() > 3
&& method.getParameters().size() == 1 && isSetterReturnType(method));
return (name.startsWith("set") && name.length() > 3 && method.getParameters().size() == 1
&& isSetterReturnType(method));
}
private boolean isSetterReturnType(ExecutableElement method) {
TypeMirror returnType = method.getReturnType();
return (TypeKind.VOID == returnType.getKind() || this.env.getTypeUtils()
.isSameType(method.getEnclosingElement().asType(), returnType));
return (TypeKind.VOID == returnType.getKind()
|| this.env.getTypeUtils().isSameType(method.getEnclosingElement().asType(), returnType));
}
private String getAccessorName(String methodName) {
String name = methodName.startsWith("is") ? methodName.substring(2)
: methodName.substring(3);
String name = methodName.startsWith("is") ? methodName.substring(2) : methodName.substring(3);
name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
return name;
}
@@ -185,8 +175,7 @@ class TypeElementMembers {
return candidate;
}
TypeMirror alternative = this.typeUtils.getWrapperOrPrimitiveFor(type);
if (alternative != null
&& this.env.getTypeUtils().isSameType(returnType, alternative)) {
if (alternative != null && this.env.getTypeUtils().isSameType(returnType, alternative)) {
return candidate;
}
}

View File

@@ -70,8 +70,7 @@ class TypeUtils {
static {
Map<String, TypeKind> primitives = new HashMap<>();
PRIMITIVE_WRAPPERS.forEach(
(kind, wrapperClass) -> primitives.put(wrapperClass.getName(), kind));
PRIMITIVE_WRAPPERS.forEach((kind, wrapperClass) -> primitives.put(wrapperClass.getName(), kind));
WRAPPER_TO_PRIMITIVE = primitives;
}
@@ -95,12 +94,10 @@ class TypeUtils {
this.mapType = getDeclaredType(this.types, Map.class, 2);
}
private TypeMirror getDeclaredType(Types types, Class<?> typeClass,
int numberOfTypeArgs) {
private TypeMirror getDeclaredType(Types types, Class<?> typeClass, int numberOfTypeArgs) {
TypeMirror[] typeArgs = new TypeMirror[numberOfTypeArgs];
Arrays.setAll(typeArgs, (i) -> types.getWildcardType(null, null));
TypeElement typeElement = this.env.getElementUtils()
.getTypeElement(typeClass.getName());
TypeElement typeElement = this.env.getElementUtils().getTypeElement(typeClass.getName());
try {
return types.getDeclaredType(typeElement, typeArgs);
}
@@ -140,8 +137,7 @@ class TypeUtils {
}
public String getJavaDoc(Element element) {
String javadoc = (element != null)
? this.env.getElementUtils().getDocComment(element) : null;
String javadoc = (element != null) ? this.env.getElementUtils().getDocComment(element) : null;
if (javadoc != null) {
javadoc = NEW_LINE_PATTERN.matcher(javadoc).replaceAll("").trim();
}
@@ -151,8 +147,7 @@ class TypeUtils {
public TypeMirror getWrapperOrPrimitiveFor(TypeMirror typeMirror) {
Class<?> candidate = getWrapperFor(typeMirror);
if (candidate != null) {
return this.env.getElementUtils().getTypeElement(candidate.getName())
.asType();
return this.env.getElementUtils().getTypeElement(candidate.getName()).asType();
}
TypeKind primitiveKind = getPrimitiveFor(typeMirror);
if (primitiveKind != null) {
@@ -200,8 +195,7 @@ class TypeUtils {
}
}
catch (Exception ex) {
this.env.getMessager().printMessage(Kind.WARNING,
"Failed to generated type descriptor for " + type,
this.env.getMessager().printMessage(Kind.WARNING, "Failed to generated type descriptor for " + type,
this.types.asElement(type));
}
}
@@ -210,8 +204,7 @@ class TypeUtils {
* A visitor that extracts the fully qualified name of a type, including generic
* information.
*/
private static class TypeExtractor
extends SimpleTypeVisitor8<String, TypeDescriptor> {
private static class TypeExtractor extends SimpleTypeVisitor8<String, TypeDescriptor> {
private final Types types;
@@ -228,17 +221,15 @@ class TypeUtils {
}
StringBuilder name = new StringBuilder();
name.append(qualifiedName);
name.append("<").append(type.getTypeArguments().stream()
.map((t) -> visit(t, descriptor)).collect(Collectors.joining(",")))
name.append("<").append(
type.getTypeArguments().stream().map((t) -> visit(t, descriptor)).collect(Collectors.joining(",")))
.append(">");
return name.toString();
}
private String determineQualifiedName(DeclaredType type,
TypeElement enclosingElement) {
private String determineQualifiedName(DeclaredType type, TypeElement enclosingElement) {
if (enclosingElement != null) {
return getQualifiedName(enclosingElement) + "$"
+ type.asElement().getSimpleName();
return getQualifiedName(enclosingElement) + "$" + type.asElement().getSimpleName();
}
return getQualifiedName(type.asElement());
}
@@ -299,8 +290,7 @@ class TypeUtils {
if (element instanceof TypeElement) {
return ((TypeElement) element).getQualifiedName().toString();
}
throw new IllegalStateException(
"Could not extract qualified name from " + element);
throw new IllegalStateException("Could not extract qualified name from " + element);
}
private TypeElement getEnclosingTypeElement(TypeMirror type) {
@@ -332,8 +322,7 @@ class TypeUtils {
}
public TypeMirror resolveGeneric(String parameterName) {
return this.generics.entrySet().stream()
.filter((e) -> getParameterName(e.getKey()).equals(parameterName))
return this.generics.entrySet().stream().filter((e) -> getParameterName(e.getKey()).equals(parameterName))
.findFirst().map(Entry::getValue).orElse(null);
}
@@ -341,8 +330,7 @@ class TypeUtils {
if (variable instanceof TypeVariable) {
TypeVariable typeVariable = (TypeVariable) variable;
if (this.generics.keySet().stream()
.noneMatch((candidate) -> getParameterName(candidate)
.equals(getParameterName(typeVariable)))) {
.noneMatch((candidate) -> getParameterName(candidate).equals(getParameterName(typeVariable)))) {
this.generics.put(typeVariable, resolution);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,20 +31,15 @@ class ExpressionTree extends ReflectionWrapper {
private final Class<?> literalTreeType = findClass("com.sun.source.tree.LiteralTree");
private final Method literalValueMethod = findMethod(this.literalTreeType,
"getValue");
private final Method literalValueMethod = findMethod(this.literalTreeType, "getValue");
private final Class<?> methodInvocationTreeType = findClass(
"com.sun.source.tree.MethodInvocationTree");
private final Class<?> methodInvocationTreeType = findClass("com.sun.source.tree.MethodInvocationTree");
private final Method methodInvocationArgumentsMethod = findMethod(
this.methodInvocationTreeType, "getArguments");
private final Method methodInvocationArgumentsMethod = findMethod(this.methodInvocationTreeType, "getArguments");
private final Class<?> newArrayTreeType = findClass(
"com.sun.source.tree.NewArrayTree");
private final Class<?> newArrayTreeType = findClass("com.sun.source.tree.NewArrayTree");
private final Method arrayValueMethod = findMethod(this.newArrayTreeType,
"getInitializers");
private final Method arrayValueMethod = findMethod(this.newArrayTreeType, "getInitializers");
ExpressionTree(Object instance) {
super("com.sun.source.tree.ExpressionTree", instance);
@@ -63,8 +58,7 @@ class ExpressionTree extends ReflectionWrapper {
public Object getFactoryValue() throws Exception {
if (this.methodInvocationTreeType.isAssignableFrom(getInstance().getClass())) {
List<?> arguments = (List<?>) this.methodInvocationArgumentsMethod
.invoke(getInstance());
List<?> arguments = (List<?>) this.methodInvocationArgumentsMethod.invoke(getInstance());
if (arguments.size() == 1) {
return new ExpressionTree(arguments.get(0)).getLiteralValue();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -155,8 +155,7 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser {
return defaultValue;
}
private Object getValue(ExpressionTree expression, Object defaultValue)
throws Exception {
private Object getValue(ExpressionTree expression, Object defaultValue) throws Exception {
Object literalValue = expression.getLiteralValue();
if (literalValue != null) {
return literalValue;
@@ -187,21 +186,19 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser {
}
private Object getFactoryValue(ExpressionTree expression, Object factoryValue) {
Object durationValue = getFactoryValue(expression, factoryValue, DURATION_OF,
DURATION_SUFFIX);
Object durationValue = getFactoryValue(expression, factoryValue, DURATION_OF, DURATION_SUFFIX);
if (durationValue != null) {
return durationValue;
}
Object dataSizeValue = getFactoryValue(expression, factoryValue, DATA_SIZE_OF,
DATA_SIZE_SUFFIX);
Object dataSizeValue = getFactoryValue(expression, factoryValue, DATA_SIZE_OF, DATA_SIZE_SUFFIX);
if (dataSizeValue != null) {
return dataSizeValue;
}
return factoryValue;
}
private Object getFactoryValue(ExpressionTree expression, Object factoryValue,
String prefix, Map<String, String> suffixMapping) {
private Object getFactoryValue(ExpressionTree expression, Object factoryValue, String prefix,
Map<String, String> suffixMapping) {
Object instance = expression.getInstance();
if (instance != null && instance.toString().startsWith(prefix)) {
String type = instance.toString();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -62,8 +62,7 @@ class ReflectionWrapper {
}
}
protected static Method findMethod(Class<?> type, String name,
Class<?>... parameterTypes) {
protected static Method findMethod(Class<?> type, String name, Class<?>... parameterTypes) {
try {
return type.getMethod(name, parameterTypes);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,22 +30,17 @@ class Tree extends ReflectionWrapper {
private final Class<?> treeVisitorType = findClass("com.sun.source.tree.TreeVisitor");
private final Method acceptMethod = findMethod("accept", this.treeVisitorType,
Object.class);
private final Method acceptMethod = findMethod("accept", this.treeVisitorType, Object.class);
private final Method getClassTreeMembers = findMethod(
findClass("com.sun.source.tree.ClassTree"), "getMembers");
private final Method getClassTreeMembers = findMethod(findClass("com.sun.source.tree.ClassTree"), "getMembers");
Tree(Object instance) {
super("com.sun.source.tree.Tree", instance);
}
public void accept(TreeVisitor visitor) throws Exception {
this.acceptMethod.invoke(getInstance(),
Proxy.newProxyInstance(getInstance().getClass().getClassLoader(),
new Class<?>[] { this.treeVisitorType },
new TreeVisitorInvocationHandler(visitor)),
0);
this.acceptMethod.invoke(getInstance(), Proxy.newProxyInstance(getInstance().getClass().getClassLoader(),
new Class<?>[] { this.treeVisitorType }, new TreeVisitorInvocationHandler(visitor)), 0);
}
/**
@@ -61,15 +56,12 @@ class Tree extends ReflectionWrapper {
@Override
@SuppressWarnings("rawtypes")
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("visitClass") && (Integer) args[1] == 0) {
Iterable members = (Iterable) Tree.this.getClassTreeMembers
.invoke(args[0]);
Iterable members = (Iterable) Tree.this.getClassTreeMembers.invoke(args[0]);
for (Object member : members) {
if (member != null) {
Tree.this.acceptMethod.invoke(member, proxy,
((Integer) args[1]) + 1);
Tree.this.acceptMethod.invoke(member, proxy, ((Integer) args[1]) + 1);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -152,8 +152,7 @@ public class ConfigurationMetadata {
candidates = new ArrayList<>(candidates);
candidates.removeIf((itemMetadata) -> !itemMetadata.hasSameType(metadata));
if (candidates.size() > 1 && metadata.getType() != null) {
candidates.removeIf(
(itemMetadata) -> !metadata.getType().equals(itemMetadata.getType()));
candidates.removeIf((itemMetadata) -> !metadata.getType().equals(itemMetadata.getType()));
}
if (candidates.size() == 1) {
return candidates.get(0);
@@ -187,8 +186,7 @@ public class ConfigurationMetadata {
if (SEPARATORS.contains(current)) {
dashed.append("-");
}
else if (Character.isUpperCase(current) && previous != null
&& !SEPARATORS.contains(previous)) {
else if (Character.isUpperCase(current) && previous != null && !SEPARATORS.contains(previous)) {
dashed.append("-").append(current);
}
else {
@@ -213,8 +211,7 @@ public class ConfigurationMetadata {
public String toString() {
StringBuilder result = new StringBuilder();
result.append(String.format("items: %n"));
this.items.values().forEach((itemMetadata) -> result.append("\t")
.append(String.format("%s%n", itemMetadata)));
this.items.values().forEach((itemMetadata) -> result.append("\t").append(String.format("%s%n", itemMetadata)));
return result.toString();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,8 +45,7 @@ public class ItemHint implements Comparable<ItemHint> {
public ItemHint(String name, List<ValueHint> values, List<ValueProvider> providers) {
this.name = toCanonicalName(name);
this.values = (values != null) ? new ArrayList<>(values) : new ArrayList<>();
this.providers = (providers != null) ? new ArrayList<>(providers)
: new ArrayList<>();
this.providers = (providers != null) ? new ArrayList<>(providers) : new ArrayList<>();
}
private String toCanonicalName(String name) {
@@ -82,8 +81,7 @@ public class ItemHint implements Comparable<ItemHint> {
@Override
public String toString() {
return "ItemHint{" + "name='" + this.name + "', values=" + this.values
+ ", providers=" + this.providers + '}';
return "ItemHint{" + "name='" + this.name + "', values=" + this.values + ", providers=" + this.providers + '}';
}
/**
@@ -110,8 +108,7 @@ public class ItemHint implements Comparable<ItemHint> {
@Override
public String toString() {
return "ValueHint{" + "value=" + this.value + ", description='"
+ this.description + '\'' + '}';
return "ValueHint{" + "value=" + this.value + ", description='" + this.description + '\'' + '}';
}
}
@@ -140,8 +137,7 @@ public class ItemHint implements Comparable<ItemHint> {
@Override
public String toString() {
return "ValueProvider{" + "name='" + this.name + "', parameters="
+ this.parameters + '}';
return "ValueProvider{" + "name='" + this.name + "', parameters=" + this.parameters + '}';
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,9 +44,8 @@ public final class ItemMetadata implements Comparable<ItemMetadata> {
private ItemDeprecation deprecation;
ItemMetadata(ItemType itemType, String prefix, String name, String type,
String sourceType, String sourceMethod, String description,
Object defaultValue, ItemDeprecation deprecation) {
ItemMetadata(ItemType itemType, String prefix, String name, String type, String sourceType, String sourceMethod,
String description, Object defaultValue, ItemDeprecation deprecation) {
this.itemType = itemType;
this.name = buildName(prefix, name);
this.type = type;
@@ -197,8 +196,7 @@ public final class ItemMetadata implements Comparable<ItemMetadata> {
return string.toString();
}
protected void buildToStringProperty(StringBuilder string, String property,
Object value) {
protected void buildToStringProperty(StringBuilder string, String property, Object value) {
if (value != null) {
string.append(" ").append(property).append(":").append(value);
}
@@ -209,22 +207,18 @@ public final class ItemMetadata implements Comparable<ItemMetadata> {
return getName().compareTo(o.getName());
}
public static ItemMetadata newGroup(String name, String type, String sourceType,
String sourceMethod) {
return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType,
sourceMethod, null, null, null);
public static ItemMetadata newGroup(String name, String type, String sourceType, String sourceMethod) {
return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, sourceMethod, null, null, null);
}
public static ItemMetadata newProperty(String prefix, String name, String type,
String sourceType, String sourceMethod, String description,
Object defaultValue, ItemDeprecation deprecation) {
return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType,
sourceMethod, description, defaultValue, deprecation);
public static ItemMetadata newProperty(String prefix, String name, String type, String sourceType,
String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) {
return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, sourceMethod, description,
defaultValue, deprecation);
}
public static String newItemMetadataPrefix(String prefix, String suffix) {
return prefix.toLowerCase(Locale.ENGLISH)
+ ConfigurationMetadata.toDashedCase(suffix);
return prefix.toLowerCase(Locale.ENGLISH) + ConfigurationMetadata.toDashedCase(suffix);
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,12 +37,10 @@ class JsonConverter {
private static final ItemMetadataComparator ITEM_COMPARATOR = new ItemMetadataComparator();
public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType)
throws Exception {
public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) throws Exception {
JSONArray jsonArray = new JSONArray();
List<ItemMetadata> items = metadata.getItems().stream()
.filter((item) -> item.isOfItemType(itemType)).sorted(ITEM_COMPARATOR)
.collect(Collectors.toList());
List<ItemMetadata> items = metadata.getItems().stream().filter((item) -> item.isOfItemType(itemType))
.sorted(ITEM_COMPARATOR).collect(Collectors.toList());
for (ItemMetadata item : items) {
if (item.isOfItemType(itemType)) {
jsonArray.put(toJsonObject(item));
@@ -123,8 +121,7 @@ class JsonConverter {
return providers;
}
private JSONObject getItemHintProvider(ItemHint.ValueProvider provider)
throws Exception {
private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) throws Exception {
JSONObject result = new JSONObject();
result.put("name", provider.getName());
if (provider.getParameters() != null && !provider.getParameters().isEmpty()) {
@@ -137,8 +134,7 @@ class JsonConverter {
return result;
}
private void putIfPresent(JSONObject jsonObject, String name, Object value)
throws Exception {
private void putIfPresent(JSONObject jsonObject, String name, Object value) throws Exception {
if (value != null) {
jsonObject.put(name, value);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,8 +42,7 @@ public class JsonMarshaller {
private static final int BUFFER_SIZE = 4098;
public void write(ConfigurationMetadata metadata, OutputStream outputStream)
throws IOException {
public void write(ConfigurationMetadata metadata, OutputStream outputStream) throws IOException {
try {
JSONObject object = new JSONObject();
JsonConverter converter = new JsonConverter();
@@ -75,8 +74,7 @@ public class JsonMarshaller {
JSONArray properties = object.optJSONArray("properties");
if (properties != null) {
for (int i = 0; i < properties.length(); i++) {
metadata.add(toItemMetadata((JSONObject) properties.get(i),
ItemType.PROPERTY));
metadata.add(toItemMetadata((JSONObject) properties.get(i), ItemType.PROPERTY));
}
}
JSONArray hints = object.optJSONArray("hints");
@@ -88,8 +86,7 @@ public class JsonMarshaller {
return metadata;
}
private ItemMetadata toItemMetadata(JSONObject object, ItemType itemType)
throws Exception {
private ItemMetadata toItemMetadata(JSONObject object, ItemType itemType) throws Exception {
String name = object.getString("name");
String type = object.optString("type", null);
String description = object.optString("description", null);
@@ -97,8 +94,8 @@ public class JsonMarshaller {
String sourceMethod = object.optString("sourceMethod", null);
Object defaultValue = readItemValue(object.opt("defaultValue"));
ItemDeprecation deprecation = toItemDeprecation(object);
return new ItemMetadata(itemType, name, null, type, sourceType, sourceMethod,
description, defaultValue, deprecation);
return new ItemMetadata(itemType, name, null, type, sourceType, sourceMethod, description, defaultValue,
deprecation);
}
private ItemDeprecation toItemDeprecation(JSONObject object) throws Exception {
@@ -107,8 +104,7 @@ public class JsonMarshaller {
ItemDeprecation deprecation = new ItemDeprecation();
deprecation.setLevel(deprecationJsonObject.optString("level", null));
deprecation.setReason(deprecationJsonObject.optString("reason", null));
deprecation
.setReplacement(deprecationJsonObject.optString("replacement", null));
deprecation.setReplacement(deprecationJsonObject.optString("replacement", null));
return deprecation;
}
return object.optBoolean("deprecated") ? new ItemDeprecation() : null;
@@ -167,8 +163,7 @@ public class JsonMarshaller {
private String toString(InputStream inputStream) throws IOException {
StringBuilder out = new StringBuilder();
InputStreamReader reader = new InputStreamReader(inputStream,
StandardCharsets.UTF_8);
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
char[] buffer = new char[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = reader.read(buffer)) != -1) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -50,13 +50,11 @@ public class MetadataStoreTests {
File classesLocation = new File(app, "target/classes");
File metaInf = new File(classesLocation, "META-INF");
metaInf.mkdirs();
File additionalMetadata = new File(metaInf,
"additional-spring-configuration-metadata.json");
File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json");
additionalMetadata.createNewFile();
assertThat(
this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation,
"META-INF/additional-spring-configuration-metadata.json")))
.isEqualTo(additionalMetadata);
assertThat(this.metadataStore.locateAdditionalMetadataFile(
new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json")))
.isEqualTo(additionalMetadata);
}
@Test
@@ -66,13 +64,11 @@ public class MetadataStoreTests {
File resourcesLocation = new File(app, "build/resources/main");
File metaInf = new File(resourcesLocation, "META-INF");
metaInf.mkdirs();
File additionalMetadata = new File(metaInf,
"additional-spring-configuration-metadata.json");
File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json");
additionalMetadata.createNewFile();
assertThat(
this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation,
"META-INF/additional-spring-configuration-metadata.json")))
.isEqualTo(additionalMetadata);
assertThat(this.metadataStore.locateAdditionalMetadataFile(
new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json")))
.isEqualTo(additionalMetadata);
}
@Test
@@ -82,13 +78,11 @@ public class MetadataStoreTests {
File resourcesLocation = new File(app, "build/resources/main");
File metaInf = new File(resourcesLocation, "META-INF");
metaInf.mkdirs();
File additionalMetadata = new File(metaInf,
"additional-spring-configuration-metadata.json");
File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json");
additionalMetadata.createNewFile();
assertThat(
this.metadataStore.locateAdditionalMetadataFile(new File(classesLocation,
"META-INF/additional-spring-configuration-metadata.json")))
.isEqualTo(additionalMetadata);
assertThat(this.metadataStore.locateAdditionalMetadataFile(
new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json")))
.isEqualTo(additionalMetadata);
}
@Test
@@ -97,14 +91,12 @@ public class MetadataStoreTests {
File location = new File(app, "src/main/resources");
File metaInf = new File(location, "META-INF");
metaInf.mkdirs();
File additionalMetadata = new File(metaInf,
"additional-spring-configuration-metadata.json");
File additionalMetadata = new File(metaInf, "additional-spring-configuration-metadata.json");
additionalMetadata.createNewFile();
given(this.environment.getOptions()).willReturn(Collections.singletonMap(
ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION,
location.getAbsolutePath()));
assertThat(this.metadataStore.locateAdditionalMetadataFile(new File(app, "foo")))
.isEqualTo(additionalMetadata);
given(this.environment.getOptions()).willReturn(
Collections.singletonMap(ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION,
location.getAbsolutePath()));
assertThat(this.metadataStore.locateAdditionalMetadataFile(new File(app, "foo"))).isEqualTo(additionalMetadata);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,8 +37,7 @@ import org.springframework.boot.configurationprocessor.metadata.JsonMarshaller;
*/
@SupportedAnnotationTypes({ "*" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class TestConfigurationMetadataAnnotationProcessor
extends ConfigurationMetadataAnnotationProcessor {
public class TestConfigurationMetadataAnnotationProcessor extends ConfigurationMetadataAnnotationProcessor {
static final String CONFIGURATION_PROPERTIES_ANNOTATION = "org.springframework.boot.configurationsample.ConfigurationProperties";
@@ -87,11 +86,9 @@ public class TestConfigurationMetadataAnnotationProcessor
protected ConfigurationMetadata writeMetaData() throws Exception {
super.writeMetaData();
try {
File metadataFile = new File(this.outputLocation,
"META-INF/spring-configuration-metadata.json");
File metadataFile = new File(this.outputLocation, "META-INF/spring-configuration-metadata.json");
if (metadataFile.isFile()) {
this.metadata = new JsonMarshaller()
.read(new FileInputStream(metadataFile));
this.metadata = new JsonMarshaller().read(new FileInputStream(metadataFile));
}
else {
this.metadata = new ConfigurationMetadata();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -63,8 +63,7 @@ public class TestProject {
private Set<File> sourceFiles = new LinkedHashSet<>();
public TestProject(TemporaryFolder tempFolder, Class<?>... classes)
throws IOException {
public TestProject(TemporaryFolder tempFolder, Class<?>... classes) throws IOException {
this.sourceFolder = tempFolder.newFolder();
this.compiler = new TestCompiler(tempFolder) {
@Override
@@ -133,15 +132,12 @@ public class TestProject {
* @param snippetStream the snippet stream
* @throws Exception if the source cannot be added
*/
public void addSourceCode(Class<?> target, InputStream snippetStream)
throws Exception {
public void addSourceCode(Class<?> target, InputStream snippetStream) throws Exception {
File targetFile = getSourceFile(target);
String contents = getContents(targetFile);
int insertAt = contents.lastIndexOf('}');
String additionalSource = FileCopyUtils
.copyToString(new InputStreamReader(snippetStream));
contents = contents.substring(0, insertAt) + additionalSource
+ contents.substring(insertAt);
String additionalSource = FileCopyUtils.copyToString(new InputStreamReader(snippetStream));
contents = contents.substring(0, insertAt) + additionalSource + contents.substring(insertAt);
putContents(targetFile, contents);
}

View File

@@ -56,16 +56,12 @@ public class TypeUtilsTests {
public void resolveTypeDescriptorOnConcreteClass() throws IOException {
process(SimpleGenericProperties.class, (roundEnv, typeUtils) -> {
for (Element rootElement : roundEnv.getRootElements()) {
TypeDescriptor typeDescriptor = typeUtils
.resolveTypeDescriptor((TypeElement) rootElement);
assertThat(typeDescriptor.getGenerics().keySet().stream()
.map(Object::toString)).containsOnly("A", "B", "C");
assertThat(typeDescriptor.resolveGeneric("A"))
.hasToString(String.class.getName());
assertThat(typeDescriptor.resolveGeneric("B"))
.hasToString(Integer.class.getName());
assertThat(typeDescriptor.resolveGeneric("C"))
.hasToString(Duration.class.getName());
TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor((TypeElement) rootElement);
assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B",
"C");
assertThat(typeDescriptor.resolveGeneric("A")).hasToString(String.class.getName());
assertThat(typeDescriptor.resolveGeneric("B")).hasToString(Integer.class.getName());
assertThat(typeDescriptor.resolveGeneric("C")).hasToString(Duration.class.getName());
}
});
}
@@ -74,14 +70,11 @@ public class TypeUtilsTests {
public void resolveTypeDescriptorOnIntermediateClass() throws IOException {
process(AbstractIntermediateGenericProperties.class, (roundEnv, typeUtils) -> {
for (Element rootElement : roundEnv.getRootElements()) {
TypeDescriptor typeDescriptor = typeUtils
.resolveTypeDescriptor((TypeElement) rootElement);
assertThat(typeDescriptor.getGenerics().keySet().stream()
.map(Object::toString)).containsOnly("A", "B", "C");
assertThat(typeDescriptor.resolveGeneric("A"))
.hasToString(String.class.getName());
assertThat(typeDescriptor.resolveGeneric("B"))
.hasToString(Integer.class.getName());
TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor((TypeElement) rootElement);
assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B",
"C");
assertThat(typeDescriptor.resolveGeneric("A")).hasToString(String.class.getName());
assertThat(typeDescriptor.resolveGeneric("B")).hasToString(Integer.class.getName());
assertThat(typeDescriptor.resolveGeneric("C")).hasToString("C");
}
});
@@ -91,17 +84,15 @@ public class TypeUtilsTests {
public void resolveTypeDescriptorWithOnlyGenerics() throws IOException {
process(AbstractGenericProperties.class, (roundEnv, typeUtils) -> {
for (Element rootElement : roundEnv.getRootElements()) {
TypeDescriptor typeDescriptor = typeUtils
.resolveTypeDescriptor((TypeElement) rootElement);
assertThat(typeDescriptor.getGenerics().keySet().stream()
.map(Object::toString)).containsOnly("A", "B", "C");
TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor((TypeElement) rootElement);
assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B",
"C");
}
});
}
private void process(Class<?> target,
BiConsumer<RoundEnvironment, TypeUtils> consumer) throws IOException {
private void process(Class<?> target, BiConsumer<RoundEnvironment, TypeUtils> consumer) throws IOException {
TestProcessor processor = new TestProcessor(consumer);
TestCompiler compiler = new TestCompiler(this.temporaryFolder);
compiler.getTask(target).call(processor);
@@ -125,8 +116,7 @@ public class TypeUtilsTests {
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
this.typeUtilsConsumer.accept(roundEnv, this.typeUtils);
return false;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -84,8 +84,7 @@ public abstract class AbstractFieldValuesProcessorTests {
assertThat(values.get("stringArrayNone")).isNull();
assertThat(values.get("stringEmptyArray")).isEqualTo(new Object[0]);
assertThat(values.get("stringArrayConst")).isEqualTo(new Object[] { "OK", "KO" });
assertThat(values.get("stringArrayConstElements"))
.isEqualTo(new Object[] { "c" });
assertThat(values.get("stringArrayConstElements")).isEqualTo(new Object[] { "c" });
assertThat(values.get("integerArray")).isEqualTo(new Object[] { 42, 24 });
assertThat(values.get("unknownArray")).isNull();
assertThat(values.get("durationNone")).isNull();
@@ -103,8 +102,7 @@ public abstract class AbstractFieldValuesProcessorTests {
assertThat(values.get("dataSizeTerabytes")).isEqualTo("40TB");
}
@SupportedAnnotationTypes({
"org.springframework.boot.configurationsample.ConfigurationProperties" })
@SupportedAnnotationTypes({ "org.springframework.boot.configurationsample.ConfigurationProperties" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
private class TestProcessor extends AbstractProcessor {
@@ -118,14 +116,12 @@ public abstract class AbstractFieldValuesProcessorTests {
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
if (element instanceof TypeElement) {
try {
this.values.putAll(
this.processor.getFieldValues((TypeElement) element));
this.values.putAll(this.processor.getFieldValues((TypeElement) element));
}
catch (Exception ex) {
throw new IllegalStateException(ex);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,8 +28,7 @@ import static org.junit.Assume.assumeNoException;
*
* @author Phillip Webb
*/
public class JavaCompilerFieldValuesProcessorTests
extends AbstractFieldValuesProcessorTests {
public class JavaCompilerFieldValuesProcessorTests extends AbstractFieldValuesProcessorTests {
@Override
protected FieldValuesParser createProcessor(ProcessingEnvironment env) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,14 +44,12 @@ public class ConfigurationMetadataTests {
@Test
public void toDashedCaseWordsUnderscore() {
assertThat(toDashedCase("Word_With_underscore"))
.isEqualTo("word-with-underscore");
assertThat(toDashedCase("Word_With_underscore")).isEqualTo("word-with-underscore");
}
@Test
public void toDashedCaseWordsSeveralUnderscores() {
assertThat(toDashedCase("Word___With__underscore"))
.isEqualTo("word---with--underscore");
assertThat(toDashedCase("Word___With__underscore")).isEqualTo("word---with--underscore");
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,14 +34,12 @@ public class ItemMetadataTests {
@Test
public void newItemMetadataPrefixWithCamelCaseSuffix() {
assertThat(newItemMetadataPrefix("prefix.", "myValue"))
.isEqualTo("prefix.my-value");
assertThat(newItemMetadataPrefix("prefix.", "myValue")).isEqualTo("prefix.my-value");
}
@Test
public void newItemMetadataPrefixWithUpperCamelCaseSuffix() {
assertThat(newItemMetadataPrefix("prefix.", "MyValue"))
.isEqualTo("prefix.my-value");
assertThat(newItemMetadataPrefix("prefix.", "MyValue")).isEqualTo("prefix.my-value");
}
private String newItemMetadataPrefix(String prefix, String suffix) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,49 +38,34 @@ public class JsonMarshallerTests {
@Test
public void marshallAndUnmarshal() throws Exception {
ConfigurationMetadata metadata = new ConfigurationMetadata();
metadata.add(ItemMetadata.newProperty("a", "b", StringBuffer.class.getName(),
InputStream.class.getName(), "sourceMethod", "desc", "x",
new ItemDeprecation("Deprecation comment", "b.c.d")));
metadata.add(ItemMetadata.newProperty("b.c.d", null, null, null, null, null, null,
null));
metadata.add(
ItemMetadata.newProperty("c", null, null, null, null, null, 123, null));
metadata.add(
ItemMetadata.newProperty("d", null, null, null, null, null, true, null));
metadata.add(ItemMetadata.newProperty("e", null, null, null, null, null,
new String[] { "y", "n" }, null));
metadata.add(ItemMetadata.newProperty("f", null, null, null, null, null,
new Boolean[] { true, false }, null));
metadata.add(ItemMetadata.newProperty("a", "b", StringBuffer.class.getName(), InputStream.class.getName(),
"sourceMethod", "desc", "x", new ItemDeprecation("Deprecation comment", "b.c.d")));
metadata.add(ItemMetadata.newProperty("b.c.d", null, null, null, null, null, null, null));
metadata.add(ItemMetadata.newProperty("c", null, null, null, null, null, 123, null));
metadata.add(ItemMetadata.newProperty("d", null, null, null, null, null, true, null));
metadata.add(ItemMetadata.newProperty("e", null, null, null, null, null, new String[] { "y", "n" }, null));
metadata.add(ItemMetadata.newProperty("f", null, null, null, null, null, new Boolean[] { true, false }, null));
metadata.add(ItemMetadata.newGroup("d", null, null, null));
metadata.add(ItemHint.newHint("a.b"));
metadata.add(ItemHint.newHint("c", new ItemHint.ValueHint(123, "hey"),
new ItemHint.ValueHint(456, null)));
metadata.add(ItemHint.newHint("c", new ItemHint.ValueHint(123, "hey"), new ItemHint.ValueHint(456, null)));
metadata.add(new ItemHint("d", null,
Arrays.asList(
new ItemHint.ValueProvider("first",
Collections.singletonMap("target", "foo")),
Arrays.asList(new ItemHint.ValueProvider("first", Collections.singletonMap("target", "foo")),
new ItemHint.ValueProvider("second", null))));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonMarshaller marshaller = new JsonMarshaller();
marshaller.write(metadata, outputStream);
ConfigurationMetadata read = marshaller
.read(new ByteArrayInputStream(outputStream.toByteArray()));
assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class)
.fromSource(InputStream.class).withDescription("desc")
.withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d"));
ConfigurationMetadata read = marshaller.read(new ByteArrayInputStream(outputStream.toByteArray()));
assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class).fromSource(InputStream.class)
.withDescription("desc").withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d"));
assertThat(read).has(Metadata.withProperty("b.c.d"));
assertThat(read).has(Metadata.withProperty("c").withDefaultValue(123));
assertThat(read).has(Metadata.withProperty("d").withDefaultValue(true));
assertThat(read).has(
Metadata.withProperty("e").withDefaultValue(new String[] { "y", "n" }));
assertThat(read).has(Metadata.withProperty("f")
.withDefaultValue(new Object[] { true, false }));
assertThat(read).has(Metadata.withProperty("e").withDefaultValue(new String[] { "y", "n" }));
assertThat(read).has(Metadata.withProperty("f").withDefaultValue(new Object[] { true, false }));
assertThat(read).has(Metadata.withGroup("d"));
assertThat(read).has(Metadata.withHint("a.b"));
assertThat(read).has(
Metadata.withHint("c").withValue(0, 123, "hey").withValue(1, 456, null));
assertThat(read).has(Metadata.withHint("d").withProvider("first", "target", "foo")
.withProvider("second"));
assertThat(read).has(Metadata.withHint("c").withValue(0, 123, "hey").withValue(1, 456, null));
assertThat(read).has(Metadata.withHint("d").withProvider("first", "target", "foo").withProvider("second"));
}
@Test
@@ -88,45 +73,35 @@ public class JsonMarshallerTests {
ConfigurationMetadata metadata = new ConfigurationMetadata();
metadata.add(ItemHint.newHint("fff"));
metadata.add(ItemHint.newHint("eee"));
metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null,
null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null,
null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null,
null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null,
null, null, null, null));
metadata.add(ItemMetadata.newGroup("com.acme.bravo",
"com.example.AnotherTestProperties", null, null));
metadata.add(ItemMetadata.newGroup("com.acme.alpha", "com.example.TestProperties",
null, null));
metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null, null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null, null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null, null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null, null, null, null, null));
metadata.add(ItemMetadata.newGroup("com.acme.bravo", "com.example.AnotherTestProperties", null, null));
metadata.add(ItemMetadata.newGroup("com.acme.alpha", "com.example.TestProperties", null, null));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonMarshaller marshaller = new JsonMarshaller();
marshaller.write(metadata, outputStream);
String json = new String(outputStream.toByteArray());
assertThat(json).containsSubsequence("\"groups\"", "\"com.acme.alpha\"",
"\"com.acme.bravo\"", "\"properties\"", "\"com.example.alpha.ccc\"",
"\"com.example.alpha.ddd\"", "\"com.example.bravo.aaa\"",
assertThat(json).containsSubsequence("\"groups\"", "\"com.acme.alpha\"", "\"com.acme.bravo\"", "\"properties\"",
"\"com.example.alpha.ccc\"", "\"com.example.alpha.ddd\"", "\"com.example.bravo.aaa\"",
"\"com.example.bravo.bbb\"", "\"hints\"", "\"eee\"", "\"fff\"");
}
@Test
public void marshallPutDeprecatedItemsAtTheEnd() throws IOException {
ConfigurationMetadata metadata = new ConfigurationMetadata();
metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null,
null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null,
null, null, null, new ItemDeprecation(null, null, "warning")));
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null,
null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null,
null, null, null, new ItemDeprecation(null, null, "warning")));
metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null, null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null, null, null, null,
new ItemDeprecation(null, null, "warning")));
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, null, null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, null, null, null, null,
new ItemDeprecation(null, null, "warning")));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonMarshaller marshaller = new JsonMarshaller();
marshaller.write(metadata, outputStream);
String json = new String(outputStream.toByteArray());
assertThat(json).containsSubsequence("\"properties\"",
"\"com.example.alpha.ddd\"", "\"com.example.bravo.bbb\"",
assertThat(json).containsSubsequence("\"properties\"", "\"com.example.alpha.ddd\"", "\"com.example.bravo.bbb\"",
"\"com.example.alpha.ccc\"", "\"com.example.bravo.aaa\"");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -92,9 +92,8 @@ public final class Metadata {
this(itemType, name, null, null, null, null, null, null);
}
public MetadataItemCondition(ItemType itemType, String name, String type,
Class<?> sourceType, String sourceMethod, String description,
Object defaultValue, ItemDeprecation deprecation) {
public MetadataItemCondition(ItemType itemType, String name, String type, Class<?> sourceType,
String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) {
this.itemType = itemType;
this.name = name;
this.type = type;
@@ -139,90 +138,76 @@ public final class Metadata {
if (this.type != null && !this.type.equals(itemMetadata.getType())) {
return false;
}
if (this.sourceType != null
&& !this.sourceType.getName().equals(itemMetadata.getSourceType())) {
if (this.sourceType != null && !this.sourceType.getName().equals(itemMetadata.getSourceType())) {
return false;
}
if (this.sourceMethod != null
&& !this.sourceMethod.equals(itemMetadata.getSourceMethod())) {
if (this.sourceMethod != null && !this.sourceMethod.equals(itemMetadata.getSourceMethod())) {
return false;
}
if (this.defaultValue != null && !ObjectUtils
.nullSafeEquals(this.defaultValue, itemMetadata.getDefaultValue())) {
if (this.defaultValue != null
&& !ObjectUtils.nullSafeEquals(this.defaultValue, itemMetadata.getDefaultValue())) {
return false;
}
if (this.defaultValue == null && itemMetadata.getDefaultValue() != null) {
return false;
}
if (this.description != null
&& !this.description.equals(itemMetadata.getDescription())) {
if (this.description != null && !this.description.equals(itemMetadata.getDescription())) {
return false;
}
if (this.deprecation == null && itemMetadata.getDeprecation() != null) {
return false;
}
if (this.deprecation != null
&& !this.deprecation.equals(itemMetadata.getDeprecation())) {
if (this.deprecation != null && !this.deprecation.equals(itemMetadata.getDeprecation())) {
return false;
}
return true;
}
public MetadataItemCondition ofType(Class<?> dataType) {
return new MetadataItemCondition(this.itemType, this.name, dataType.getName(),
this.sourceType, this.sourceMethod, this.description,
this.defaultValue, this.deprecation);
return new MetadataItemCondition(this.itemType, this.name, dataType.getName(), this.sourceType,
this.sourceMethod, this.description, this.defaultValue, this.deprecation);
}
public MetadataItemCondition ofType(String dataType) {
return new MetadataItemCondition(this.itemType, this.name, dataType,
this.sourceType, this.sourceMethod, this.description,
this.defaultValue, this.deprecation);
return new MetadataItemCondition(this.itemType, this.name, dataType, this.sourceType, this.sourceMethod,
this.description, this.defaultValue, this.deprecation);
}
public MetadataItemCondition fromSource(Class<?> sourceType) {
return new MetadataItemCondition(this.itemType, this.name, this.type,
sourceType, this.sourceMethod, this.description, this.defaultValue,
this.deprecation);
return new MetadataItemCondition(this.itemType, this.name, this.type, sourceType, this.sourceMethod,
this.description, this.defaultValue, this.deprecation);
}
public MetadataItemCondition fromSourceMethod(String sourceMethod) {
return new MetadataItemCondition(this.itemType, this.name, this.type,
this.sourceType, sourceMethod, this.description, this.defaultValue,
this.deprecation);
return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, sourceMethod,
this.description, this.defaultValue, this.deprecation);
}
public MetadataItemCondition withDescription(String description) {
return new MetadataItemCondition(this.itemType, this.name, this.type,
this.sourceType, this.sourceMethod, description, this.defaultValue,
this.deprecation);
return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod,
description, this.defaultValue, this.deprecation);
}
public MetadataItemCondition withDefaultValue(Object defaultValue) {
return new MetadataItemCondition(this.itemType, this.name, this.type,
this.sourceType, this.sourceMethod, this.description, defaultValue,
this.deprecation);
return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod,
this.description, defaultValue, this.deprecation);
}
public MetadataItemCondition withDeprecation(String reason, String replacement) {
return withDeprecation(reason, replacement, null);
}
public MetadataItemCondition withDeprecation(String reason, String replacement,
String level) {
return new MetadataItemCondition(this.itemType, this.name, this.type,
this.sourceType, this.sourceMethod, this.description,
this.defaultValue, new ItemDeprecation(reason, replacement, level));
public MetadataItemCondition withDeprecation(String reason, String replacement, String level) {
return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod,
this.description, this.defaultValue, new ItemDeprecation(reason, replacement, level));
}
public MetadataItemCondition withNoDeprecation() {
return new MetadataItemCondition(this.itemType, this.name, this.type,
this.sourceType, this.sourceMethod, this.description,
this.defaultValue, null);
return new MetadataItemCondition(this.itemType, this.name, this.type, this.sourceType, this.sourceMethod,
this.description, this.defaultValue, null);
}
private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata,
String name) {
private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata, String name) {
for (ItemMetadata item : metadata.getItems()) {
if (item.isOfItemType(this.itemType) && name.equals(item.getName())) {
return item;
@@ -247,8 +232,7 @@ public final class Metadata {
this.providerConditions = Collections.emptyList();
}
public MetadataHintCondition(String name,
List<ItemHintValueCondition> valueConditions,
public MetadataHintCondition(String name, List<ItemHintValueCondition> valueConditions,
List<ItemHintProviderCondition> providerConditions) {
this.name = name;
this.valueConditions = valueConditions;
@@ -274,12 +258,10 @@ public final class Metadata {
if (itemHint == null) {
return false;
}
return matches(itemHint, this.valueConditions)
&& matches(itemHint, this.providerConditions);
return matches(itemHint, this.valueConditions) && matches(itemHint, this.providerConditions);
}
private boolean matches(ItemHint itemHint,
List<? extends Condition<ItemHint>> conditions) {
private boolean matches(ItemHint itemHint, List<? extends Condition<ItemHint>> conditions) {
for (Condition<ItemHint> condition : conditions) {
if (!condition.matches(itemHint)) {
return false;
@@ -288,8 +270,7 @@ public final class Metadata {
return true;
}
private ItemHint getFirstHintWithName(ConfigurationMetadata metadata,
String name) {
private ItemHint getFirstHintWithName(ConfigurationMetadata metadata, String name) {
for (ItemHint hint : metadata.getHints()) {
if (name.equals(hint.getName())) {
return hint;
@@ -298,11 +279,9 @@ public final class Metadata {
return null;
}
public MetadataHintCondition withValue(int index, Object value,
String description) {
public MetadataHintCondition withValue(int index, Object value, String description) {
return new MetadataHintCondition(this.name,
add(this.valueConditions,
new ItemHintValueCondition(index, value, description)),
add(this.valueConditions, new ItemHintValueCondition(index, value, description)),
this.providerConditions);
}
@@ -310,17 +289,13 @@ public final class Metadata {
return withProvider(this.providerConditions.size(), provider, null);
}
public MetadataHintCondition withProvider(String provider, String key,
Object value) {
return withProvider(this.providerConditions.size(), provider,
Collections.singletonMap(key, value));
public MetadataHintCondition withProvider(String provider, String key, Object value) {
return withProvider(this.providerConditions.size(), provider, Collections.singletonMap(key, value));
}
public MetadataHintCondition withProvider(int index, String provider,
Map<String, Object> parameters) {
public MetadataHintCondition withProvider(int index, String provider, Map<String, Object> parameters) {
return new MetadataHintCondition(this.name, this.valueConditions,
add(this.providerConditions,
new ItemHintProviderCondition(index, provider, parameters)));
add(this.providerConditions, new ItemHintProviderCondition(index, provider, parameters)));
}
private <T> List<T> add(List<T> items, T item) {
@@ -367,8 +342,7 @@ public final class Metadata {
if (this.value != null && !this.value.equals(valueHint.getValue())) {
return false;
}
if (this.description != null
&& !this.description.equals(valueHint.getDescription())) {
if (this.description != null && !this.description.equals(valueHint.getDescription())) {
return false;
}
return true;
@@ -384,8 +358,7 @@ public final class Metadata {
private final Map<String, Object> parameters;
ItemHintProviderCondition(int index, String name,
Map<String, Object> parameters) {
ItemHintProviderCondition(int index, String name, Map<String, Object> parameters) {
this.index = index;
this.name = name;
this.parameters = parameters;

View File

@@ -22,7 +22,6 @@ package org.springframework.boot.configurationsample.generic;
* @param <C> mapping value type
* @author Stephane Nicoll
*/
public abstract class AbstractIntermediateGenericProperties<C>
extends AbstractGenericProperties<String, Integer, C> {
public abstract class AbstractIntermediateGenericProperties<C> extends AbstractGenericProperties<String, Integer, C> {
}

View File

@@ -26,7 +26,6 @@ import org.springframework.boot.configurationsample.ConfigurationProperties;
* @author Stephane Nicoll
*/
@ConfigurationProperties("generic")
public class SimpleGenericProperties
extends AbstractIntermediateGenericProperties<Duration> {
public class SimpleGenericProperties extends AbstractIntermediateGenericProperties<Duration> {
}

View File

@@ -26,7 +26,6 @@ import org.springframework.boot.configurationsample.ConfigurationProperties;
* @author Stephane Nicoll
*/
@ConfigurationProperties("generic")
public class UnresolvedGenericProperties<B extends Number, C>
extends AbstractGenericProperties<String, B, C> {
public class UnresolvedGenericProperties<B extends Number, C> extends AbstractGenericProperties<String, B, C> {
}

View File

@@ -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();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,8 +21,7 @@ package org.springframework.boot.configurationsample.simple;
*
* @author Stephane Nicoll
*/
public abstract class HierarchicalPropertiesParent
extends HierarchicalPropertiesGrandparent {
public abstract class HierarchicalPropertiesParent extends HierarchicalPropertiesGrandparent {
private String second;