Merge branch '2.1.x'

Closes gh-17079
This commit is contained in:
Andy Wilkinson
2019-06-07 11:00:44 +01:00
2799 changed files with 28402 additions and 47836 deletions

View File

@@ -73,11 +73,9 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
static final String DEPRECATED_CONFIGURATION_PROPERTY_ANNOTATION = "org.springframework.boot."
+ "context.properties.DeprecatedConfigurationProperty";
static final String DEFAULT_VALUE_ANNOTATION = "org.springframework.boot."
+ "context.properties.bind.DefaultValue";
static final String DEFAULT_VALUE_ANNOTATION = "org.springframework.boot." + "context.properties.bind.DefaultValue";
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";
@@ -129,21 +127,16 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
public synchronized void init(ProcessingEnvironment env) {
super.init(env);
this.metadataStore = new MetadataStore(env);
this.metadataCollector = new MetadataCollector(env,
this.metadataStore.readMetadata());
this.metadataEnv = new MetadataGenerationEnvironment(env,
configurationPropertiesAnnotation(),
nestedConfigurationPropertyAnnotation(),
deprecatedConfigurationPropertyAnnotation(), defaultValueAnnotation(),
endpointAnnotation(), readOperationAnnotation());
this.metadataCollector = new MetadataCollector(env, this.metadataStore.readMetadata());
this.metadataEnv = new MetadataGenerationEnvironment(env, configurationPropertiesAnnotation(),
nestedConfigurationPropertyAnnotation(), deprecatedConfigurationPropertyAnnotation(),
defaultValueAnnotation(), endpointAnnotation(), readOperationAnnotation());
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
this.metadataCollector.processing(roundEnv);
TypeElement annotationType = this.metadataEnv
.getConfigurationPropertiesAnnotationElement();
TypeElement annotationType = this.metadataEnv.getConfigurationPropertiesAnnotationElement();
if (annotationType != null) { // Is @ConfigurationProperties available
for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) {
processElement(element);
@@ -151,8 +144,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
}
TypeElement endpointType = this.metadataEnv.getEndpointAnnotationElement();
if (endpointType != null) { // Is @Endpoint available
getElementsAnnotatedOrMetaAnnotatedWith(roundEnv, endpointType)
.forEach(this::processEndpoint);
getElementsAnnotatedOrMetaAnnotatedWith(roundEnv, endpointType).forEach(this::processEndpoint);
}
if (roundEnv.processingOver()) {
try {
@@ -165,8 +157,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()) {
@@ -181,11 +173,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);
@@ -202,8 +193,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
private void processElement(Element element) {
try {
AnnotationMirror annotation = this.metadataEnv
.getConfigurationPropertiesAnnotation(element);
AnnotationMirror annotation = this.metadataEnv.getConfigurationPropertiesAnnotation(element);
if (annotation != null) {
String prefix = getPrefix(annotation);
if (element instanceof TypeElement) {
@@ -215,8 +205,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);
}
}
@@ -227,22 +216,16 @@ 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.metadataEnv.getTypeUtils().getQualifiedName(returns),
this.metadataEnv.getTypeUtils()
.getQualifiedName(element.getEnclosingElement()),
element.toString());
ItemMetadata group = ItemMetadata.newGroup(prefix,
this.metadataEnv.getTypeUtils().getQualifiedName(returns),
this.metadataEnv.getTypeUtils().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);
@@ -252,67 +235,54 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
}
}
private void processTypeElement(String prefix, TypeElement element,
ExecutableElement source) {
new PropertyDescriptorResolver(this.metadataEnv).resolve(element, source)
.forEach((descriptor) -> {
this.metadataCollector.add(
descriptor.resolveItemMetadata(prefix, this.metadataEnv));
if (descriptor.isNested(this.metadataEnv)) {
TypeElement nestedTypeElement = (TypeElement) this.metadataEnv
.getTypeUtils().asElement(descriptor.getType());
String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix,
descriptor.getName());
processTypeElement(nestedPrefix, nestedTypeElement, source);
}
});
private void processTypeElement(String prefix, TypeElement element, ExecutableElement source) {
new PropertyDescriptorResolver(this.metadataEnv).resolve(element, source).forEach((descriptor) -> {
this.metadataCollector.add(descriptor.resolveItemMetadata(prefix, this.metadataEnv));
if (descriptor.isNested(this.metadataEnv)) {
TypeElement nestedTypeElement = (TypeElement) this.metadataEnv.getTypeUtils()
.asElement(descriptor.getType());
String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, descriptor.getName());
processTypeElement(nestedPrefix, nestedTypeElement, source);
}
});
}
private void processEndpoint(Element element, List<Element> annotations) {
try {
String annotationName = this.metadataEnv.getTypeUtils()
.getQualifiedName(annotations.get(0));
AnnotationMirror annotation = this.metadataEnv.getAnnotation(element,
annotationName);
String annotationName = this.metadataEnv.getTypeUtils().getQualifiedName(annotations.get(0));
AnnotationMirror annotation = this.metadataEnv.getAnnotation(element, annotationName);
if (element instanceof TypeElement) {
processEndpoint(annotation, (TypeElement) element);
}
}
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);
}
}
private void processEndpoint(AnnotationMirror annotation, TypeElement element) {
Map<String, Object> elementValues = this.metadataEnv
.getAnnotationElementValues(annotation);
Map<String, Object> elementValues = this.metadataEnv.getAnnotationElementValues(annotation);
String endpointId = (String) elementValues.get("id");
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.metadataEnv.getTypeUtils().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())) {
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
if (this.metadataEnv.getReadOperationAnnotation(method) != null
&& (TypeKind.VOID != method.getReturnType().getKind())
&& hasNoOrOptionalParameters(method)) {
&& (TypeKind.VOID != method.getReturnType().getKind()) && hasNoOrOptionalParameters(method)) {
return true;
}
}
@@ -329,8 +299,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor
}
private String getPrefix(AnnotationMirror annotation) {
Map<String, Object> elementValues = this.metadataEnv
.getAnnotationElementValues(annotation);
Map<String, Object> elementValues = this.metadataEnv.getAnnotationElementValues(annotation);
Object prefix = elementValues.get("prefix");
if (prefix != null && !"".equals(prefix)) {
return (String) prefix;
@@ -352,8 +321,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

@@ -37,9 +37,8 @@ import javax.tools.Diagnostic.Kind;
*/
class ConstructorParameterPropertyDescriptor extends PropertyDescriptor<VariableElement> {
ConstructorParameterPropertyDescriptor(TypeElement ownerElement,
ExecutableElement factoryMethod, VariableElement source, String name,
TypeMirror type, VariableElement field, ExecutableElement getter,
ConstructorParameterPropertyDescriptor(TypeElement ownerElement, ExecutableElement factoryMethod,
VariableElement source, String name, TypeMirror type, VariableElement field, ExecutableElement getter,
ExecutableElement setter) {
super(ownerElement, factoryMethod, source, name, type, field, getter, setter);
}
@@ -60,8 +59,7 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor<Variable
return getSource().asType().accept(DefaultPrimitiveTypeVisitor.INSTANCE, null);
}
private Object getDefaultValueFromAnnotation(
MetadataGenerationEnvironment environment, Element element) {
private Object getDefaultValueFromAnnotation(MetadataGenerationEnvironment environment, Element element) {
AnnotationMirror annotation = environment.getDefaultValueAnnotation(element);
List<String> defaultValue = getDefaultValue(environment, annotation);
if (defaultValue != null) {
@@ -70,21 +68,18 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor<Variable
if (defaultValue.size() == 1) {
return coerceValue(specificType, defaultValue.get(0));
}
return defaultValue.stream()
.map((value) -> coerceValue(specificType, value))
return defaultValue.stream().map((value) -> coerceValue(specificType, value))
.collect(Collectors.toList());
}
catch (IllegalArgumentException ex) {
environment.getMessager().printMessage(Kind.ERROR, ex.getMessage(),
element, annotation);
environment.getMessager().printMessage(Kind.ERROR, ex.getMessage(), element, annotation);
}
}
return null;
}
@SuppressWarnings("unchecked")
private List<String> getDefaultValue(MetadataGenerationEnvironment environment,
AnnotationMirror annotation) {
private List<String> getDefaultValue(MetadataGenerationEnvironment environment, AnnotationMirror annotation) {
if (annotation == null) {
return null;
}
@@ -94,24 +89,20 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor<Variable
private TypeMirror determineSpecificType(MetadataGenerationEnvironment environment) {
TypeMirror candidate = getSource().asType();
TypeMirror elementCandidate = environment.getTypeUtils()
.extractElementType(candidate);
TypeMirror elementCandidate = environment.getTypeUtils().extractElementType(candidate);
if (elementCandidate != null) {
candidate = elementCandidate;
}
PrimitiveType primitiveType = environment.getTypeUtils()
.getPrimitiveType(candidate);
PrimitiveType primitiveType = environment.getTypeUtils().getPrimitiveType(candidate);
return (primitiveType != null) ? primitiveType : candidate;
}
private Object coerceValue(TypeMirror type, String value) {
Object coercedValue = type.accept(DefaultValueCoercionTypeVisitor.INSTANCE,
value);
Object coercedValue = type.accept(DefaultValueCoercionTypeVisitor.INSTANCE, value);
return (coercedValue != null) ? coercedValue : value;
}
private static class DefaultValueCoercionTypeVisitor
extends TypeKindVisitor8<Object, String> {
private static class DefaultValueCoercionTypeVisitor extends TypeKindVisitor8<Object, String> {
private static final DefaultValueCoercionTypeVisitor INSTANCE = new DefaultValueCoercionTypeVisitor();
@@ -120,8 +111,7 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor<Variable
return Integer.valueOf(value);
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException(
String.format("Invalid number representation '%s'", value));
throw new IllegalArgumentException(String.format("Invalid number representation '%s'", value));
}
}
@@ -130,8 +120,7 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor<Variable
return Double.valueOf(value);
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException(String
.format("Invalid floating point representation '%s'", value));
throw new IllegalArgumentException(String.format("Invalid floating point representation '%s'", value));
}
}
@@ -163,8 +152,7 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor<Variable
@Override
public Object visitPrimitiveAsChar(PrimitiveType t, String value) {
if (value.length() > 1) {
throw new IllegalArgumentException(
String.format("Invalid character representation '%s'", value));
throw new IllegalArgumentException(String.format("Invalid character representation '%s'", value));
}
return value;
}
@@ -181,8 +169,7 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor<Variable
}
private static class DefaultPrimitiveTypeVisitor
extends TypeKindVisitor8<Object, Void> {
private static class DefaultPrimitiveTypeVisitor extends TypeKindVisitor8<Object, Void> {
private static final DefaultPrimitiveTypeVisitor INSTANCE = new DefaultPrimitiveTypeVisitor();

View File

@@ -28,17 +28,15 @@ import javax.lang.model.type.TypeMirror;
*/
class JavaBeanPropertyDescriptor extends PropertyDescriptor<ExecutableElement> {
JavaBeanPropertyDescriptor(TypeElement ownerElement, ExecutableElement factoryMethod,
ExecutableElement getter, String name, TypeMirror type, VariableElement field,
ExecutableElement setter) {
JavaBeanPropertyDescriptor(TypeElement ownerElement, ExecutableElement factoryMethod, ExecutableElement getter,
String name, TypeMirror type, VariableElement field, ExecutableElement setter) {
super(ownerElement, factoryMethod, getter, name, type, field, getter, setter);
}
@Override
protected boolean isProperty(MetadataGenerationEnvironment env) {
boolean isCollection = env.getTypeUtils().isCollectionOrMap(getType());
return !env.isExcluded(getType()) && getGetter() != null
&& (getSetter() != null || isCollection);
return !env.isExcluded(getType()) && getGetter() != null && (getSetter() != null || isCollection);
}
@Override

View File

@@ -42,9 +42,8 @@ class LombokPropertyDescriptor extends PropertyDescriptor<VariableElement> {
private static final String LOMBOK_ACCESS_LEVEL_PUBLIC = "PUBLIC";
LombokPropertyDescriptor(TypeElement typeElement, ExecutableElement factoryMethod,
VariableElement field, String name, TypeMirror type, ExecutableElement getter,
ExecutableElement setter) {
LombokPropertyDescriptor(TypeElement typeElement, ExecutableElement factoryMethod, VariableElement field,
String name, TypeMirror type, ExecutableElement getter, ExecutableElement setter) {
super(typeElement, factoryMethod, field, name, type, field, getter, setter);
}
@@ -71,10 +70,8 @@ class LombokPropertyDescriptor extends PropertyDescriptor<VariableElement> {
}
@Override
protected ItemDeprecation resolveItemDeprecation(
MetadataGenerationEnvironment environment) {
boolean deprecated = environment.isDeprecated(getField())
|| environment.isDeprecated(getGetter())
protected ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment) {
boolean deprecated = environment.isDeprecated(getField()) || environment.isDeprecated(getGetter())
|| environment.isDeprecated(getFactoryMethod());
return deprecated ? environment.resolveItemDeprecation(getGetter()) : null;
}
@@ -93,25 +90,20 @@ class LombokPropertyDescriptor extends PropertyDescriptor<VariableElement> {
* write accessor
* @return {@code true} if this field has a public accessor of the specified type
*/
private boolean hasLombokPublicAccessor(MetadataGenerationEnvironment env,
boolean getter) {
String annotation = (getter ? LOMBOK_GETTER_ANNOTATION
: LOMBOK_SETTER_ANNOTATION);
AnnotationMirror lombokMethodAnnotationOnField = env.getAnnotation(getField(),
annotation);
private boolean hasLombokPublicAccessor(MetadataGenerationEnvironment env, boolean getter) {
String annotation = (getter ? LOMBOK_GETTER_ANNOTATION : LOMBOK_SETTER_ANNOTATION);
AnnotationMirror lombokMethodAnnotationOnField = env.getAnnotation(getField(), annotation);
if (lombokMethodAnnotationOnField != null) {
return isAccessLevelPublic(env, lombokMethodAnnotationOnField);
}
AnnotationMirror lombokMethodAnnotationOnElement = env
.getAnnotation(getOwnerElement(), annotation);
AnnotationMirror lombokMethodAnnotationOnElement = env.getAnnotation(getOwnerElement(), annotation);
if (lombokMethodAnnotationOnElement != null) {
return isAccessLevelPublic(env, lombokMethodAnnotationOnElement);
}
return (env.getAnnotation(getOwnerElement(), LOMBOK_DATA_ANNOTATION) != null);
}
private boolean isAccessLevelPublic(MetadataGenerationEnvironment env,
AnnotationMirror lombokAnnotation) {
private boolean isAccessLevelPublic(MetadataGenerationEnvironment env, AnnotationMirror lombokAnnotation) {
Map<String, Object> values = env.getAnnotationElementValues(lombokAnnotation);
Object value = values.get("value");
return (value == null || value.toString().equals(LOMBOK_ACCESS_LEVEL_PUBLIC));

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

@@ -92,12 +92,9 @@ class MetadataGenerationEnvironment {
private final String readOperationAnnotation;
MetadataGenerationEnvironment(ProcessingEnvironment environment,
String configurationPropertiesAnnotation,
String nestedConfigurationPropertyAnnotation,
String deprecatedConfigurationPropertyAnnotation,
String defaultValueAnnotation, String endpointAnnotation,
String readOperationAnnotation) {
MetadataGenerationEnvironment(ProcessingEnvironment environment, String configurationPropertiesAnnotation,
String nestedConfigurationPropertyAnnotation, String deprecatedConfigurationPropertyAnnotation,
String defaultValueAnnotation, String endpointAnnotation, String readOperationAnnotation) {
this.typeUtils = new TypeUtils(environment);
this.elements = environment.getElementUtils();
this.messager = environment.getMessager();
@@ -135,8 +132,7 @@ class MetadataGenerationEnvironment {
* value has been detected
*/
public Object getFieldDefaultValue(TypeElement type, String name) {
return this.defaultValues.computeIfAbsent(type, this::resolveFieldValues)
.get(name);
return this.defaultValues.computeIfAbsent(type, this::resolveFieldValues).get(name);
}
public boolean isExcluded(TypeMirror type) {
@@ -161,8 +157,7 @@ class MetadataGenerationEnvironment {
}
public ItemDeprecation resolveItemDeprecation(Element element) {
AnnotationMirror annotation = getAnnotation(element,
this.deprecatedConfigurationPropertyAnnotation);
AnnotationMirror annotation = getAnnotation(element, this.deprecatedConfigurationPropertyAnnotation);
String reason = null;
String replacement = null;
if (annotation != null) {
@@ -192,8 +187,8 @@ class MetadataGenerationEnvironment {
public Map<String, Object> getAnnotationElementValues(AnnotationMirror annotation) {
Map<String, Object> values = new LinkedHashMap<>();
annotation.getElementValues().forEach((name, value) -> values
.put(name.getSimpleName().toString(), getAnnotationValue(value)));
annotation.getElementValues()
.forEach((name, value) -> values.put(name.getSimpleName().toString(), getAnnotationValue(value)));
return values;
}
@@ -201,8 +196,7 @@ class MetadataGenerationEnvironment {
Object value = annotationValue.getValue();
if (value instanceof List) {
List<Object> values = new ArrayList<>();
((List<?>) value)
.forEach((v) -> values.add(((AnnotationValue) v).getValue()));
((List<?>) value).forEach((v) -> values.add(((AnnotationValue) v).getValue()));
return values;
}
return value;
@@ -259,8 +253,7 @@ class MetadataGenerationEnvironment {
// continue
}
Element superType = this.typeUtils.asElement(element.getSuperclass());
if (superType instanceof TypeElement
&& superType.asType().getKind() != TypeKind.NONE) {
if (superType instanceof TypeElement && superType.asType().getKind() != TypeKind.NONE) {
resolveFieldValuesFor(values, (TypeElement) superType);
}
}

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

@@ -51,9 +51,8 @@ abstract class PropertyDescriptor<S extends Element> {
private final ExecutableElement setter;
protected PropertyDescriptor(TypeElement ownerElement,
ExecutableElement factoryMethod, S source, String name, TypeMirror type,
VariableElement field, ExecutableElement getter, ExecutableElement setter) {
protected PropertyDescriptor(TypeElement ownerElement, ExecutableElement factoryMethod, S source, String name,
TypeMirror type, VariableElement field, ExecutableElement getter, ExecutableElement setter) {
this.ownerElement = ownerElement;
this.factoryMethod = factoryMethod;
this.source = source;
@@ -98,21 +97,17 @@ abstract class PropertyDescriptor<S extends Element> {
protected abstract boolean isProperty(MetadataGenerationEnvironment environment);
protected abstract Object resolveDefaultValue(
MetadataGenerationEnvironment environment);
protected abstract Object resolveDefaultValue(MetadataGenerationEnvironment environment);
protected ItemDeprecation resolveItemDeprecation(
MetadataGenerationEnvironment environment) {
boolean deprecated = environment.isDeprecated(getGetter())
|| environment.isDeprecated(getSetter())
protected ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment) {
boolean deprecated = environment.isDeprecated(getGetter()) || environment.isDeprecated(getSetter())
|| environment.isDeprecated(getFactoryMethod());
return deprecated ? environment.resolveItemDeprecation(getGetter()) : null;
}
protected boolean isNested(MetadataGenerationEnvironment environment) {
Element typeElement = environment.getTypeUtils().asElement(getType());
if (!(typeElement instanceof TypeElement)
|| typeElement.getKind() == ElementKind.ENUM) {
if (!(typeElement instanceof TypeElement) || typeElement.getKind() == ElementKind.ENUM) {
return false;
}
if (environment.getConfigurationPropertiesAnnotation(getGetter()) != null) {
@@ -127,8 +122,7 @@ abstract class PropertyDescriptor<S extends Element> {
return isParentTheSame(typeElement, getOwnerElement());
}
public ItemMetadata resolveItemMetadata(String prefix,
MetadataGenerationEnvironment environment) {
public ItemMetadata resolveItemMetadata(String prefix, MetadataGenerationEnvironment environment) {
if (isNested(environment)) {
return resolveItemMetadataGroup(prefix, environment);
}
@@ -138,19 +132,17 @@ abstract class PropertyDescriptor<S extends Element> {
return null;
}
private ItemMetadata resolveItemMetadataProperty(String prefix,
MetadataGenerationEnvironment environment) {
private ItemMetadata resolveItemMetadataProperty(String prefix, MetadataGenerationEnvironment environment) {
String dataType = resolveType(environment);
String ownerType = environment.getTypeUtils().getQualifiedName(getOwnerElement());
String description = resolveDescription(environment);
Object defaultValue = resolveDefaultValue(environment);
ItemDeprecation deprecation = resolveItemDeprecation(environment);
return ItemMetadata.newProperty(prefix, getName(), dataType, ownerType, null,
description, defaultValue, deprecation);
return ItemMetadata.newProperty(prefix, getName(), dataType, ownerType, null, description, defaultValue,
deprecation);
}
private ItemMetadata resolveItemMetadataGroup(String prefix,
MetadataGenerationEnvironment environment) {
private ItemMetadata resolveItemMetadataGroup(String prefix, MetadataGenerationEnvironment environment) {
Element propertyElement = environment.getTypeUtils().asElement(getType());
String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, getName());
String dataType = environment.getTypeUtils().getQualifiedName(propertyElement);

View File

@@ -49,22 +49,19 @@ class PropertyDescriptorResolver {
* or {@code null}
* @return the candidate properties for metadata generation
*/
public Stream<PropertyDescriptor<?>> resolve(TypeElement type,
ExecutableElement factoryMethod) {
public Stream<PropertyDescriptor<?>> resolve(TypeElement type, ExecutableElement factoryMethod) {
TypeElementMembers members = new TypeElementMembers(this.environment, type);
ExecutableElement constructor = resolveConstructor(type);
if (constructor != null) {
return resolveConstructorProperties(type, factoryMethod, members,
constructor);
return resolveConstructorProperties(type, factoryMethod, members, constructor);
}
else {
return resolveJavaBeanProperties(type, factoryMethod, members);
}
}
public Stream<PropertyDescriptor<?>> resolveConstructorProperties(TypeElement type,
ExecutableElement factoryMethod, TypeElementMembers members,
ExecutableElement constructor) {
public Stream<PropertyDescriptor<?>> resolveConstructorProperties(TypeElement type, ExecutableElement factoryMethod,
TypeElementMembers members, ExecutableElement constructor) {
Map<String, PropertyDescriptor<?>> candidates = new LinkedHashMap<>();
constructor.getParameters().forEach((parameter) -> {
String name = parameter.getSimpleName().toString();
@@ -72,49 +69,44 @@ class PropertyDescriptorResolver {
ExecutableElement getter = members.getPublicGetter(name, propertyType);
ExecutableElement setter = members.getPublicSetter(name, propertyType);
VariableElement field = members.getFields().get(name);
register(candidates, new ConstructorParameterPropertyDescriptor(type,
factoryMethod, parameter, name, propertyType, field, getter, setter));
register(candidates, new ConstructorParameterPropertyDescriptor(type, factoryMethod, parameter, name,
propertyType, field, getter, setter));
});
return candidates.values().stream();
}
public Stream<PropertyDescriptor<?>> resolveJavaBeanProperties(TypeElement type,
ExecutableElement factoryMethod, TypeElementMembers members) {
public Stream<PropertyDescriptor<?>> resolveJavaBeanProperties(TypeElement type, ExecutableElement factoryMethod,
TypeElementMembers members) {
// First check if we have regular java bean properties there
Map<String, PropertyDescriptor<?>> candidates = new LinkedHashMap<>();
members.getPublicGetters().forEach((name, getter) -> {
TypeMirror propertyType = getter.getReturnType();
register(candidates,
new JavaBeanPropertyDescriptor(type, factoryMethod, getter, name,
propertyType, members.getFields().get(name),
members.getPublicSetter(name, propertyType)));
register(candidates, new JavaBeanPropertyDescriptor(type, factoryMethod, getter, name, propertyType,
members.getFields().get(name), members.getPublicSetter(name, propertyType)));
});
// Then check for Lombok ones
members.getFields().forEach((name, field) -> {
TypeMirror propertyType = field.asType();
ExecutableElement getter = members.getPublicGetter(name, propertyType);
ExecutableElement setter = members.getPublicSetter(name, propertyType);
register(candidates, new LombokPropertyDescriptor(type, factoryMethod, field,
name, propertyType, getter, setter));
register(candidates,
new LombokPropertyDescriptor(type, factoryMethod, field, name, propertyType, getter, setter));
});
return candidates.values().stream();
}
private void register(Map<String, PropertyDescriptor<?>> candidates,
PropertyDescriptor<?> descriptor) {
private void register(Map<String, PropertyDescriptor<?>> candidates, PropertyDescriptor<?> descriptor) {
if (!candidates.containsKey(descriptor.getName()) && isCandidate(descriptor)) {
candidates.put(descriptor.getName(), descriptor);
}
}
private boolean isCandidate(PropertyDescriptor<?> descriptor) {
return descriptor.isProperty(this.environment)
|| descriptor.isNested(this.environment);
return descriptor.isProperty(this.environment) || descriptor.isNested(this.environment);
}
private ExecutableElement resolveConstructor(TypeElement type) {
List<ExecutableElement> constructors = ElementFilter
.constructorsIn(type.getEnclosedElements());
List<ExecutableElement> constructors = ElementFilter.constructorsIn(type.getEnclosedElements());
if (constructors.size() == 1 && constructors.get(0).getParameters().size() > 0) {
return constructors.get(0);
}

View File

@@ -57,17 +57,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);
}
Element superType = this.env.getTypeUtils().asElement(element.getSuperclass());
if (superType instanceof TypeElement
&& !OBJECT_CLASS_NAME.equals(superType.toString())) {
if (superType instanceof TypeElement && !OBJECT_CLASS_NAME.equals(superType.toString())) {
process((TypeElement) superType);
}
}
@@ -80,8 +77,8 @@ class TypeElementMembers {
}
else if (isSetter(method)) {
String propertyName = getAccessorName(name);
List<ExecutableElement> matchingSetters = this.publicSetters
.computeIfAbsent(propertyName, (k) -> new ArrayList<>());
List<ExecutableElement> matchingSetters = this.publicSetters.computeIfAbsent(propertyName,
(k) -> new ArrayList<>());
TypeMirror paramType = method.getParameters().get(0).asType();
if (getMatchingSetter(matchingSetters, paramType) == null) {
matchingSetters.add(method);
@@ -92,13 +89,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)) {
@@ -110,27 +105,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;
}
@@ -157,10 +149,8 @@ class TypeElementMembers {
if (this.env.getTypeUtils().isSameType(returnType, type)) {
return candidate;
}
TypeMirror alternative = this.env.getTypeUtils()
.getWrapperOrPrimitiveFor(type);
if (alternative != null
&& this.env.getTypeUtils().isSameType(returnType, alternative)) {
TypeMirror alternative = this.env.getTypeUtils().getWrapperOrPrimitiveFor(type);
if (alternative != null && this.env.getTypeUtils().isSameType(returnType, alternative)) {
return candidate;
}
}
@@ -174,8 +164,7 @@ class TypeElementMembers {
if (matching != null) {
return matching;
}
TypeMirror alternative = this.env.getTypeUtils()
.getWrapperOrPrimitiveFor(type);
TypeMirror alternative = this.env.getTypeUtils().getWrapperOrPrimitiveFor(type);
if (alternative != null) {
return getMatchingSetter(candidates, alternative);
}

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);
}
@@ -156,13 +153,11 @@ class TypeUtils {
}
private TypeMirror getCollectionElementType(TypeMirror type) {
if (((TypeElement) this.types.asElement(type)).getQualifiedName()
.contentEquals(Collection.class.getName())) {
if (((TypeElement) this.types.asElement(type)).getQualifiedName().contentEquals(Collection.class.getName())) {
DeclaredType declaredType = (DeclaredType) type;
// raw type, just "Collection"
if (declaredType.getTypeArguments().size() == 0) {
return this.types.getDeclaredType(this.env.getElementUtils()
.getTypeElement(Object.class.getName()));
return this.types.getDeclaredType(this.env.getElementUtils().getTypeElement(Object.class.getName()));
}
// return type argument to Collection<...>
return declaredType.getTypeArguments().get(0);
@@ -183,8 +178,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();
}
@@ -207,8 +201,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) {
@@ -256,8 +249,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));
}
}
@@ -266,8 +258,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;
@@ -284,17 +275,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());
}
@@ -355,8 +344,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) {
@@ -388,8 +376,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);
}
@@ -397,8 +384,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.
@@ -148,8 +148,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);
@@ -183,8 +182,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 {
@@ -209,8 +207,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

@@ -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()) {

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

@@ -62,8 +62,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
* @author Kris De Volder
* @author Jonas Keßler
*/
public class ConfigurationMetadataAnnotationProcessorTests
extends AbstractMetadataGenerationTests {
public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGenerationTests {
@Test
public void notAnnotated() {
@@ -74,15 +73,12 @@ public class ConfigurationMetadataAnnotationProcessorTests
@Test
public void simpleProperties() {
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)
.withDefaultValue(false).fromSource(SimpleProperties.class)
.withDescription("A simple flag.").withDeprecation(null, null));
assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).withDefaultValue(false)
.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"));
@@ -91,85 +87,60 @@ public class ConfigurationMetadataAnnotationProcessorTests
@Test
public void simplePrefixValueProperties() {
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() {
ConfigurationMetadata metadata = compile(SimpleTypeProperties.class);
assertThat(metadata).has(
Metadata.withGroup("simple.type").fromSource(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-string", String.class));
.has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class).withDefaultValue(0));
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-byte", Byte.class));
.has(Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class).withDefaultValue(false));
assertThat(metadata).has(Metadata.withProperty("simple.type.my-short", Short.class));
assertThat(metadata)
.has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class)
.withDefaultValue(0));
.has(Metadata.withProperty("simple.type.my-primitive-short", Short.class).withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("simple.type.my-integer", Integer.class));
assertThat(metadata)
.has(Metadata.withProperty("simple.type.my-char", Character.class));
assertThat(metadata).has(
Metadata.withProperty("simple.type.my-primitive-char", Character.class));
.has(Metadata.withProperty("simple.type.my-primitive-integer", Integer.class).withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("simple.type.my-long", Long.class));
assertThat(metadata)
.has(Metadata.withProperty("simple.type.my-boolean", Boolean.class));
assertThat(metadata).has(
Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class)
.withDefaultValue(false));
assertThat(metadata)
.has(Metadata.withProperty("simple.type.my-short", Short.class));
assertThat(metadata)
.has(Metadata.withProperty("simple.type.my-primitive-short", Short.class)
.withDefaultValue(0));
assertThat(metadata)
.has(Metadata.withProperty("simple.type.my-integer", Integer.class));
assertThat(metadata).has(
Metadata.withProperty("simple.type.my-primitive-integer", Integer.class)
.withDefaultValue(0));
assertThat(metadata)
.has(Metadata.withProperty("simple.type.my-long", Long.class));
assertThat(metadata)
.has(Metadata.withProperty("simple.type.my-primitive-long", Long.class)
.withDefaultValue(0));
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));
.has(Metadata.withProperty("simple.type.my-primitive-long", Long.class).withDefaultValue(0));
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() {
ConfigurationMetadata metadata = compile(HierarchicalProperties.class,
HierarchicalPropertiesParent.class,
ConfigurationMetadata metadata = compile(HierarchicalProperties.class, HierarchicalPropertiesParent.class,
HierarchicalPropertiesGrandparent.class);
assertThat(metadata).has(Metadata.withGroup("hierarchical")
assertThat(metadata).has(Metadata.withGroup("hierarchical").fromSource(HierarchicalProperties.class));
assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class).withDefaultValue("one")
.fromSource(HierarchicalProperties.class));
assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class)
.withDefaultValue("one").fromSource(HierarchicalProperties.class));
assertThat(metadata).has(Metadata
.withProperty("hierarchical.second", String.class).withDefaultValue("two")
assertThat(metadata).has(Metadata.withProperty("hierarchical.second", String.class).withDefaultValue("two")
.fromSource(HierarchicalProperties.class));
assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class).withDefaultValue("three")
.fromSource(HierarchicalProperties.class));
assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class)
.withDefaultValue("three").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."));
}
@@ -180,11 +151,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
@@ -192,11 +162,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"));
}
@@ -205,12 +172,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.flag", Boolean.class)
.withDefaultValue(false).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).withDefaultValue(false)
.withNoDeprecation().fromSource(type));
}
@Test
@@ -218,10 +183,9 @@ 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)
.withDefaultValue(false).fromSource(type));
assertThat(metadata).has(
Metadata.withProperty("boxing.counter", Integer.class).fromSource(type));
assertThat(metadata)
.has(Metadata.withProperty("boxing.flag", Boolean.class).withDefaultValue(false).fromSource(type));
assertThat(metadata).has(Metadata.withProperty("boxing.counter", Integer.class).fromSource(type));
}
@Test
@@ -230,17 +194,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>>"));
}
@@ -248,38 +208,32 @@ 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 annotatedGetter() {
ConfigurationMetadata metadata = compile(AnnotatedGetter.class);
assertThat(metadata).has(Metadata.withGroup("specific").fromSource(AnnotatedGetter.class));
assertThat(metadata)
.has(Metadata.withGroup("specific").fromSource(AnnotatedGetter.class));
assertThat(metadata).has(Metadata.withProperty("specific.name", String.class)
.fromSource(AnnotatedGetter.class));
.has(Metadata.withProperty("specific.name", String.class).fromSource(AnnotatedGetter.class));
}
@Test
public void staticAccessor() {
ConfigurationMetadata metadata = compile(StaticAccessor.class);
assertThat(metadata)
.has(Metadata.withGroup("specific").fromSource(StaticAccessor.class));
assertThat(metadata).has(Metadata.withGroup("specific").fromSource(StaticAccessor.class));
assertThat(metadata).has(Metadata.withProperty("specific.counter", Integer.class)
.fromSource(StaticAccessor.class).withDefaultValue(42));
assertThat(metadata)
.doesNotHave(Metadata.withProperty("specific.name", String.class)
.fromSource(StaticAccessor.class));
.doesNotHave(Metadata.withProperty("specific.name", String.class).fromSource(StaticAccessor.class));
assertThat(metadata.getItems()).hasSize(2);
}
@@ -292,20 +246,17 @@ public class ConfigurationMetadataAnnotationProcessorTests
@Test
public void innerClassProperties() {
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"));
@@ -314,12 +265,11 @@ public class ConfigurationMetadataAnnotationProcessorTests
@Test
public void innerClassPropertiesHierarchical() {
ConfigurationMetadata metadata = compile(InnerClassHierarchicalProperties.class);
assertThat(metadata).has(Metadata.withGroup("config.foo")
.ofType(InnerClassHierarchicalProperties.Foo.class));
assertThat(metadata).has(Metadata.withGroup("config.foo.bar")
.ofType(InnerClassHierarchicalProperties.Bar.class));
assertThat(metadata).has(Metadata.withGroup("config.foo.bar.baz")
.ofType(InnerClassHierarchicalProperties.Foo.Baz.class));
assertThat(metadata).has(Metadata.withGroup("config.foo").ofType(InnerClassHierarchicalProperties.Foo.class));
assertThat(metadata)
.has(Metadata.withGroup("config.foo.bar").ofType(InnerClassHierarchicalProperties.Bar.class));
assertThat(metadata)
.has(Metadata.withGroup("config.foo.bar.baz").ofType(InnerClassHierarchicalProperties.Foo.Baz.class));
assertThat(metadata).has(Metadata.withProperty("config.foo.bar.baz.blah"));
assertThat(metadata).has(Metadata.withProperty("config.foo.bar.bling"));
}
@@ -335,16 +285,12 @@ public class ConfigurationMetadataAnnotationProcessorTests
@Test
public void nestedClassChildProperties() {
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
@@ -383,30 +329,25 @@ public class ConfigurationMetadataAnnotationProcessorTests
@Test
public void invalidDoubleRegistration() {
assertThatIllegalStateException()
.isThrownBy(() -> compile(InvalidDoubleRegistrationProperties.class))
assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDoubleRegistrationProperties.class))
.withMessageContaining("Compilation failed");
}
@Test
public void constructorParameterPropertyWithInvalidDefaultValueOnNumber() {
assertThatIllegalStateException()
.isThrownBy(() -> compile(InvalidDefaultValueNumberProperties.class))
assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueNumberProperties.class))
.withMessageContaining("Compilation failed");
}
@Test
public void constructorParameterPropertyWithInvalidDefaultValueOnFloatingPoint() {
assertThatIllegalStateException()
.isThrownBy(
() -> compile(InvalidDefaultValueFloatingPointProperties.class))
assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueFloatingPointProperties.class))
.withMessageContaining("Compilation failed");
}
@Test
public void constructorParameterPropertyWithInvalidDefaultValueOnCharacter() {
assertThatIllegalStateException()
.isThrownBy(() -> compile(InvalidDefaultValueCharacterProperties.class))
assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueCharacterProperties.class))
.withMessageContaining("Compilation failed");
}

View File

@@ -47,10 +47,8 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
@Test
public void constructorParameterSimpleProperty() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(
ownerElement, "theName");
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
assertThat(property.getName()).isEqualTo("theName");
assertThat(property.getSource()).hasToString("theName");
assertThat(property.getGetter().getSimpleName()).hasToString("getTheName");
@@ -62,10 +60,8 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
@Test
public void constructorParameterNestedPropertySameClass() throws IOException {
process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutableInnerClassProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(
ownerElement, "first");
TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
assertThat(property.getName()).isEqualTo("first");
assertThat(property.getSource()).hasToString("first");
assertThat(property.getGetter().getSimpleName()).hasToString("getFirst");
@@ -77,10 +73,8 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
@Test
public void constructorParameterNestedPropertyWithAnnotation() throws IOException {
process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutableInnerClassProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(
ownerElement, "third");
TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third");
assertThat(property.getName()).isEqualTo("third");
assertThat(property.getSource()).hasToString("third");
assertThat(property.getGetter().getSimpleName()).hasToString("getThird");
@@ -90,13 +84,10 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterSimplePropertyWithNoAccessorShouldBeExposed()
throws IOException {
public void constructorParameterSimplePropertyWithNoAccessorShouldBeExposed() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(
ownerElement, "counter");
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "counter");
assertThat(property.getName()).isEqualTo("counter");
assertThat(property.getSource()).hasToString("counter");
assertThat(property.getGetter()).isNull();
@@ -108,55 +99,43 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
@Test
public void constructorParameterMetadataSimpleProperty() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(
ownerElement, "counter");
assertItemMetadata(metadataEnv, property).isProperty().hasName("test.counter")
.hasType(Long.class).hasSourceType(ImmutableSimpleProperties.class)
.hasNoDescription().isNotDeprecated();
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "counter");
assertItemMetadata(metadataEnv, property).isProperty().hasName("test.counter").hasType(Long.class)
.hasSourceType(ImmutableSimpleProperties.class).hasNoDescription().isNotDeprecated();
});
}
@Test
public void constructorParameterMetadataNestedGroup() throws IOException {
process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutableInnerClassProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(
ownerElement, "first");
TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first")
.hasType(
"org.springframework.boot.configurationsample.immutable.ImmutableInnerClassProperties$Foo")
.hasSourceType(ImmutableInnerClassProperties.class)
.hasSourceMethod("getFirst()").hasNoDescription().isNotDeprecated();
.hasType("org.springframework.boot.configurationsample.immutable.ImmutableInnerClassProperties$Foo")
.hasSourceType(ImmutableInnerClassProperties.class).hasSourceMethod("getFirst()").hasNoDescription()
.isNotDeprecated();
});
}
@Test
public void constructorParameterDeprecatedPropertyOnGetter() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutableSimpleProperties.class);
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ExecutableElement getter = getMethod(ownerElement, "isFlag");
VariableElement field = getField(ownerElement, "flag");
VariableElement constructorParameter = getConstructorParameter(ownerElement,
"flag");
ConstructorParameterPropertyDescriptor property = new ConstructorParameterPropertyDescriptor(
ownerElement, null, constructorParameter, "flag", field.asType(),
field, getter, null);
assertItemMetadata(metadataEnv, property).isProperty()
.isDeprecatedWithNoInformation();
VariableElement constructorParameter = getConstructorParameter(ownerElement, "flag");
ConstructorParameterPropertyDescriptor property = new ConstructorParameterPropertyDescriptor(ownerElement,
null, constructorParameter, "flag", field.asType(), field, getter, null);
assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation();
});
}
@Test
public void constructorParameterPropertyWithDescription() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(
ownerElement, "theName");
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
assertItemMetadata(metadataEnv, property).isProperty()
.hasDescription("The name of this simple properties.");
});
@@ -165,154 +144,86 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
@Test
public void constructorParameterPropertyWithDefaultValue() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(
ownerElement, "theName");
assertItemMetadata(metadataEnv, property).isProperty()
.hasDefaultValue("boot");
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
assertItemMetadata(metadataEnv, property).isProperty().hasDefaultValue("boot");
});
}
@Test
public void constructorParameterPropertyWithPrimitiveTypes() throws IOException {
process(ImmutablePrimitiveProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutablePrimitiveProperties.class);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "flag"))
.hasDefaultValue(false);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "octet")).hasDefaultValue(0);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "letter"))
.hasDefaultValue(null);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "number")).hasDefaultValue(0);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(0);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(0L);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "percentage"))
.hasDefaultValue(0);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "ratio")).hasDefaultValue(0D);
TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveProperties.class);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(false);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")).hasDefaultValue(0);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue(null);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")).hasDefaultValue(0);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(0);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(0L);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "ratio")).hasDefaultValue(0D);
});
}
@Test
public void constructorParameterPropertyWithPrimitiveTypesAndDefaultValues()
throws IOException {
process(ImmutablePrimitiveWithDefaultsProperties.class,
(roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(
ImmutablePrimitiveWithDefaultsProperties.class);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "flag"))
.hasDefaultValue(true);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "octet"))
.hasDefaultValue(120);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "letter"))
.hasDefaultValue("a");
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "number"))
.hasDefaultValue(1000);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "counter"))
.hasDefaultValue(42);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "value"))
.hasDefaultValue(2000);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "percentage"))
.hasDefaultValue(0.5);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "ratio"))
.hasDefaultValue(42.42);
});
public void constructorParameterPropertyWithPrimitiveTypesAndDefaultValues() throws IOException {
process(ImmutablePrimitiveWithDefaultsProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWithDefaultsProperties.class);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")).hasDefaultValue(120);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue("a");
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")).hasDefaultValue(1000);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(42);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(2000);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0.5);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "ratio")).hasDefaultValue(42.42);
});
}
@Test
public void constructorParameterPropertyWithPrimitiveWrapperTypesAndDefaultValues()
throws IOException {
process(ImmutablePrimitiveWrapperWithDefaultsProperties.class,
(roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(
ImmutablePrimitiveWrapperWithDefaultsProperties.class);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "flag"))
.hasDefaultValue(true);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "octet"))
.hasDefaultValue(120);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "letter"))
.hasDefaultValue("a");
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "number"))
.hasDefaultValue(1000);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "counter"))
.hasDefaultValue(42);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "value"))
.hasDefaultValue(2000);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "percentage"))
.hasDefaultValue(0.5);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "ratio"))
.hasDefaultValue(42.42);
});
public void constructorParameterPropertyWithPrimitiveWrapperTypesAndDefaultValues() throws IOException {
process(ImmutablePrimitiveWrapperWithDefaultsProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWrapperWithDefaultsProperties.class);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")).hasDefaultValue(120);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue("a");
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")).hasDefaultValue(1000);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(42);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(2000);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0.5);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "ratio")).hasDefaultValue(42.42);
});
}
@Test
public void constructorParameterPropertyWithCollectionTypesAndDefaultValues()
throws IOException {
public void constructorParameterPropertyWithCollectionTypesAndDefaultValues() throws IOException {
process(ImmutableCollectionProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(ImmutableCollectionProperties.class);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "names"))
.hasDefaultValue(null);
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "flags"))
.hasDefaultValue(Arrays.asList(true, false));
assertItemMetadata(metadataEnv,
createPropertyDescriptor(ownerElement, "durations"))
.hasDefaultValue(Arrays.asList("10s", "1m", "1h"));
TypeElement ownerElement = roundEnv.getRootElement(ImmutableCollectionProperties.class);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "names")).hasDefaultValue(null);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flags"))
.hasDefaultValue(Arrays.asList(true, false));
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "durations"))
.hasDefaultValue(Arrays.asList("10s", "1m", "1h"));
});
}
protected ConstructorParameterPropertyDescriptor createPropertyDescriptor(
TypeElement ownerElement, String name) {
VariableElement constructorParameter = getConstructorParameter(ownerElement,
name);
protected ConstructorParameterPropertyDescriptor createPropertyDescriptor(TypeElement ownerElement, String name) {
VariableElement constructorParameter = getConstructorParameter(ownerElement, name);
VariableElement field = getField(ownerElement, name);
ExecutableElement getter = getMethod(ownerElement,
createAccessorMethodName("get", name));
ExecutableElement setter = getMethod(ownerElement,
createAccessorMethodName("set", name));
return new ConstructorParameterPropertyDescriptor(ownerElement, null,
constructorParameter, name, field.asType(), field, getter, setter);
ExecutableElement getter = getMethod(ownerElement, createAccessorMethodName("get", name));
ExecutableElement setter = getMethod(ownerElement, createAccessorMethodName("set", name));
return new ConstructorParameterPropertyDescriptor(ownerElement, null, constructorParameter, name,
field.asType(), field, getter, setter);
}
private VariableElement getConstructorParameter(TypeElement ownerElement,
String name) {
List<ExecutableElement> constructors = ElementFilter
.constructorsIn(ownerElement.getEnclosedElements()).stream()
.filter((constructor) -> !constructor.getParameters().isEmpty())
.collect(Collectors.toList());
private VariableElement getConstructorParameter(TypeElement ownerElement, String name) {
List<ExecutableElement> constructors = ElementFilter.constructorsIn(ownerElement.getEnclosedElements()).stream()
.filter((constructor) -> !constructor.getParameters().isEmpty()).collect(Collectors.toList());
if (constructors.size() != 1) {
throw new IllegalStateException(
"No candidate constructor for " + ownerElement);
throw new IllegalStateException("No candidate constructor for " + ownerElement);
}
return constructors.get(0).getParameters().stream()
.filter((parameter) -> parameter.getSimpleName().toString().equals(name))
.findFirst().orElse(null);
.filter((parameter) -> parameter.getSimpleName().toString().equals(name)).findFirst().orElse(null);
}
}

View File

@@ -42,8 +42,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
@Test
public void simpleEndpoint() {
ConfigurationMetadata metadata = compile(SimpleEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.simple")
.fromSource(SimpleEndpoint.class));
assertThat(metadata).has(Metadata.withGroup("management.endpoint.simple").fromSource(SimpleEndpoint.class));
assertThat(metadata).has(enabledFlag("simple", true));
assertThat(metadata).has(cacheTtl("simple"));
assertThat(metadata.getItems()).hasSize(3);
@@ -52,8 +51,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
@Test
public void disableEndpoint() {
ConfigurationMetadata metadata = compile(DisabledEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.disabled")
.fromSource(DisabledEndpoint.class));
assertThat(metadata).has(Metadata.withGroup("management.endpoint.disabled").fromSource(DisabledEndpoint.class));
assertThat(metadata).has(enabledFlag("disabled", false));
assertThat(metadata.getItems()).hasSize(2);
}
@@ -61,8 +59,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
@Test
public void enabledEndpoint() {
ConfigurationMetadata metadata = compile(EnabledEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.enabled")
.fromSource(EnabledEndpoint.class));
assertThat(metadata).has(Metadata.withGroup("management.endpoint.enabled").fromSource(EnabledEndpoint.class));
assertThat(metadata).has(enabledFlag("enabled", true));
assertThat(metadata.getItems()).hasSize(2);
}
@@ -70,11 +67,10 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
@Test
public void customPropertiesEndpoint() {
ConfigurationMetadata metadata = compile(CustomPropertiesEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.customprops")
.fromSource(CustomPropertiesEndpoint.class));
assertThat(metadata)
.has(Metadata.withProperty("management.endpoint.customprops.name")
.ofType(String.class).withDefaultValue("test"));
.has(Metadata.withGroup("management.endpoint.customprops").fromSource(CustomPropertiesEndpoint.class));
assertThat(metadata).has(Metadata.withProperty("management.endpoint.customprops.name").ofType(String.class)
.withDefaultValue("test"));
assertThat(metadata).has(enabledFlag("customprops", true));
assertThat(metadata).has(cacheTtl("customprops"));
assertThat(metadata.getItems()).hasSize(4);
@@ -83,8 +79,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
@Test
public void specificEndpoint() {
ConfigurationMetadata metadata = compile(SpecificEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific")
.fromSource(SpecificEndpoint.class));
assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class));
assertThat(metadata).has(enabledFlag("specific", true));
assertThat(metadata).has(cacheTtl("specific"));
assertThat(metadata.getItems()).hasSize(3);
@@ -93,27 +88,26 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
@Test
public void camelCaseEndpoint() {
ConfigurationMetadata metadata = compile(CamelCaseEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.pascal-case")
.fromSource(CamelCaseEndpoint.class));
assertThat(metadata)
.has(Metadata.withGroup("management.endpoint.pascal-case").fromSource(CamelCaseEndpoint.class));
assertThat(metadata).has(enabledFlag("PascalCase", "pascal-case", true));
assertThat(metadata.getItems()).hasSize(2);
}
@Test
public void incrementalEndpointBuildChangeGeneralEnabledFlag() throws Exception {
TestProject project = new TestProject(this.temporaryFolder,
IncrementalEndpoint.class);
TestProject project = new TestProject(this.temporaryFolder, IncrementalEndpoint.class);
ConfigurationMetadata metadata = project.fullBuild();
assertThat(metadata).has(Metadata.withGroup("management.endpoint.incremental")
.fromSource(IncrementalEndpoint.class));
assertThat(metadata)
.has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class));
assertThat(metadata).has(enabledFlag("incremental", true));
assertThat(metadata).has(cacheTtl("incremental"));
assertThat(metadata.getItems()).hasSize(3);
project.replaceText(IncrementalEndpoint.class, "id = \"incremental\"",
"id = \"incremental\", enableByDefault = false");
metadata = project.incrementalBuild(IncrementalEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.incremental")
.fromSource(IncrementalEndpoint.class));
assertThat(metadata)
.has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class));
assertThat(metadata).has(enabledFlag("incremental", false));
assertThat(metadata).has(cacheTtl("incremental"));
assertThat(metadata.getItems()).hasSize(3);
@@ -121,61 +115,50 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
@Test
public void incrementalEndpointBuildChangeCacheFlag() throws Exception {
TestProject project = new TestProject(this.temporaryFolder,
IncrementalEndpoint.class);
TestProject project = new TestProject(this.temporaryFolder, IncrementalEndpoint.class);
ConfigurationMetadata metadata = project.fullBuild();
assertThat(metadata).has(Metadata.withGroup("management.endpoint.incremental")
.fromSource(IncrementalEndpoint.class));
assertThat(metadata)
.has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class));
assertThat(metadata).has(enabledFlag("incremental", true));
assertThat(metadata).has(cacheTtl("incremental"));
assertThat(metadata.getItems()).hasSize(3);
project.replaceText(IncrementalEndpoint.class, "@Nullable String param",
"String param");
project.replaceText(IncrementalEndpoint.class, "@Nullable String param", "String param");
metadata = project.incrementalBuild(IncrementalEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.incremental")
.fromSource(IncrementalEndpoint.class));
assertThat(metadata)
.has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class));
assertThat(metadata).has(enabledFlag("incremental", true));
assertThat(metadata.getItems()).hasSize(2);
}
@Test
public void incrementalEndpointBuildEnableSpecificEndpoint() throws Exception {
TestProject project = new TestProject(this.temporaryFolder,
SpecificEndpoint.class);
TestProject project = new TestProject(this.temporaryFolder, SpecificEndpoint.class);
ConfigurationMetadata metadata = project.fullBuild();
assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific")
.fromSource(SpecificEndpoint.class));
assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class));
assertThat(metadata).has(enabledFlag("specific", true));
assertThat(metadata).has(cacheTtl("specific"));
assertThat(metadata.getItems()).hasSize(3);
project.replaceText(SpecificEndpoint.class, "enableByDefault = true",
"enableByDefault = false");
project.replaceText(SpecificEndpoint.class, "enableByDefault = true", "enableByDefault = false");
metadata = project.incrementalBuild(SpecificEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific")
.fromSource(SpecificEndpoint.class));
assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class));
assertThat(metadata).has(enabledFlag("specific", false));
assertThat(metadata).has(cacheTtl("specific"));
assertThat(metadata.getItems()).hasSize(3);
}
private Metadata.MetadataItemCondition enabledFlag(String endpointId,
String endpointSuffix, Boolean defaultValue) {
return Metadata
.withEnabledFlag("management.endpoint." + endpointSuffix + ".enabled")
.withDefaultValue(defaultValue).withDescription(
String.format("Whether to enable the %s endpoint.", endpointId));
private Metadata.MetadataItemCondition enabledFlag(String endpointId, String endpointSuffix, Boolean defaultValue) {
return Metadata.withEnabledFlag("management.endpoint." + endpointSuffix + ".enabled")
.withDefaultValue(defaultValue)
.withDescription(String.format("Whether to enable the %s endpoint.", endpointId));
}
private Metadata.MetadataItemCondition enabledFlag(String endpointId,
Boolean defaultValue) {
private Metadata.MetadataItemCondition enabledFlag(String endpointId, Boolean defaultValue) {
return enabledFlag(endpointId, endpointId, defaultValue);
}
private Metadata.MetadataItemCondition cacheTtl(String endpointId) {
return Metadata
.withProperty("management.endpoint." + endpointId + ".cache.time-to-live")
.ofType(Duration.class).withDefaultValue("0ms")
.withDescription("Maximum time that a response can be cached.");
return Metadata.withProperty("management.endpoint." + endpointId + ".cache.time-to-live").ofType(Duration.class)
.withDefaultValue("0ms").withDescription("Maximum time that a response can be cached.");
}
}

View File

@@ -39,90 +39,74 @@ public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationT
@Test
public void simpleGenericProperties() {
ConfigurationMetadata metadata = compile(AbstractGenericProperties.class,
SimpleGenericProperties.class);
assertThat(metadata).has(
Metadata.withGroup("generic").fromSource(SimpleGenericProperties.class));
ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, SimpleGenericProperties.class);
assertThat(metadata).has(Metadata.withGroup("generic").fromSource(SimpleGenericProperties.class));
assertThat(metadata).has(Metadata.withProperty("generic.name", String.class)
.fromSource(SimpleGenericProperties.class)
.withDescription("Generic name.").withDefaultValue(null));
.fromSource(SimpleGenericProperties.class).withDescription("Generic name.").withDefaultValue(null));
assertThat(metadata).has(Metadata
.withProperty("generic.mappings",
"java.util.Map<java.lang.Integer,java.time.Duration>")
.fromSource(SimpleGenericProperties.class)
.withDescription("Generic mappings.").withDefaultValue(null));
.withProperty("generic.mappings", "java.util.Map<java.lang.Integer,java.time.Duration>")
.fromSource(SimpleGenericProperties.class).withDescription("Generic mappings.").withDefaultValue(null));
assertThat(metadata.getItems()).hasSize(3);
}
@Test
public void complexGenericProperties() {
ConfigurationMetadata metadata = compile(ComplexGenericProperties.class);
assertThat(metadata).has(
Metadata.withGroup("generic").fromSource(ComplexGenericProperties.class));
assertThat(metadata).has(
Metadata.withGroup("generic.test").ofType(UpperBoundGenericPojo.class)
.fromSource(ComplexGenericProperties.class));
assertThat(metadata).has(Metadata
.withProperty("generic.test.mappings",
"java.util.Map<java.lang.Enum<T>,java.lang.String>")
.fromSource(UpperBoundGenericPojo.class));
assertThat(metadata).has(Metadata.withGroup("generic").fromSource(ComplexGenericProperties.class));
assertThat(metadata).has(Metadata.withGroup("generic.test").ofType(UpperBoundGenericPojo.class)
.fromSource(ComplexGenericProperties.class));
assertThat(metadata)
.has(Metadata.withProperty("generic.test.mappings", "java.util.Map<java.lang.Enum<T>,java.lang.String>")
.fromSource(UpperBoundGenericPojo.class));
assertThat(metadata.getItems()).hasSize(3);
}
@Test
public void unresolvedGenericProperties() {
ConfigurationMetadata metadata = compile(AbstractGenericProperties.class,
UnresolvedGenericProperties.class);
assertThat(metadata).has(Metadata.withGroup("generic")
.fromSource(UnresolvedGenericProperties.class));
ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, UnresolvedGenericProperties.class);
assertThat(metadata).has(Metadata.withGroup("generic").fromSource(UnresolvedGenericProperties.class));
assertThat(metadata).has(Metadata.withProperty("generic.name", String.class)
.fromSource(UnresolvedGenericProperties.class)
.withDescription("Generic name.").withDefaultValue(null));
assertThat(metadata).has(Metadata
.withProperty("generic.mappings",
"java.util.Map<java.lang.Number,java.lang.Object>")
.fromSource(UnresolvedGenericProperties.class)
.withDescription("Generic mappings.").withDefaultValue(null));
.fromSource(UnresolvedGenericProperties.class).withDescription("Generic name.").withDefaultValue(null));
assertThat(metadata)
.has(Metadata.withProperty("generic.mappings", "java.util.Map<java.lang.Number,java.lang.Object>")
.fromSource(UnresolvedGenericProperties.class).withDescription("Generic mappings.")
.withDefaultValue(null));
assertThat(metadata.getItems()).hasSize(3);
}
@Test
public void genericTypes() {
ConfigurationMetadata metadata = compile(GenericConfig.class);
assertThat(metadata).has(Metadata.withGroup("generic").ofType(
"org.springframework.boot.configurationsample.generic.GenericConfig"));
assertThat(metadata).has(Metadata.withGroup("generic.foo").ofType(
"org.springframework.boot.configurationsample.generic.GenericConfig$Foo"));
assertThat(metadata).has(Metadata.withGroup("generic.foo.bar").ofType(
"org.springframework.boot.configurationsample.generic.GenericConfig$Bar"));
assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz").ofType(
"org.springframework.boot.configurationsample.generic.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.generic.GenericConfig$Bar<java.lang.Integer>>")
assertThat(metadata).has(Metadata.withGroup("generic")
.ofType("org.springframework.boot.configurationsample.generic.GenericConfig"));
assertThat(metadata).has(Metadata.withGroup("generic.foo")
.ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Foo"));
assertThat(metadata).has(Metadata.withGroup("generic.foo.bar")
.ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar"));
assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz")
.ofType("org.springframework.boot.configurationsample.generic.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.generic.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() {
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);
}

View File

@@ -29,21 +29,18 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class ImmutablePropertiesMetadataGenerationTests
extends AbstractMetadataGenerationTests {
public class ImmutablePropertiesMetadataGenerationTests extends AbstractMetadataGenerationTests {
@Test
public void immutableSimpleProperties() {
ConfigurationMetadata metadata = compile(ImmutableSimpleProperties.class);
assertThat(metadata).has(Metadata.withGroup("immutable")
.fromSource(ImmutableSimpleProperties.class));
assertThat(metadata).has(Metadata.withProperty("immutable.the-name", String.class)
.fromSource(ImmutableSimpleProperties.class)
.withDescription("The name of this simple properties.")
.withDefaultValue("boot"));
assertThat(metadata).has(Metadata.withProperty("immutable.flag", Boolean.class)
.withDefaultValue(false).fromSource(ImmutableSimpleProperties.class)
.withDescription("A simple flag.").withDeprecation(null, null));
assertThat(metadata).has(Metadata.withGroup("immutable").fromSource(ImmutableSimpleProperties.class));
assertThat(metadata).has(
Metadata.withProperty("immutable.the-name", String.class).fromSource(ImmutableSimpleProperties.class)
.withDescription("The name of this simple properties.").withDefaultValue("boot"));
assertThat(metadata).has(Metadata.withProperty("immutable.flag", Boolean.class).withDefaultValue(false)
.fromSource(ImmutableSimpleProperties.class).withDescription("A simple flag.")
.withDeprecation(null, null));
assertThat(metadata).has(Metadata.withProperty("immutable.comparator"));
assertThat(metadata).has(Metadata.withProperty("immutable.counter"));
assertThat(metadata.getItems()).hasSize(5);

View File

@@ -31,79 +31,65 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class IncrementalBuildMetadataGenerationTests
extends AbstractMetadataGenerationTests {
public class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGenerationTests {
@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).withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("bar.counter")
.fromSource(BarProperties.class).withDefaultValue(0));
assertThat(metadata)
.has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0));
assertThat(metadata)
.has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0));
metadata = project.incrementalBuild(BarProperties.class);
assertThat(metadata).has(Metadata.withProperty("foo.counter")
.fromSource(FooProperties.class).withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("bar.counter")
.fromSource(BarProperties.class).withDefaultValue(0));
project.addSourceCode(BarProperties.class,
BarProperties.class.getResourceAsStream("BarProperties.snippet"));
assertThat(metadata)
.has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0));
assertThat(metadata)
.has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0));
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").withDefaultValue(0));
assertThat(metadata)
.has(Metadata.withProperty("bar.counter").withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("foo.counter").withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("bar.counter").withDefaultValue(0));
project.revert(BarProperties.class);
metadata = project.incrementalBuild(BarProperties.class);
assertThat(metadata).isNotEqualTo(Metadata.withProperty("bar.extra"));
assertThat(metadata)
.has(Metadata.withProperty("foo.counter").withDefaultValue(0));
assertThat(metadata)
.has(Metadata.withProperty("bar.counter").withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("foo.counter").withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("bar.counter").withDefaultValue(0));
}
@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").withDefaultValue(0));
assertThat(metadata)
.has(Metadata.withProperty("bar.counter").withDefaultValue(0));
project.replaceText(BarProperties.class, "@ConfigurationProperties",
"//@ConfigurationProperties");
assertThat(metadata).has(Metadata.withProperty("foo.counter").withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("bar.counter").withDefaultValue(0));
project.replaceText(BarProperties.class, "@ConfigurationProperties", "//@ConfigurationProperties");
metadata = project.incrementalBuild(BarProperties.class);
assertThat(metadata)
.has(Metadata.withProperty("foo.counter").withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("foo.counter").withDefaultValue(0));
assertThat(metadata).isNotEqualTo(Metadata.withProperty("bar.counter"));
}
@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).withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("bar.counter")
.fromSource(BarProperties.class).withDefaultValue(0));
assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter")
.fromSource(RenamedBarProperties.class));
assertThat(metadata)
.has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0));
assertThat(metadata)
.has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0));
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).withDefaultValue(0));
assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter")
.fromSource(BarProperties.class).withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("bar.counter").withDefaultValue(0)
.fromSource(RenamedBarProperties.class));
assertThat(metadata)
.has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0));
assertThat(metadata)
.doesNotHave(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0));
assertThat(metadata)
.has(Metadata.withProperty("bar.counter").withDefaultValue(0).fromSource(RenamedBarProperties.class));
}
}

