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