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