View File

@@ -42,10 +42,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void javaBeanSimpleProperty() throws IOException {
process(SimpleTypeProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(SimpleTypeProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"myString");
TypeElement ownerElement = roundEnv.getRootElement(SimpleTypeProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "myString");
assertThat(property.getName()).isEqualTo("myString");
assertThat(property.getSource()).isSameAs(property.getGetter());
assertThat(property.getGetter().getSimpleName()).hasToString("getMyString");
@@ -58,10 +56,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void javaBeanCollectionProperty() throws IOException {
process(SimpleCollectionProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(SimpleCollectionProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"doubles");
TypeElement ownerElement = roundEnv.getRootElement(SimpleCollectionProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "doubles");
assertThat(property.getName()).isEqualTo("doubles");
assertThat(property.getGetter().getSimpleName()).hasToString("getDoubles");
assertThat(property.getSetter()).isNull();
@@ -73,10 +69,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void javaBeanNestedPropertySameClass() throws IOException {
process(InnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(InnerClassProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"first");
TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
assertThat(property.getName()).isEqualTo("first");
assertThat(property.getGetter().getSimpleName()).hasToString("getFirst");
assertThat(property.getSetter()).isNull();
@@ -88,10 +82,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void javaBeanNestedPropertyWithAnnotation() throws IOException {
process(InnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(InnerClassProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"third");
TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third");
assertThat(property.getName()).isEqualTo("third");
assertThat(property.getGetter().getSimpleName()).hasToString("getThird");
assertThat(property.getSetter()).isNull();
@@ -101,14 +93,13 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanSimplePropertyWithOnlyGetterShouldNotBeExposed()
throws IOException {
public void javaBeanSimplePropertyWithOnlyGetterShouldNotBeExposed() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
ExecutableElement getter = getMethod(ownerElement, "getSize");
VariableElement field = getField(ownerElement, "size");
JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor(
ownerElement, getter, getter, "size", field.asType(), field, null);
JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor(ownerElement, getter, getter, "size",
field.asType(), field, null);
assertThat(property.getName()).isEqualTo("size");
assertThat(property.getSource()).isSameAs(property.getGetter());
assertThat(property.getGetter().getSimpleName()).hasToString("getSize");
@@ -119,14 +110,12 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanSimplePropertyWithOnlySetterShouldNotBeExposed()
throws IOException {
public void javaBeanSimplePropertyWithOnlySetterShouldNotBeExposed() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
VariableElement field = getField(ownerElement, "counter");
JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor(
ownerElement, null, null, "counter", field.asType(), field,
getMethod(ownerElement, "setCounter"));
JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor(ownerElement, null, null, "counter",
field.asType(), field, getMethod(ownerElement, "setCounter"));
assertThat(property.getName()).isEqualTo("counter");
assertThat(property.getSource()).isSameAs(property.getGetter());
assertThat(property.getGetter()).isNull();
@@ -139,55 +128,43 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void javaBeanMetadataSimpleProperty() throws IOException {
process(SimpleTypeProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(SimpleTypeProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"myString");
assertItemMetadata(metadataEnv, property).isProperty()
.hasName("test.my-string").hasType(String.class)
.hasSourceType(SimpleTypeProperties.class).hasNoDescription()
.isNotDeprecated();
TypeElement ownerElement = roundEnv.getRootElement(SimpleTypeProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "myString");
assertItemMetadata(metadataEnv, property).isProperty().hasName("test.my-string").hasType(String.class)
.hasSourceType(SimpleTypeProperties.class).hasNoDescription().isNotDeprecated();
});
}
@Test
public void javaBeanMetadataCollectionProperty() throws IOException {
process(SimpleCollectionProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(SimpleCollectionProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"doubles");
TypeElement ownerElement = roundEnv.getRootElement(SimpleCollectionProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "doubles");
assertItemMetadata(metadataEnv, property).isProperty().hasName("test.doubles")
.hasType("java.util.List<java.lang.Double>")
.hasSourceType(SimpleCollectionProperties.class).hasNoDescription()
.isNotDeprecated();
.hasType("java.util.List<java.lang.Double>").hasSourceType(SimpleCollectionProperties.class)
.hasNoDescription().isNotDeprecated();
});
}
@Test
public void javaBeanMetadataNestedGroup() throws IOException {
process(InnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(InnerClassProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"first");
TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first")
.hasType(
"org.springframework.boot.configurationsample.specific.InnerClassProperties$Foo")
.hasSourceType(InnerClassProperties.class)
.hasSourceMethod("getFirst()").hasNoDescription().isNotDeprecated();
.hasType("org.springframework.boot.configurationsample.specific.InnerClassProperties$Foo")
.hasSourceType(InnerClassProperties.class).hasSourceMethod("getFirst()").hasNoDescription()
.isNotDeprecated();
});
}
@Test
public void javaBeanMetadataNotACandidatePropertyShouldReturnNull()
throws IOException {
public void javaBeanMetadataNotACandidatePropertyShouldReturnNull() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
VariableElement field = getField(ownerElement, "counter");
JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor(
ownerElement, null, null, "counter", field.asType(), field,
getMethod(ownerElement, "setCounter"));
JavaBeanPropertyDescriptor property = new JavaBeanPropertyDescriptor(ownerElement, null, null, "counter",
field.asType(), field, getMethod(ownerElement, "setCounter"));
assertThat(property.resolveItemMetadata("test", metadataEnv)).isNull();
});
}
@@ -199,22 +176,17 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
(roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(
org.springframework.boot.configurationsample.simple.DeprecatedProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(
ownerElement, "name");
assertItemMetadata(metadataEnv, property).isProperty()
.isDeprecatedWithNoInformation();
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name");
assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation();
});
}
@Test
public void javaBeanMetadataDeprecatedPropertyWithAnnotation() throws IOException {
process(DeprecatedSingleProperty.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(DeprecatedSingleProperty.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"name");
assertItemMetadata(metadataEnv, property).isProperty()
.isDeprecatedWithReason("renamed")
TypeElement ownerElement = roundEnv.getRootElement(DeprecatedSingleProperty.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name");
assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithReason("renamed")
.isDeprecatedWithReplacement("singledeprecated.new-name");
});
}
@@ -223,10 +195,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
public void javaBeanDeprecatedPropertyOnGetter() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"flag", "isFlag", "setFlag");
assertItemMetadata(metadataEnv, property).isProperty()
.isDeprecatedWithNoInformation();
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "flag", "isFlag", "setFlag");
assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation();
});
}
@@ -234,10 +204,8 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
public void javaBeanDeprecatedPropertyOnSetter() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"theName");
assertItemMetadata(metadataEnv, property).isProperty()
.isDeprecatedWithNoInformation();
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation();
});
}
@@ -245,8 +213,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
public void javaBeanPropertyWithDescription() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"theName");
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
assertItemMetadata(metadataEnv, property).isProperty()
.hasDescription("The name of this simple properties.");
});
@@ -256,27 +223,22 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
public void javaBeanPropertyWithDefaultValue() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"theName");
assertItemMetadata(metadataEnv, property).isProperty()
.hasDefaultValue("boot");
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
assertItemMetadata(metadataEnv, property).isProperty().hasDefaultValue("boot");
});
}
protected JavaBeanPropertyDescriptor createPropertyDescriptor(
TypeElement ownerElement, String name) {
return createPropertyDescriptor(ownerElement, name,
createAccessorMethodName("get", name),
protected JavaBeanPropertyDescriptor createPropertyDescriptor(TypeElement ownerElement, String name) {
return createPropertyDescriptor(ownerElement, name, createAccessorMethodName("get", name),
createAccessorMethodName("set", name));
}
protected JavaBeanPropertyDescriptor createPropertyDescriptor(
TypeElement ownerElement, String name, String getterName, String setterName) {
protected JavaBeanPropertyDescriptor createPropertyDescriptor(TypeElement ownerElement, String name,
String getterName, String setterName) {
ExecutableElement getter = getMethod(ownerElement, getterName);
ExecutableElement setter = getMethod(ownerElement, setterName);
VariableElement field = getField(ownerElement, name);
return new JavaBeanPropertyDescriptor(ownerElement, null, getter, name,
getter.getReturnType(), field, setter);
return new JavaBeanPropertyDescriptor(ownerElement, null, getter, name, getter.getReturnType(), field, setter);
}
}

View File

@@ -55,63 +55,51 @@ public class LombokMetadataGenerationTests extends AbstractMetadataGenerationTes
@Test
public void lombokExplicitProperties() {
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() {
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
@@ -124,43 +112,38 @@ public class LombokMetadataGenerationTests extends AbstractMetadataGenerationTes
@Test
public void lombokInnerClassWithGetterProperties() {
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);
}
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);
}

View File

@@ -45,10 +45,8 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void lombokSimpleProperty() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"name");
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name");
assertThat(property.getName()).isEqualTo("name");
assertThat(property.getSource()).isSameAs(property.getField());
assertThat(property.getField().getSimpleName()).hasToString("name");
@@ -60,10 +58,8 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void lombokCollectionProperty() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"items");
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "items");
assertThat(property.getName()).isEqualTo("items");
assertThat(property.getSource()).isSameAs(property.getField());
assertThat(property.getField().getSimpleName()).hasToString("items");
@@ -75,10 +71,8 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void lombokNestedPropertySameClass() throws IOException {
process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokInnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"first");
TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
assertThat(property.getName()).isEqualTo("first");
assertThat(property.getSource()).isSameAs(property.getField());
assertThat(property.getField().getSimpleName()).hasToString("first");
@@ -90,10 +84,8 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void lombokNestedPropertyWithAnnotation() throws IOException {
process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokInnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"third");
TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third");
assertThat(property.getName()).isEqualTo("third");
assertThat(property.getSource()).isSameAs(property.getField());
assertThat(property.getField().getSimpleName()).hasToString("third");
@@ -103,52 +95,40 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokSimplePropertyWithOnlyGetterOnClassShouldNotBeExposed()
throws IOException {
public void lombokSimplePropertyWithOnlyGetterOnClassShouldNotBeExposed() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"ignored");
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored");
assertThat(property.isProperty(metadataEnv)).isFalse();
assertThat(property.isNested(metadataEnv)).isFalse();
});
}
@Test
public void lombokSimplePropertyWithOnlyGetterOnDataClassShouldNotBeExposed()
throws IOException {
public void lombokSimplePropertyWithOnlyGetterOnDataClassShouldNotBeExposed() throws IOException {
process(LombokSimpleDataProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokSimpleDataProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"ignored");
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleDataProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored");
assertThat(property.isProperty(metadataEnv)).isFalse();
assertThat(property.isNested(metadataEnv)).isFalse();
});
}
@Test
public void lombokSimplePropertyWithOnlyGetterOnFieldShouldNotBeExposed()
throws IOException {
public void lombokSimplePropertyWithOnlyGetterOnFieldShouldNotBeExposed() throws IOException {
process(LombokExplicitProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokExplicitProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"ignoredOnlyGetter");
TypeElement ownerElement = roundEnv.getRootElement(LombokExplicitProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignoredOnlyGetter");
assertThat(property.isProperty(metadataEnv)).isFalse();
assertThat(property.isNested(metadataEnv)).isFalse();
});
}
@Test
public void lombokSimplePropertyWithOnlySetterOnFieldShouldNotBeExposed()
throws IOException {
public void lombokSimplePropertyWithOnlySetterOnFieldShouldNotBeExposed() throws IOException {
process(LombokExplicitProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokExplicitProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"ignoredOnlySetter");
TypeElement ownerElement = roundEnv.getRootElement(LombokExplicitProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignoredOnlySetter");
assertThat(property.isProperty(metadataEnv)).isFalse();
assertThat(property.isNested(metadataEnv)).isFalse();
});
@@ -157,70 +137,56 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void lombokMetadataSimpleProperty() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"description");
assertItemMetadata(metadataEnv, property).isProperty()
.hasName("test.description").hasType(String.class)
.hasSourceType(LombokSimpleProperties.class).hasNoDescription()
.isNotDeprecated();
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "description");
assertItemMetadata(metadataEnv, property).isProperty().hasName("test.description").hasType(String.class)
.hasSourceType(LombokSimpleProperties.class).hasNoDescription().isNotDeprecated();
});
}
@Test
public void lombokMetadataCollectionProperty() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"items");
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "items");
assertItemMetadata(metadataEnv, property).isProperty().hasName("test.items")
.hasType("java.util.List<java.lang.String>")
.hasSourceType(LombokSimpleProperties.class).hasNoDescription()
.isNotDeprecated();
.hasType("java.util.List<java.lang.String>").hasSourceType(LombokSimpleProperties.class)
.hasNoDescription().isNotDeprecated();
});
}
@Test
public void lombokMetadataNestedGroup() throws IOException {
process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokInnerClassProperties.class);
TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class);
VariableElement field = getField(ownerElement, "third");
ExecutableElement getter = getMethod(ownerElement, "getThird");
LombokPropertyDescriptor property = new LombokPropertyDescriptor(ownerElement,
null, field, "third", field.asType(), getter, null);
LombokPropertyDescriptor property = new LombokPropertyDescriptor(ownerElement, null, field, "third",
field.asType(), getter, null);
assertItemMetadata(metadataEnv, property).isGroup().hasName("test.third")
.hasType(
"org.springframework.boot.configurationsample.lombok.SimpleLombokPojo")
.hasSourceType(LombokInnerClassProperties.class)
.hasSourceMethod("getThird()").hasNoDescription().isNotDeprecated();
.hasType("org.springframework.boot.configurationsample.lombok.SimpleLombokPojo")
.hasSourceType(LombokInnerClassProperties.class).hasSourceMethod("getThird()").hasNoDescription()
.isNotDeprecated();
});
}
@Test
public void lombokMetadataNestedGroupNoGetter() throws IOException {
process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokInnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"first");
TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first")
.hasType(
"org.springframework.boot.configurationsample.lombok.LombokInnerClassProperties$Foo")
.hasSourceType(LombokInnerClassProperties.class).hasSourceMethod(null)
.hasNoDescription().isNotDeprecated();
.hasType("org.springframework.boot.configurationsample.lombok.LombokInnerClassProperties$Foo")
.hasSourceType(LombokInnerClassProperties.class).hasSourceMethod(null).hasNoDescription()
.isNotDeprecated();
});
}
@Test
public void lombokMetadataNotACandidatePropertyShouldReturnNull() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"ignored");
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored");
assertThat(property.resolveItemMetadata("test", metadataEnv)).isNull();
});
}
@@ -232,46 +198,35 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
(roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(
org.springframework.boot.configurationsample.lombok.LombokDeprecatedProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(
ownerElement, "name");
assertItemMetadata(metadataEnv, property).isProperty()
.isDeprecatedWithNoInformation();
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name");
assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation();
});
}
@Test
public void lombokDeprecatedPropertyOnField() throws IOException {
process(LombokDeprecatedSingleProperty.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokDeprecatedSingleProperty.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"name");
assertItemMetadata(metadataEnv, property).isProperty()
.isDeprecatedWithNoInformation();
TypeElement ownerElement = roundEnv.getRootElement(LombokDeprecatedSingleProperty.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name");
assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation();
});
}
@Test
public void lombokPropertyWithDescription() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"name");
assertItemMetadata(metadataEnv, property).isProperty()
.hasDescription("Name description.");
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name");
assertItemMetadata(metadataEnv, property).isProperty().hasDescription("Name description.");
});
}
@Test
public void lombokPropertyWithDefaultValue() throws IOException {
process(LombokDefaultValueProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(LombokDefaultValueProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"description");
assertItemMetadata(metadataEnv, property).isProperty()
.hasDefaultValue("my description");
TypeElement ownerElement = roundEnv.getRootElement(LombokDefaultValueProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "description");
assertItemMetadata(metadataEnv, property).isProperty().hasDefaultValue("my description");
});
}
@@ -279,8 +234,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
public void lombokPropertyNotCandidate() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"theName");
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
assertThat(property.isProperty(metadataEnv)).isFalse();
assertThat(property.isNested(metadataEnv)).isFalse();
});
@@ -289,24 +243,18 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void lombokNestedPropertyNotCandidate() throws IOException {
process(InnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv
.getRootElement(InnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement,
"first");
TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
assertThat(property.isProperty(metadataEnv)).isFalse();
assertThat(property.isNested(metadataEnv)).isFalse();
});
}
protected LombokPropertyDescriptor createPropertyDescriptor(TypeElement ownerElement,
String name) {
protected LombokPropertyDescriptor createPropertyDescriptor(TypeElement ownerElement, String name) {
VariableElement field = getField(ownerElement, name);
ExecutableElement getter = getMethod(ownerElement,
createAccessorMethodName("get", name));
ExecutableElement setter = getMethod(ownerElement,
createAccessorMethodName("set", name));
return new LombokPropertyDescriptor(ownerElement, null, field, name,
field.asType(), getter, setter);
ExecutableElement getter = getMethod(ownerElement, createAccessorMethodName("get", name));
ExecutableElement setter = getMethod(ownerElement, createAccessorMethodName("set", name));
return new LombokPropertyDescriptor(ownerElement, null, field, name, field.asType(), getter, setter);
}
}

