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