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