View File

@@ -56,114 +56,96 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
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 mergeExistingPropertyWithSeveralCandidates() throws Exception {
ItemMetadata property = ItemMetadata.newProperty("simple", "flag",
Boolean.class.getName(), null, null, null, true, null);
ItemMetadata property = ItemMetadata.newProperty("simple", "flag", Boolean.class.getName(), null, null, null,
true, null);
writeAdditionalMetadata(property);
ConfigurationMetadata metadata = compile(SimpleProperties.class,
SimpleConflictingProperties.class);
ConfigurationMetadata metadata = compile(SimpleProperties.class, SimpleConflictingProperties.class);
assertThat(metadata.getItems()).hasSize(6);
List<ItemMetadata> items = metadata.getItems().stream()
.filter((item) -> item.getName().equals("simple.flag"))
List<ItemMetadata> items = metadata.getItems().stream().filter((item) -> item.getName().equals("simple.flag"))
.collect(Collectors.toList());
assertThat(items).hasSize(2);
ItemMetadata matchingProperty = items.stream()
.filter((item) -> item.getType().equals(Boolean.class.getName()))
ItemMetadata matchingProperty = items.stream().filter((item) -> item.getType().equals(Boolean.class.getName()))
.findFirst().orElse(null);
assertThat(matchingProperty).isNotNull();
assertThat(matchingProperty.getDefaultValue()).isEqualTo(true);
assertThat(matchingProperty.getSourceType())
.isEqualTo(SimpleProperties.class.getName());
assertThat(matchingProperty.getSourceType()).isEqualTo(SimpleProperties.class.getName());
assertThat(matchingProperty.getDescription()).isEqualTo("A simple flag.");
ItemMetadata nonMatchingProperty = items.stream()
.filter((item) -> item.getType().equals(String.class.getName()))
.findFirst().orElse(null);
.filter((item) -> item.getType().equals(String.class.getName())).findFirst().orElse(null);
assertThat(nonMatchingProperty).isNotNull();
assertThat(nonMatchingProperty.getDefaultValue()).isEqualTo("hello");
assertThat(nonMatchingProperty.getSourceType())
.isEqualTo(SimpleConflictingProperties.class.getName());
assertThat(nonMatchingProperty.getSourceType()).isEqualTo(SimpleConflictingProperties.class.getName());
assertThat(nonMatchingProperty.getDescription()).isNull();
}
@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);
}
@@ -171,70 +153,59 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
public void mergeOfInvalidAdditionalMetadata() throws IOException {
File additionalMetadataFile = createAdditionalMetadataFile();
FileCopyUtils.copy("Hello World", new FileWriter(additionalMetadataFile));
assertThatIllegalStateException()
.isThrownBy(() -> compile(SimpleProperties.class))
assertThatIllegalStateException().isThrownBy(() -> compile(SimpleProperties.class))
.withMessage("Compilation failed");
}
@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.emptyList(),
Arrays.asList(
new ItemHint.ValueProvider("first",
Collections.singletonMap("target", "org.foo")),
Arrays.asList(new ItemHint.ValueProvider("first", Collections.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(getCompiler().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");
@@ -250,8 +221,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
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));
}
private void writeAdditionalMetadata(ItemMetadata... metadata) throws Exception {
@@ -305,8 +275,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
private File createAdditionalMetadataFile() throws IOException {
File metaInfFolder = new File(getCompiler().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;
}

View File

@@ -27,8 +27,7 @@ import org.springframework.boot.configurationprocessor.test.TestConfigurationMet
*
* @author Stephane Nicoll
*/
class MetadataGenerationEnvironmentFactory
implements Function<ProcessingEnvironment, MetadataGenerationEnvironment> {
class MetadataGenerationEnvironmentFactory implements Function<ProcessingEnvironment, MetadataGenerationEnvironment> {
@Override
public MetadataGenerationEnvironment apply(ProcessingEnvironment environment) {

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

@@ -38,31 +38,30 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati
@Test
public void simpleMethodConfig() {
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)
.has(Metadata.withProperty("foo.name", String.class).fromSource(SimpleMethodConfig.Foo.class));
assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false)
.fromSource(SimpleMethodConfig.Foo.class));
assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class)
.withDefaultValue(false).fromSource(SimpleMethodConfig.Foo.class));
}
@Test
public void invalidMethodConfig() {
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() {
ConfigurationMetadata metadata = compile(MethodAndClassConfig.class);
assertThat(metadata).has(Metadata.withProperty("conflict.name", String.class)
assertThat(metadata)
.has(Metadata.withProperty("conflict.name", String.class).fromSource(MethodAndClassConfig.Foo.class));
assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class).withDefaultValue(false)
.fromSource(MethodAndClassConfig.Foo.class));
assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class)
.withDefaultValue(false).fromSource(MethodAndClassConfig.Foo.class));
assertThat(metadata).has(Metadata.withProperty("conflict.value", String.class)
.fromSource(MethodAndClassConfig.class));
assertThat(metadata)
.has(Metadata.withProperty("conflict.value", String.class).fromSource(MethodAndClassConfig.class));
}
@Test
@@ -77,11 +76,9 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati
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));
assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class)
.withDefaultValue(false).fromSource(DeprecatedMethodConfig.Foo.class)
.withDeprecation(null, null));
.fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null));
assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false)
.fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null));
}
@Test
@@ -91,13 +88,10 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati
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)
.withDefaultValue(false)
.fromSource(
org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class)
assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false)
.fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class)
.withDeprecation(null, null));
}

