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