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