Migrate ModuleInfo cache to BindingReflections
[mdsal.git] / binding / mdsal-binding-spec-util / src / main / java / org / opendaylight / mdsal / binding / spec / reflect / BindingReflections.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.spec.reflect;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.ImmutableSet.Builder;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.Method;
22 import java.lang.reflect.Type;
23 import java.util.Arrays;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Optional;
30 import java.util.ServiceLoader;
31 import java.util.Set;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.TimeUnit;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import org.checkerframework.checker.regex.qual.Regex;
37 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
38 import org.opendaylight.yangtools.util.ClassLoaderUtils;
39 import org.opendaylight.yangtools.yang.binding.Action;
40 import org.opendaylight.yangtools.yang.binding.Augmentable;
41 import org.opendaylight.yangtools.yang.binding.Augmentation;
42 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
43 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
44 import org.opendaylight.yangtools.yang.binding.ChildOf;
45 import org.opendaylight.yangtools.yang.binding.DataContainer;
46 import org.opendaylight.yangtools.yang.binding.DataObject;
47 import org.opendaylight.yangtools.yang.binding.Notification;
48 import org.opendaylight.yangtools.yang.binding.RpcService;
49 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
50 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.common.QNameModule;
53 import org.opendaylight.yangtools.yang.common.YangConstants;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 public final class BindingReflections {
58
59     private static final long EXPIRATION_TIME = 60;
60
61     @Regex
62     private static final String ROOT_PACKAGE_PATTERN_STRING =
63             "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.(?:rev[0-9][0-9][0-1][0-9][0-3][0-9]|norev))";
64     private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
65     private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
66
67     private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
68             .weakKeys()
69             .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
70             .build(new ClassToQNameLoader());
71
72     private static final LoadingCache<ClassLoader, ImmutableSet<YangModuleInfo>> MODULE_INFO_CACHE =
73             CacheBuilder.newBuilder().weakKeys().weakValues().build(
74                 new CacheLoader<ClassLoader, ImmutableSet<YangModuleInfo>>() {
75                     @Override
76                     public ImmutableSet<YangModuleInfo> load(final ClassLoader key) {
77                         return loadModuleInfos(key);
78                     }
79                 });
80
81     private BindingReflections() {
82         throw new UnsupportedOperationException("Utility class.");
83     }
84
85     /**
86      * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
87      * implemented {@link Augmentation} interface.
88      *
89      * @param augmentation
90      *            {@link Augmentation} subclass for which we want to determine
91      *            augmentation target.
92      * @return Augmentation target - class which augmentation provides additional extensions.
93      */
94     public static Class<? extends Augmentable<?>> findAugmentationTarget(
95             final Class<? extends Augmentation<?>> augmentation) {
96         final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
97             Augmentation.class);
98         return opt.orElse(null);
99     }
100
101     /**
102      * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
103      * {@link ChildOf} interface.
104      *
105      * @param childClass
106      *            child class for which we want to find the parent class.
107      * @return Parent class, e.g. class of which the childClass is ChildOf.
108      */
109     public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
110         return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class).orElse(null);
111     }
112
113     /**
114      * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
115      * invoking {@link DataObject#implementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
116      *
117      * @param child
118      *            Child object for which the parent needs to be located.
119      * @return Parent class, or null if a parent is not found.
120      */
121     public static Class<?> findHierarchicalParent(final DataObject child) {
122         if (child instanceof ChildOf) {
123             return ClassLoaderUtils.findFirstGenericArgument(child.implementedInterface(), ChildOf.class).orElse(null);
124         }
125         return null;
126     }
127
128     /**
129      * Returns a QName associated to supplied type.
130      *
131      * @param dataType Data type class
132      * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
133      *         QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
134      *         have name. May return null if QName is not present.
135      */
136     public static QName findQName(final Class<?> dataType) {
137         return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
138     }
139
140     /**
141      * Checks if method is RPC invocation.
142      *
143      * @param possibleMethod
144      *            Method to check
145      * @return true if method is RPC invocation, false otherwise.
146      */
147     public static boolean isRpcMethod(final Method possibleMethod) {
148         return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
149                 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
150                 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
151                 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
152                 // non input type and two arguments for input type, resolveRpcInputClass() counting
153                 // with zero for non input and one for input type
154                 && possibleMethod.getParameterCount() <= 2;
155     }
156
157     /**
158      * Extracts Output class for RPC method.
159      *
160      * @param targetMethod
161      *            method to scan
162      * @return Optional.empty() if result type could not be get, or return type is Void.
163      */
164     @SuppressWarnings("rawtypes")
165     public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
166         checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
167         Type futureType = targetMethod.getGenericReturnType();
168         Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType).orElse(null);
169         Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType).orElse(null);
170         if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
171             return Optional.of((Class) rpcResultArgument);
172         }
173         return Optional.empty();
174     }
175
176     /**
177      * Extracts input class for RPC method.
178      *
179      * @param targetMethod
180      *            method to scan
181      * @return Optional.empty() if RPC has no input, RPC input type otherwise.
182      */
183     @SuppressWarnings("rawtypes")
184     public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
185         for (Class clazz : targetMethod.getParameterTypes()) {
186             if (DataContainer.class.isAssignableFrom(clazz)) {
187                 return Optional.of(clazz);
188             }
189         }
190         return Optional.empty();
191     }
192
193     public static QName getQName(final Class<? extends BaseIdentity> context) {
194         return findQName(context);
195     }
196
197     /**
198      * Checks if class is child of augmentation.
199      */
200     public static boolean isAugmentationChild(final Class<?> clazz) {
201         // FIXME: Current resolver could be still confused when child node was added by grouping
202         checkArgument(clazz != null);
203
204         @SuppressWarnings({ "rawtypes", "unchecked" })
205         Class<?> parent = findHierarchicalParent((Class) clazz);
206         if (parent == null) {
207             LOG.debug("Did not find a parent for class {}", clazz);
208             return false;
209         }
210
211         String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
212         String parentModelPackage = getModelRootPackageName(parent.getPackage());
213
214         return !clazzModelPackage.equals(parentModelPackage);
215     }
216
217     /**
218      * Returns root package name for supplied package.
219      *
220      * @param pkg
221      *            Package for which find model root package.
222      * @return Package of model root.
223      */
224     public static String getModelRootPackageName(final Package pkg) {
225         return getModelRootPackageName(pkg.getName());
226     }
227
228     /**
229      * Returns root package name for supplied package name.
230      *
231      * @param name
232      *            Package for which find model root package.
233      * @return Package of model root.
234      */
235     public static String getModelRootPackageName(final String name) {
236         checkArgument(name != null, "Package name should not be null.");
237         checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
238                 BindingMapping.PACKAGE_PREFIX, name);
239         Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
240         checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
241                 ROOT_PACKAGE_PATTERN_STRING);
242         return match.group(0);
243     }
244
245     @SuppressWarnings("checkstyle:illegalCatch")
246     public static QNameModule getQNameModule(final Class<?> clz) {
247         if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
248                 || Action.class.isAssignableFrom(clz)) {
249             return findQName(clz).getModule();
250         }
251         try {
252             return BindingReflections.getModuleInfo(clz).getName().getModule();
253         } catch (Exception e) {
254             throw new IllegalStateException("Unable to get QName of defining model.", e);
255         }
256     }
257
258     /**
259      * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
260      *
261      * @param cls data object class
262      * @return Instance of {@link YangModuleInfo} associated with model, from
263      *         which this class was derived.
264      */
265     public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
266         checkArgument(cls != null);
267         String packageName = getModelRootPackageName(cls.getPackage());
268         final String potentialClassName = getModuleInfoClassName(packageName);
269         return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> {
270             Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
271             return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
272         });
273     }
274
275     public static String getModuleInfoClassName(final String packageName) {
276         return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
277     }
278
279     /**
280      * Check if supplied class is derived from YANG model.
281      *
282      * @param cls
283      *            Class to check
284      * @return true if class is derived from YANG model.
285      */
286     public static boolean isBindingClass(final Class<?> cls) {
287         if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
288             return true;
289         }
290         return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
291     }
292
293     /**
294      * Checks if supplied method is callback for notifications.
295      *
296      * @param method method to check
297      * @return true if method is notification callback.
298      */
299     public static boolean isNotificationCallback(final Method method) {
300         checkArgument(method != null);
301         if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
302             Class<?> potentialNotification = method.getParameterTypes()[0];
303             if (isNotification(potentialNotification)
304                     && method.getName().equals("on" + potentialNotification.getSimpleName())) {
305                 return true;
306             }
307         }
308         return false;
309     }
310
311     /**
312      * Checks is supplied class is a {@link Notification}.
313      *
314      * @param potentialNotification class to examine
315      * @return True if the class represents a Notification.
316      */
317     public static boolean isNotification(final Class<?> potentialNotification) {
318         checkArgument(potentialNotification != null, "potentialNotification must not be null.");
319         return Notification.class.isAssignableFrom(potentialNotification);
320     }
321
322     /**
323      * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
324      * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
325      *
326      * @return Set of {@link YangModuleInfo} available for current classloader.
327      */
328     public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
329         return loadModuleInfos(Thread.currentThread().getContextClassLoader());
330     }
331
332     /**
333      * Loads {@link YangModuleInfo} infos available on supplied classloader.
334      *
335      * <p>
336      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
337      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
338      * {@link YangModuleInfo}.
339      *
340      * <p>
341      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
342      * collecting results of {@link YangModuleInfo#getImportedModules()}.
343      *
344      * <p>
345      * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
346      *
347      * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
348      * @return Set of {@link YangModuleInfo} available for supplied classloader.
349      */
350     public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
351         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
352         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
353                 loader);
354         for (YangModelBindingProvider bindingProvider : serviceLoader) {
355             YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
356             checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
357             collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
358         }
359         return moduleInfoSet.build();
360     }
361
362     /**
363      * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available
364      * information does not change. Subsequent accesses may return cached values.
365      *
366      * <p>
367      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
368      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
369      * {@link YangModuleInfo}.
370      *
371      * <p>
372      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
373      * collecting results of {@link YangModuleInfo#getImportedModules()}.
374      *
375      * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
376      * @return Set of {@link YangModuleInfo} available for supplied classloader.
377      */
378     @Beta
379     public static ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) throws ExecutionException {
380         return MODULE_INFO_CACHE.get(loader);
381     }
382
383     private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
384             final Builder<YangModuleInfo> moduleInfoSet) {
385         moduleInfoSet.add(moduleInfo);
386         for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
387             collectYangModuleInfo(dependency, moduleInfoSet);
388         }
389     }
390
391     /**
392      * Checks if supplied class represents RPC Input / RPC Output.
393      *
394      * @param targetType
395      *            Class to be checked
396      * @return true if class represents RPC Input or RPC Output class.
397      */
398     public static boolean isRpcType(final Class<? extends DataObject> targetType) {
399         return DataContainer.class.isAssignableFrom(targetType)
400                 && !ChildOf.class.isAssignableFrom(targetType)
401                 && !Notification.class.isAssignableFrom(targetType)
402                 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
403     }
404
405     /**
406      * Scans supplied class and returns an iterable of all data children classes.
407      *
408      * @param type
409      *            YANG Modeled Entity derived from DataContainer
410      * @return Iterable of all data children, which have YANG modeled entity
411      */
412     @SuppressWarnings("unchecked")
413     public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
414         checkArgument(type != null, "Target type must not be null");
415         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
416         List<Class<? extends DataObject>> ret = new LinkedList<>();
417         for (Method method : type.getMethods()) {
418             Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method,
419                 BindingMapping.GETTER_PREFIX);
420             if (entity.isPresent()) {
421                 ret.add((Class<? extends DataObject>) entity.get());
422             }
423         }
424         return ret;
425     }
426
427     /**
428      * Scans supplied class and returns an iterable of all data children classes.
429      *
430      * @param type
431      *            YANG Modeled Entity derived from DataContainer
432      * @return Iterable of all data children, which have YANG modeled entity
433      */
434     public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
435         return getChildrenClassToMethod(type, BindingMapping.GETTER_PREFIX);
436     }
437
438     private static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type, final String prefix) {
439         checkArgument(type != null, "Target type must not be null");
440         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
441             type);
442         Map<Class<?>, Method> ret = new HashMap<>();
443         for (Method method : type.getMethods()) {
444             Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method, prefix);
445             if (entity.isPresent()) {
446                 ret.put(entity.get(), method);
447             }
448         }
449         return ret;
450     }
451
452     @Beta
453     public static Map<Class<?>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
454         return getChildrenClassToMethod(type, BindingMapping.NONNULL_PREFIX);
455     }
456
457     @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" })
458     private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
459             final String prefix) {
460         final String methodName = method.getName();
461         if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
462             return Optional.empty();
463         }
464
465         Class returnType = method.getReturnType();
466         if (DataContainer.class.isAssignableFrom(returnType)) {
467             return Optional.of(returnType);
468         }
469         if (List.class.isAssignableFrom(returnType)) {
470             try {
471                 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> {
472                     return ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType()).flatMap(
473                         result -> result instanceof Class && DataContainer.class.isAssignableFrom((Class) result)
474                             ? Optional.of((Class) result) : Optional.empty());
475                 });
476             } catch (Exception e) {
477                 /*
478                  * It is safe to log this this exception on debug, since this
479                  * method should not fail. Only failures are possible if the
480                  * runtime / backing.
481                  */
482                 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
483             }
484         }
485         return Optional.empty();
486     }
487
488     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
489
490         @Override
491         public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
492             return resolveQNameNoCache(key);
493         }
494
495         /**
496          * Tries to resolve QName for supplied class. Looks up for static field with name from constant
497          * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
498          * {@link #computeQName(Class)} to compute QName for missing types.
499          */
500         private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
501             try {
502                 final Field field;
503                 try {
504                     field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
505                 } catch (NoSuchFieldException e) {
506                     LOG.debug("{} does not have a {} field, falling back to computation", key,
507                         BindingMapping.QNAME_STATIC_FIELD_NAME, e);
508                     return Optional.of(computeQName(key));
509                 }
510
511                 final Object obj = field.get(null);
512                 if (obj instanceof QName) {
513                     return Optional.of((QName) obj);
514                 }
515             } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
516                 /*
517                  * It is safe to log this this exception on debug, since this method should not fail. Only failures are
518                  * possible if the runtime / backing is inconsistent.
519                  */
520                 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
521             }
522             return Optional.empty();
523         }
524
525         /**
526          * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
527          * supplied class.
528          *
529          * <p>
530          * If class is
531          * <ul>
532          * <li>rpc input: local name is "input".
533          * <li>rpc output: local name is "output".
534          * <li>augmentation: local name is "module name".
535          * </ul>
536          *
537          * <p>
538          * There is also fallback, if it is not possible to compute QName using following algorithm returns module
539          * QName.
540          *
541          * @throws IllegalStateException If YangModuleInfo could not be resolved
542          * @throws IllegalArgumentException If supplied class was not derived from YANG model.
543          */
544         // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
545         @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
546         private static QName computeQName(final Class key) {
547             checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
548
549             YangModuleInfo moduleInfo;
550             try {
551                 moduleInfo = getModuleInfo(key);
552             } catch (Exception e) {
553                 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
554                     e);
555             }
556             final QName module = moduleInfo.getName();
557             if (Augmentation.class.isAssignableFrom(key)) {
558                 return module;
559             } else if (isRpcType(key)) {
560                 final String className = key.getSimpleName();
561                 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
562                     return YangConstants.operationOutputQName(module.getModule()).intern();
563                 }
564
565                 return YangConstants.operationInputQName(module.getModule()).intern();
566             }
567
568             /*
569              * Fallback for Binding types which do not have QNAME field
570              */
571             return module;
572         }
573     }
574
575     /**
576      * Extracts augmentation from Binding DTO field using reflection.
577      *
578      * @param input
579      *            Instance of DataObject which is augmentable and may contain
580      *            augmentation
581      * @return Map of augmentations if read was successful, otherwise empty map.
582      */
583     public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
584         if (input instanceof AugmentationHolder) {
585             return ((AugmentationHolder) input).augmentations();
586         }
587         return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
588     }
589
590     /**
591      * Determines if two augmentation classes or case classes represents same
592      * data.
593      *
594      * <p>
595      * Two augmentations or cases could be substituted only if and if:
596      * <ul>
597      * <li>Both implements same interfaces</li>
598      * <li>Both have same children</li>
599      * <li>If augmentations: Both have same augmentation target class. Target
600      * class was generated for data node in grouping.</li>
601      * <li>If cases: Both are from same choice. Choice class was generated for
602      * data node in grouping.</li>
603      * </ul>
604      *
605      * <p>
606      * <b>Explanation:</b> Binding Specification reuses classes generated for
607      * groupings as part of normal data tree, this classes from grouping could
608      * be used at various locations and user may not be aware of it and may use
609      * incorrect case or augmentation in particular subtree (via copy
610      * constructors, etc).
611      *
612      * @param potential
613      *            Class which is potential substitution
614      * @param target
615      *            Class which should be used at particular subtree
616      * @return true if and only if classes represents same data.
617      */
618     @SuppressWarnings({ "rawtypes", "unchecked" })
619     public static boolean isSubstitutionFor(final Class potential, final Class target) {
620         Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
621         Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
622         if (!subImplemented.equals(targetImplemented)) {
623             return false;
624         }
625         if (Augmentation.class.isAssignableFrom(potential)
626                 && !BindingReflections.findAugmentationTarget(potential).equals(
627                         BindingReflections.findAugmentationTarget(target))) {
628             return false;
629         }
630         for (Method potentialMethod : potential.getMethods()) {
631             try {
632                 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
633                 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
634                     return false;
635                 }
636             } catch (NoSuchMethodException e) {
637                 // Counterpart method is missing, so classes could not be substituted.
638                 return false;
639             } catch (SecurityException e) {
640                 throw new IllegalStateException("Could not compare methods", e);
641             }
642         }
643         return true;
644     }
645 }