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