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