yangys
2024-03-27 e48aa2ac8dea1be5db11c63edf0b912c4ad5ce65
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package com.qianwen.smart.core.auto.service;
 
 
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedOptions;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.SimpleAnnotationValueVisitor8;
import javax.lang.model.util.Types;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
 
import com.qianwen.smart.core.auto.common.AbstractBladeProcessor;
import com.qianwen.smart.core.auto.common.MultiSetMap;
import com.qianwen.smart.core.auto.common.Sets;
import com.qianwen.smart.core.auto.common.TypeHelper;
 
@SupportedOptions({"debug"})
public class AutoServiceProcessor extends AbstractBladeProcessor {
    private final MultiSetMap<String, String> providers = new MultiSetMap<>();
    private TypeHelper typeHelper;
 
    public synchronized void init(ProcessingEnvironment env) {
        super.init(env);
        this.typeHelper = new TypeHelper(env);
    }
 
    public Set<String> getSupportedAnnotationTypes() {
        return Sets.ofImmutableSet(AutoService.class.getName());
    }
 
    @Override // org.springblade.core.auto.common.AbstractBladeProcessor
    protected boolean processImpl(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if (roundEnv.processingOver()) {
            generateConfigFiles();
            return true;
        }
        processAnnotations(annotations, roundEnv);
        return true;
    }
 
    private void processAnnotations(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(AutoService.class);
        log(annotations.toString());
        log(elements.toString());
        for (Element e : elements) {
            //Element element = (TypeElement) e;
            TypeElement element = (TypeElement) e;
            AnnotationMirror annotationMirror = getAnnotationMirror(e, AutoService.class);
            if (annotationMirror != null) {
                Set<TypeMirror> typeMirrors = getValueFieldOfClasses(annotationMirror);
                if (typeMirrors.isEmpty()) {
                    error("No service interfaces provided for element!", e, annotationMirror);
                } else {
                    for (TypeMirror typeMirror : typeMirrors) {
                        String providerInterfaceName = this.typeHelper.getType(typeMirror);
                        Name providerImplementerName = element.getQualifiedName();
                        log("provider interface: " + providerInterfaceName);
                        log("provider implementer: " + providerImplementerName);
                        if (checkImplementer(element, typeMirror)) {
                            this.providers.put(providerInterfaceName, this.typeHelper.getType(element));
                        } else {
                            String message = "ServiceProviders must implement their service provider interface. " + providerImplementerName + " does not implement " + providerInterfaceName;
                            error(message, e, annotationMirror);
                        }
                    }
                }
            }
        }
    }
 
    private void generateConfigFiles() {
        Filer filer = this.processingEnv.getFiler();
        for (String providerInterface : this.providers.keySet()) {
            String resourceFile = "META-INF/services/" + providerInterface;
            log("Working on resource file: " + resourceFile);
            try {
                SortedSet<String> allServices = new TreeSet<>();
                try {
                    FileObject existingFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "", resourceFile);
                    log("Looking for existing resource file at " + existingFile.toUri());
                    Set<String> oldServices = ServicesFiles.readServiceFile(existingFile.openInputStream());
                    log("Existing service entries: " + oldServices);
                    allServices.addAll(oldServices);
                } catch (IOException e) {
                    log("Resource file did not already exist.");
                }
                Set<String> newServices = new HashSet<>(this.providers.get(providerInterface));
                if (allServices.containsAll(newServices)) {
                    log("No new service entries being added.");
                    return;
                }
                allServices.addAll(newServices);
                log("New service file contents: " + allServices);
                FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceFile, new Element[0]);
                OutputStream out = fileObject.openOutputStream();
                ServicesFiles.writeServiceFile(allServices, out);
                out.close();
                log("Wrote to: " + fileObject.toUri());
            } catch (IOException e2) {
                fatalError("Unable to create " + resourceFile + ", " + e2);
                return;
            }
        }
    }
 
    private boolean checkImplementer(TypeElement providerImplementer, TypeMirror providerType) {
        Types types = this.processingEnv.getTypeUtils();
        return types.isSubtype(providerImplementer.asType(), providerType);
    }
 
 
    private Set<TypeMirror> getValueFieldOfClasses(AnnotationMirror annotationMirror) {
        return getAnnotationValue(annotationMirror, "value")
                  .accept(new SimpleAnnotationValueVisitor8<Set<TypeMirror>, Void>() {
                      public Set<TypeMirror> visitType(TypeMirror typeMirror, Void v) {
                        Set<TypeMirror> declaredTypeSet = new HashSet<>(1);
                        declaredTypeSet.add(typeMirror);
                        return Collections.unmodifiableSet(declaredTypeSet);
                      }
                      
                      public Set<TypeMirror> visitArray(List<? extends AnnotationValue> values, Void v) {
                          
                        return (Set<TypeMirror>)values
                          .stream()
                          .flatMap(value -> ((Set)value.accept(this, null)).stream())
                          .collect(Collectors.toSet());
                      }
                    }, null);
    }
 
    public AnnotationValue getAnnotationValue(AnnotationMirror annotationMirror, String elementName) {
        Objects.requireNonNull(annotationMirror);
        Objects.requireNonNull(elementName);
        for (Map.Entry<ExecutableElement, AnnotationValue> entry : getAnnotationValuesWithDefaults(annotationMirror).entrySet()) {
            if (entry.getKey().getSimpleName().contentEquals(elementName)) {
                return entry.getValue();
            }
        }
        String name = this.typeHelper.getType(annotationMirror);
        throw new IllegalArgumentException(String.format("@%s does not define an element %s()", name, elementName));
    }
 
    public Map<ExecutableElement, AnnotationValue> getAnnotationValuesWithDefaults(AnnotationMirror annotation) {
        Map<ExecutableElement, AnnotationValue> values = new HashMap<>(32);
        Map<? extends ExecutableElement, ? extends AnnotationValue> declaredValues = annotation.getElementValues();
        for (ExecutableElement method : ElementFilter.methodsIn(annotation.getAnnotationType().asElement().getEnclosedElements())) {
          if (declaredValues.containsKey(method)) {
            values.put(method, declaredValues.get(method));
            continue;
          } 
          if (method.getDefaultValue() != null) {
            values.put(method, method.getDefaultValue());
            continue;
          } 
          String name = this.typeHelper.getType(method);
          throw new IllegalStateException("Unset annotation value without default should never happen: " + name + '.' + method
              .getSimpleName() + "()");
        } 
        return Collections.unmodifiableMap(values);
    }
 
    public AnnotationMirror getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass) {
        String annotationClassName = annotationClass.getCanonicalName();
        for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
            String name = this.typeHelper.getType(annotationMirror);
            if (name.contentEquals(annotationClassName)) {
                return annotationMirror;
            }
        }
        return null;
    }
}