guava
301 строка · 12.1 Кб
1/*
2* Copyright (C) 2008 The Guava Authors
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17package com.google.common.collect.testing.features;
18
19import com.google.common.annotations.GwtIncompatible;
20import com.google.common.collect.testing.Helpers;
21import com.google.errorprone.annotations.CanIgnoreReturnValue;
22import java.lang.annotation.Annotation;
23import java.lang.reflect.AnnotatedElement;
24import java.lang.reflect.Method;
25import java.util.ArrayDeque;
26import java.util.ArrayList;
27import java.util.Collections;
28import java.util.HashMap;
29import java.util.LinkedHashSet;
30import java.util.List;
31import java.util.Locale;
32import java.util.Map;
33import java.util.Queue;
34import java.util.Set;
35
36/**
37* Utilities for collecting and validating tester requirements from annotations.
38*
39* @author George van den Driessche
40*/
41@GwtIncompatible
42public class FeatureUtil {
43/** A cache of annotated objects (typically a Class or Method) to its set of annotations. */
44private static Map<AnnotatedElement, List<Annotation>> annotationCache = new HashMap<>();
45
46private static final Map<Class<?>, TesterRequirements> classTesterRequirementsCache =
47new HashMap<>();
48
49private static final Map<Method, TesterRequirements> methodTesterRequirementsCache =
50new HashMap<>();
51
52/**
53* Given a set of features, add to it all the features directly or indirectly implied by any of
54* them, and return it.
55*
56* @param features the set of features to expand
57* @return the same set of features, expanded with all implied features
58*/
59@CanIgnoreReturnValue
60public static Set<Feature<?>> addImpliedFeatures(Set<Feature<?>> features) {
61Queue<Feature<?>> queue = new ArrayDeque<>(features);
62while (!queue.isEmpty()) {
63Feature<?> feature = queue.remove();
64for (Feature<?> implied : feature.getImpliedFeatures()) {
65if (features.add(implied)) {
66queue.add(implied);
67}
68}
69}
70return features;
71}
72
73/**
74* Given a set of features, return a new set of all features directly or indirectly implied by any
75* of them.
76*
77* @param features the set of features whose implications to find
78* @return the implied set of features
79*/
80public static Set<Feature<?>> impliedFeatures(Set<Feature<?>> features) {
81Set<Feature<?>> impliedSet = new LinkedHashSet<>();
82Queue<Feature<?>> queue = new ArrayDeque<>(features);
83while (!queue.isEmpty()) {
84Feature<?> feature = queue.remove();
85for (Feature<?> implied : feature.getImpliedFeatures()) {
86if (!features.contains(implied) && impliedSet.add(implied)) {
87queue.add(implied);
88}
89}
90}
91return impliedSet;
92}
93
94/**
95* Get the full set of requirements for a tester class.
96*
97* @param testerClass a tester class
98* @return all the constraints implicitly or explicitly required by the class or any of its
99* superclasses.
100* @throws ConflictingRequirementsException if the requirements are mutually inconsistent.
101*/
102public static TesterRequirements getTesterRequirements(Class<?> testerClass)
103throws ConflictingRequirementsException {
104synchronized (classTesterRequirementsCache) {
105TesterRequirements requirements = classTesterRequirementsCache.get(testerClass);
106if (requirements == null) {
107requirements = buildTesterRequirements(testerClass);
108classTesterRequirementsCache.put(testerClass, requirements);
109}
110return requirements;
111}
112}
113
114/**
115* Get the full set of requirements for a tester class.
116*
117* @param testerMethod a test method of a tester class
118* @return all the constraints implicitly or explicitly required by the method, its declaring
119* class, or any of its superclasses.
120* @throws ConflictingRequirementsException if the requirements are mutually inconsistent.
121*/
122public static TesterRequirements getTesterRequirements(Method testerMethod)
123throws ConflictingRequirementsException {
124synchronized (methodTesterRequirementsCache) {
125TesterRequirements requirements = methodTesterRequirementsCache.get(testerMethod);
126if (requirements == null) {
127requirements = buildTesterRequirements(testerMethod);
128methodTesterRequirementsCache.put(testerMethod, requirements);
129}
130return requirements;
131}
132}
133
134/**
135* Construct the full set of requirements for a tester class.
136*
137* @param testerClass a tester class
138* @return all the constraints implicitly or explicitly required by the class or any of its
139* superclasses.
140* @throws ConflictingRequirementsException if the requirements are mutually inconsistent.
141*/
142static TesterRequirements buildTesterRequirements(Class<?> testerClass)
143throws ConflictingRequirementsException {
144TesterRequirements declaredRequirements = buildDeclaredTesterRequirements(testerClass);
145Class<?> baseClass = testerClass.getSuperclass();
146if (baseClass == null) {
147return declaredRequirements;
148} else {
149TesterRequirements clonedBaseRequirements =
150new TesterRequirements(getTesterRequirements(baseClass));
151return incorporateRequirements(clonedBaseRequirements, declaredRequirements, testerClass);
152}
153}
154
155/**
156* Construct the full set of requirements for a tester method.
157*
158* @param testerMethod a test method of a tester class
159* @return all the constraints implicitly or explicitly required by the method, its declaring
160* class, or any of its superclasses.
161* @throws ConflictingRequirementsException if the requirements are mutually inconsistent.
162*/
163static TesterRequirements buildTesterRequirements(Method testerMethod)
164throws ConflictingRequirementsException {
165TesterRequirements clonedClassRequirements =
166new TesterRequirements(getTesterRequirements(testerMethod.getDeclaringClass()));
167TesterRequirements declaredRequirements = buildDeclaredTesterRequirements(testerMethod);
168return incorporateRequirements(clonedClassRequirements, declaredRequirements, testerMethod);
169}
170
171/**
172* Find all the constraints explicitly or implicitly specified by a single tester annotation.
173*
174* @param testerAnnotation a tester annotation
175* @return the requirements specified by the annotation
176* @throws ConflictingRequirementsException if the requirements are mutually inconsistent.
177*/
178private static TesterRequirements buildTesterRequirements(Annotation testerAnnotation)
179throws ConflictingRequirementsException {
180Class<? extends Annotation> annotationClass = testerAnnotation.annotationType();
181Feature<?>[] presentFeatures;
182Feature<?>[] absentFeatures;
183try {
184presentFeatures = (Feature[]) annotationClass.getMethod("value").invoke(testerAnnotation);
185absentFeatures = (Feature[]) annotationClass.getMethod("absent").invoke(testerAnnotation);
186} catch (Exception e) {
187throw new IllegalArgumentException("Error extracting features from tester annotation.", e);
188}
189Set<Feature<?>> allPresentFeatures =
190addImpliedFeatures(Helpers.<Feature<?>>copyToSet(presentFeatures));
191Set<Feature<?>> allAbsentFeatures =
192addImpliedFeatures(Helpers.<Feature<?>>copyToSet(absentFeatures));
193if (!Collections.disjoint(allPresentFeatures, allAbsentFeatures)) {
194throw new ConflictingRequirementsException(
195"Annotation explicitly or "
196+ "implicitly requires one or more features to be both present "
197+ "and absent.",
198intersection(allPresentFeatures, allAbsentFeatures),
199testerAnnotation);
200}
201return new TesterRequirements(allPresentFeatures, allAbsentFeatures);
202}
203
204/**
205* Construct the set of requirements specified by annotations directly on a tester class or
206* method.
207*
208* @param classOrMethod a tester class or a test method thereof
209* @return all the constraints implicitly or explicitly required by annotations on the class or
210* method.
211* @throws ConflictingRequirementsException if the requirements are mutually inconsistent.
212*/
213public static TesterRequirements buildDeclaredTesterRequirements(AnnotatedElement classOrMethod)
214throws ConflictingRequirementsException {
215TesterRequirements requirements = new TesterRequirements();
216
217Iterable<Annotation> testerAnnotations = getTesterAnnotations(classOrMethod);
218for (Annotation testerAnnotation : testerAnnotations) {
219TesterRequirements moreRequirements = buildTesterRequirements(testerAnnotation);
220incorporateRequirements(requirements, moreRequirements, testerAnnotation);
221}
222
223return requirements;
224}
225
226/**
227* Find all the tester annotations declared on a tester class or method.
228*
229* @param classOrMethod a class or method whose tester annotations to find
230* @return an iterable sequence of tester annotations on the class
231*/
232public static Iterable<Annotation> getTesterAnnotations(AnnotatedElement classOrMethod) {
233synchronized (annotationCache) {
234List<Annotation> annotations = annotationCache.get(classOrMethod);
235if (annotations == null) {
236annotations = new ArrayList<>();
237for (Annotation a : classOrMethod.getDeclaredAnnotations()) {
238if (a.annotationType().isAnnotationPresent(TesterAnnotation.class)) {
239annotations.add(a);
240}
241}
242annotations = Collections.unmodifiableList(annotations);
243annotationCache.put(classOrMethod, annotations);
244}
245return annotations;
246}
247}
248
249/**
250* Incorporate additional requirements into an existing requirements object.
251*
252* @param requirements the existing requirements object
253* @param moreRequirements more requirements to incorporate
254* @param source the source of the additional requirements (used only for error reporting)
255* @return the existing requirements object, modified to include the additional requirements
256* @throws ConflictingRequirementsException if the additional requirements are inconsistent with
257* the existing requirements
258*/
259@CanIgnoreReturnValue
260private static TesterRequirements incorporateRequirements(
261TesterRequirements requirements, TesterRequirements moreRequirements, Object source)
262throws ConflictingRequirementsException {
263Set<Feature<?>> presentFeatures = requirements.getPresentFeatures();
264Set<Feature<?>> absentFeatures = requirements.getAbsentFeatures();
265Set<Feature<?>> morePresentFeatures = moreRequirements.getPresentFeatures();
266Set<Feature<?>> moreAbsentFeatures = moreRequirements.getAbsentFeatures();
267checkConflict("absent", absentFeatures, "present", morePresentFeatures, source);
268checkConflict("present", presentFeatures, "absent", moreAbsentFeatures, source);
269presentFeatures.addAll(morePresentFeatures);
270absentFeatures.addAll(moreAbsentFeatures);
271return requirements;
272}
273
274// Used by incorporateRequirements() only
275private static void checkConflict(
276String earlierRequirement,
277Set<Feature<?>> earlierFeatures,
278String newRequirement,
279Set<Feature<?>> newFeatures,
280Object source)
281throws ConflictingRequirementsException {
282if (!Collections.disjoint(newFeatures, earlierFeatures)) {
283throw new ConflictingRequirementsException(
284String.format(
285Locale.ROOT,
286"Annotation requires to be %s features that earlier "
287+ "annotations required to be %s.",
288newRequirement,
289earlierRequirement),
290intersection(newFeatures, earlierFeatures),
291source);
292}
293}
294
295/** Construct a new {@link java.util.Set} that is the intersection of the given sets. */
296public static <T> Set<T> intersection(Set<? extends T> set1, Set<? extends T> set2) {
297Set<T> result = Helpers.<T>copyToSet(set1);
298result.retainAll(set2);
299return result;
300}
301}
302