View File

@@ -59,90 +59,76 @@ public class PropertyDescriptorResolverTests {
@Test
public void propertiesWithJavaBeanProperties() throws IOException {
process(SimpleProperties.class, propertyNames((stream) -> assertThat(stream)
.containsExactly("theName", "flag", "comparator")));
process(SimpleProperties.class,
propertyNames((stream) -> assertThat(stream).containsExactly("theName", "flag", "comparator")));
}
@Test
public void propertiesWithJavaBeanHierarchicalProperties() throws IOException {
process(HierarchicalProperties.class,
Arrays.asList(HierarchicalPropertiesParent.class,
HierarchicalPropertiesGrandparent.class),
Arrays.asList(HierarchicalPropertiesParent.class, HierarchicalPropertiesGrandparent.class),
(type, metadataEnv) -> {
PropertyDescriptorResolver resolver = new PropertyDescriptorResolver(
metadataEnv);
assertThat(
resolver.resolve(type, null).map(PropertyDescriptor::getName))
.containsExactly("third", "second", "first");
PropertyDescriptorResolver resolver = new PropertyDescriptorResolver(metadataEnv);
assertThat(resolver.resolve(type, null).map(PropertyDescriptor::getName)).containsExactly("third",
"second", "first");
assertThat(resolver.resolve(type, null)
.map((descriptor) -> descriptor.resolveItemMetadata("test",
metadataEnv))
.map(ItemMetadata::getDefaultValue)).containsExactly("three",
"two", "one");
.map((descriptor) -> descriptor.resolveItemMetadata("test", metadataEnv))
.map(ItemMetadata::getDefaultValue)).containsExactly("three", "two", "one");
});
}
@Test
public void propertiesWithLombokGetterSetterAtClassLevel() throws IOException {
process(LombokSimpleProperties.class, propertyNames((stream) -> assertThat(stream)
.containsExactly("name", "description", "counter", "number", "items")));
process(LombokSimpleProperties.class, propertyNames(
(stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items")));
}
@Test
public void propertiesWithLombokGetterSetterAtFieldLevel() throws IOException {
process(LombokExplicitProperties.class,
propertyNames((stream) -> assertThat(stream).containsExactly("name",
"description", "counter", "number", "items")));
process(LombokExplicitProperties.class, propertyNames(
(stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items")));
}
@Test
public void propertiesWithLombokDataClass() throws IOException {
process(LombokSimpleDataProperties.class,
propertyNames((stream) -> assertThat(stream).containsExactly("name",
"description", "counter", "number", "items")));
process(LombokSimpleDataProperties.class, propertyNames(
(stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items")));
}
@Test
public void propertiesWithConstructorParameters() throws IOException {
process(ImmutableSimpleProperties.class,
propertyNames((stream) -> assertThat(stream).containsExactly("theName",
"flag", "comparator", "counter")));
process(ImmutableSimpleProperties.class, propertyNames(
(stream) -> assertThat(stream).containsExactly("theName", "flag", "comparator", "counter")));
}
@Test
public void propertiesWithSeveralConstructors() throws IOException {
process(TwoConstructorsExample.class, propertyNames((stream) -> assertThat(stream).containsExactly("name")));
process(TwoConstructorsExample.class,
propertyNames((stream) -> assertThat(stream).containsExactly("name")));
process(TwoConstructorsExample.class, properties((stream) -> assertThat(stream)
.element(0).isInstanceOf(JavaBeanPropertyDescriptor.class)));
properties((stream) -> assertThat(stream).element(0).isInstanceOf(JavaBeanPropertyDescriptor.class)));
}
private BiConsumer<TypeElement, MetadataGenerationEnvironment> properties(
Consumer<Stream<PropertyDescriptor<?>>> stream) {
return (element, metadataEnv) -> {
PropertyDescriptorResolver resolver = new PropertyDescriptorResolver(
metadataEnv);
PropertyDescriptorResolver resolver = new PropertyDescriptorResolver(metadataEnv);
stream.accept(resolver.resolve(element, null));
};
}
private BiConsumer<TypeElement, MetadataGenerationEnvironment> propertyNames(
Consumer<Stream<String>> stream) {
return properties(
(result) -> stream.accept(result.map(PropertyDescriptor::getName)));
private BiConsumer<TypeElement, MetadataGenerationEnvironment> propertyNames(Consumer<Stream<String>> stream) {
return properties((result) -> stream.accept(result.map(PropertyDescriptor::getName)));
}
private void process(Class<?> target,
BiConsumer<TypeElement, MetadataGenerationEnvironment> consumer)
private void process(Class<?> target, BiConsumer<TypeElement, MetadataGenerationEnvironment> consumer)
throws IOException {
process(target, Collections.emptyList(), consumer);
}
private void process(Class<?> target, Collection<Class<?>> additionalClasses,
BiConsumer<TypeElement, MetadataGenerationEnvironment> consumer)
throws IOException {
BiConsumer<RoundEnvironmentTester, MetadataGenerationEnvironment> internalConsumer = (
roundEnv, metadataEnv) -> {
BiConsumer<TypeElement, MetadataGenerationEnvironment> consumer) throws IOException {
BiConsumer<RoundEnvironmentTester, MetadataGenerationEnvironment> internalConsumer = (roundEnv,
metadataEnv) -> {
TypeElement element = roundEnv.getRootElement(target);
consumer.accept(element, metadataEnv);
};

View File

@@ -50,24 +50,23 @@ public abstract class PropertyDescriptorTests {
}
protected ExecutableElement getMethod(TypeElement element, String name) {
return ElementFilter.methodsIn(element.getEnclosedElements()).stream().filter(
(method) -> ((Element) method).getSimpleName().toString().equals(name))
.findFirst().orElse(null);
return ElementFilter.methodsIn(element.getEnclosedElements()).stream()
.filter((method) -> ((Element) method).getSimpleName().toString().equals(name)).findFirst()
.orElse(null);
}
protected VariableElement getField(TypeElement element, String name) {
return ElementFilter.fieldsIn(element.getEnclosedElements()).stream().filter(
(method) -> ((Element) method).getSimpleName().toString().equals(name))
.findFirst().orElse(null);
return ElementFilter.fieldsIn(element.getEnclosedElements()).stream()
.filter((method) -> ((Element) method).getSimpleName().toString().equals(name)).findFirst()
.orElse(null);
}
protected ItemMetadataAssert assertItemMetadata(
MetadataGenerationEnvironment metadataEnv, PropertyDescriptor<?> property) {
protected ItemMetadataAssert assertItemMetadata(MetadataGenerationEnvironment metadataEnv,
PropertyDescriptor<?> property) {
return new ItemMetadataAssert(property.resolveItemMetadata("test", metadataEnv));
}
protected void process(Class<?> target,
BiConsumer<RoundEnvironmentTester, MetadataGenerationEnvironment> consumer)
protected void process(Class<?> target, BiConsumer<RoundEnvironmentTester, MetadataGenerationEnvironment> consumer)
throws IOException {
TestableAnnotationProcessor<MetadataGenerationEnvironment> processor = new TestableAnnotationProcessor<>(
consumer, new MetadataGenerationEnvironmentFactory());

View File

@@ -64,8 +64,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
@@ -134,15 +133,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

@@ -47,17 +47,13 @@ public class TypeUtilsTests {
@Test
public void resolveTypeDescriptorOnConcreteClass() throws IOException {
process(SimpleGenericProperties.class, (roundEnv, typeUtils) -> {
TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor(
roundEnv.getRootElement(SimpleGenericProperties.class));
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(roundEnv.getRootElement(SimpleGenericProperties.class));
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());
});
}
@@ -65,15 +61,12 @@ public class TypeUtilsTests {
@Test
public void resolveTypeDescriptorOnIntermediateClass() throws IOException {
process(AbstractIntermediateGenericProperties.class, (roundEnv, typeUtils) -> {
TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor(
roundEnv.getRootElement(AbstractIntermediateGenericProperties.class));
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(roundEnv.getRootElement(AbstractIntermediateGenericProperties.class));
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");
});
}
@@ -81,19 +74,16 @@ public class TypeUtilsTests {
@Test
public void resolveTypeDescriptorWithOnlyGenerics() throws IOException {
process(AbstractGenericProperties.class, (roundEnv, typeUtils) -> {
TypeDescriptor typeDescriptor = typeUtils.resolveTypeDescriptor(
roundEnv.getRootElement(AbstractGenericProperties.class));
assertThat(
typeDescriptor.getGenerics().keySet().stream().map(Object::toString))
.containsOnly("A", "B", "C");
TypeDescriptor typeDescriptor = typeUtils
.resolveTypeDescriptor(roundEnv.getRootElement(AbstractGenericProperties.class));
assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B",
"C");
});
}
private void process(Class<?> target,
BiConsumer<RoundEnvironmentTester, TypeUtils> consumer) throws IOException {
TestableAnnotationProcessor<TypeUtils> processor = new TestableAnnotationProcessor<>(
consumer, TypeUtils::new);
private void process(Class<?> target, BiConsumer<RoundEnvironmentTester, TypeUtils> consumer) throws IOException {
TestableAnnotationProcessor<TypeUtils> processor = new TestableAnnotationProcessor<>(consumer, TypeUtils::new);
TestCompiler compiler = new TestCompiler(this.temporaryFolder);
compiler.getTask(target).call(processor);
}

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

@@ -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

@@ -39,10 +39,8 @@ public class RoundEnvironmentTester {
*/
public TypeElement getRootElement(Class<?> type) {
return (TypeElement) this.roundEnvironment.getRootElements().stream()
.filter((element) -> element.toString().equals(type.getName()))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No element found for "
+ type
.filter((element) -> element.toString().equals(type.getName())).findFirst()
.orElseThrow(() -> new IllegalStateException("No element found for " + type
+ " make sure it is included in the list of classes to compile"));
}

View File

@@ -38,8 +38,7 @@ import org.springframework.boot.configurationprocessor.metadata.JsonMarshaller;
*/
@SupportedAnnotationTypes({ "*" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class TestConfigurationMetadataAnnotationProcessor
extends ConfigurationMetadataAnnotationProcessor {
public class TestConfigurationMetadataAnnotationProcessor extends ConfigurationMetadataAnnotationProcessor {
public static final String CONFIGURATION_PROPERTIES_ANNOTATION = "org.springframework.boot.configurationsample.ConfigurationProperties";
@@ -95,11 +94,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

@@ -57,8 +57,7 @@ public class TestableAnnotationProcessor<T> extends AbstractProcessor {
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
RoundEnvironmentTester tester = new RoundEnvironmentTester(roundEnv);
if (!roundEnv.getRootElements().isEmpty()) {
this.consumer.accept(tester, this.target);

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

@@ -35,8 +35,7 @@ public class ImmutableCollectionProperties {
private final List<Duration> durations;
public ImmutableCollectionProperties(List<String> names,
@DefaultValue({ "true", "false" }) List<Boolean> flags,
public ImmutableCollectionProperties(List<String> names, @DefaultValue({ "true", "false" }) List<Boolean> flags,
@DefaultValue({ "10s", "1m", "1h" }) List<Duration> durations) {
this.names = names;
this.flags = flags;

View File

@@ -35,8 +35,7 @@ public class ImmutableInnerClassProperties {
private final Fourth fourth;
public ImmutableInnerClassProperties(Foo first, Foo second, SimplePojo third,
Fourth fourth) {
public ImmutableInnerClassProperties(Foo first, Foo second, SimplePojo third, Fourth fourth) {
this.first = first;
this.second = second;
this.third = third;

View File

@@ -40,8 +40,8 @@ public class ImmutablePrimitiveProperties {
private final double ratio;
public ImmutablePrimitiveProperties(boolean flag, byte octet, char letter,
short number, int counter, long value, float percentage, double ratio) {
public ImmutablePrimitiveProperties(boolean flag, byte octet, char letter, short number, int counter, long value,
float percentage, double ratio) {
this.flag = flag;
this.octet = octet;
this.letter = letter;

View File

@@ -42,9 +42,8 @@ public class ImmutablePrimitiveWithDefaultsProperties {
private final double ratio;
public ImmutablePrimitiveWithDefaultsProperties(@DefaultValue("true") boolean flag,
@DefaultValue("120") byte octet, @DefaultValue("a") char letter,
@DefaultValue("1000") short number, @DefaultValue("42") int counter,
public ImmutablePrimitiveWithDefaultsProperties(@DefaultValue("true") boolean flag, @DefaultValue("120") byte octet,
@DefaultValue("a") char letter, @DefaultValue("1000") short number, @DefaultValue("42") int counter,
@DefaultValue("2000") long value, @DefaultValue("0.5") float percentage,
@DefaultValue("42.42") double ratio) {
this.flag = flag;

View File

@@ -42,9 +42,8 @@ public class ImmutablePrimitiveWrapperWithDefaultsProperties {
private final Double ratio;
public ImmutablePrimitiveWrapperWithDefaultsProperties(
@DefaultValue("true") Boolean flag, @DefaultValue("120") Byte octet,
@DefaultValue("a") Character letter, @DefaultValue("1000") Short number,
public ImmutablePrimitiveWrapperWithDefaultsProperties(@DefaultValue("true") Boolean flag,
@DefaultValue("120") Byte octet, @DefaultValue("a") Character letter, @DefaultValue("1000") Short number,
@DefaultValue("42") Integer counter, @DefaultValue("2000") Long value,
@DefaultValue("0.5") Float percentage, @DefaultValue("42.42") Double ratio) {
this.flag = flag;

View File

@@ -47,8 +47,8 @@ public class ImmutableSimpleProperties {
@SuppressWarnings("unused")
private final Long counter;
public ImmutableSimpleProperties(@DefaultValue("boot") String theName, boolean flag,
Comparator<?> comparator, Long counter) {
public ImmutableSimpleProperties(@DefaultValue("boot") String theName, boolean flag, Comparator<?> comparator,
Long counter) {
this.theName = theName;
this.flag = flag;
this.comparator = comparator;

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

@@ -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 = "two";

View File

@@ -30,8 +30,7 @@ public class InvalidDefaultValueFloatingPointProperties {
private final Double ratio;
public InvalidDefaultValueFloatingPointProperties(
@DefaultValue("55.55.33") Double ratio) {
public InvalidDefaultValueFloatingPointProperties(@DefaultValue("55.55.33") Double ratio) {
this.ratio = ratio;
}