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