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