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