Move BindingReflections.getChildrenClass*
[mdsal.git] / binding / mdsal-binding-spec-util / src / main / java / org / opendaylight / mdsal / binding / spec / reflect / BindingReflections.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.spec.reflect;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.ImmutableSet.Builder;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.lang.reflect.Modifier;
24 import java.lang.reflect.Type;
25 import java.util.Arrays;
26 import java.util.HashSet;
27 import java.util.Optional;
28 import java.util.ServiceLoader;
29 import java.util.Set;
30 import java.util.concurrent.TimeUnit;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import org.checkerframework.checker.regex.qual.Regex;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
36 import org.opendaylight.yangtools.util.ClassLoaderUtils;
37 import org.opendaylight.yangtools.yang.binding.Action;
38 import org.opendaylight.yangtools.yang.binding.Augmentable;
39 import org.opendaylight.yangtools.yang.binding.Augmentation;
40 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
41 import org.opendaylight.yangtools.yang.binding.BindingContract;
42 import org.opendaylight.yangtools.yang.binding.ChildOf;
43 import org.opendaylight.yangtools.yang.binding.DataContainer;
44 import org.opendaylight.yangtools.yang.binding.DataObject;
45 import org.opendaylight.yangtools.yang.binding.Notification;
46 import org.opendaylight.yangtools.yang.binding.Rpc;
47 import org.opendaylight.yangtools.yang.binding.RpcService;
48 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
49 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.common.QNameModule;
52 import org.opendaylight.yangtools.yang.common.YangConstants;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 public final class BindingReflections {
57
58     private static final long EXPIRATION_TIME = 60;
59
60     @Regex
61     private static final String ROOT_PACKAGE_PATTERN_STRING =
62             "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.(?:rev[0-9][0-9][0-1][0-9][0-3][0-9]|norev))";
63     private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
64     private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
65
66     private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
67             .weakKeys()
68             .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
69             .build(new ClassToQNameLoader());
70
71     private static final LoadingCache<ClassLoader, ImmutableSet<YangModuleInfo>> MODULE_INFO_CACHE =
72             CacheBuilder.newBuilder().weakKeys().weakValues().build(
73                 new CacheLoader<ClassLoader, ImmutableSet<YangModuleInfo>>() {
74                     @Override
75                     public ImmutableSet<YangModuleInfo> load(final ClassLoader key) {
76                         return loadModuleInfos(key);
77                     }
78                 });
79
80     private BindingReflections() {
81         // Hidden on purpose
82     }
83
84     /**
85      * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
86      * implemented {@link Augmentation} interface.
87      *
88      * @param augmentation
89      *            {@link Augmentation} subclass for which we want to determine
90      *            augmentation target.
91      * @return Augmentation target - class which augmentation provides additional extensions.
92      */
93     public static Class<? extends Augmentable<?>> findAugmentationTarget(
94             final Class<? extends Augmentation<?>> augmentation) {
95         final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
96             Augmentation.class);
97         return opt.orElse(null);
98     }
99
100     /**
101      * Returns a QName associated to supplied type.
102      *
103      * @param dataType Data type class
104      * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
105      *         QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
106      *         have name. May return null if QName is not present.
107      */
108     public static QName findQName(final Class<?> dataType) {
109         return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
110     }
111
112     /**
113      * Checks if method is RPC invocation.
114      *
115      * @param possibleMethod
116      *            Method to check
117      * @return true if method is RPC invocation, false otherwise.
118      */
119     public static boolean isRpcMethod(final Method possibleMethod) {
120         return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
121                 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
122                 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
123                 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
124                 // non input type and two arguments for input type, resolveRpcInputClass() counting
125                 // with zero for non input and one for input type
126                 && possibleMethod.getParameterCount() <= 2;
127     }
128
129     /**
130      * Extracts Output class for RPC method.
131      *
132      * @param targetMethod method to scan
133      * @return Optional.empty() if result type could not be get, or return type is Void.
134      * @deprecated This method is unused and scheduled for removal
135      */
136     @Deprecated(since = "10.0.4", forRemoval = true)
137     @SuppressWarnings("rawtypes")
138     public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
139         checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
140         Type futureType = targetMethod.getGenericReturnType();
141         Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType).orElse(null);
142         Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType).orElse(null);
143         if (rpcResultArgument instanceof Class cls && !Void.class.equals(rpcResultArgument)) {
144             return Optional.of(cls);
145         }
146         return Optional.empty();
147     }
148
149     /**
150      * Extracts input class for RPC method.
151      *
152      * @param targetMethod method to scan
153      * @return Optional.empty() if RPC has no input, RPC input type otherwise.
154      * @deprecated This method is unused and scheduled for removal
155      */
156     @Deprecated(since = "10.0.4", forRemoval = true)
157     @SuppressWarnings("rawtypes")
158     public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
159         for (Class clazz : targetMethod.getParameterTypes()) {
160             if (DataContainer.class.isAssignableFrom(clazz)) {
161                 return Optional.of(clazz);
162             }
163         }
164         return Optional.empty();
165     }
166
167     public static @NonNull QName getQName(final BaseIdentity identity) {
168         return getContractQName(identity);
169     }
170
171     public static @NonNull QName getQName(final Rpc<?, ?> rpc) {
172         return getContractQName(rpc);
173     }
174
175     private static @NonNull QName getContractQName(final BindingContract<?> contract) {
176         return CLASS_TO_QNAME.getUnchecked(contract.implementedInterface())
177             .orElseThrow(() -> new IllegalStateException("Failed to resolve QName of " + contract));
178     }
179
180     /**
181      * Returns root package name for supplied package.
182      *
183      * @param pkg
184      *            Package for which find model root package.
185      * @return Package of model root.
186      */
187     public static String getModelRootPackageName(final Package pkg) {
188         return getModelRootPackageName(pkg.getName());
189     }
190
191     /**
192      * Returns root package name for supplied package name.
193      *
194      * @param name
195      *            Package for which find model root package.
196      * @return Package of model root.
197      */
198     public static String getModelRootPackageName(final String name) {
199         checkArgument(name != null, "Package name should not be null.");
200         checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
201                 BindingMapping.PACKAGE_PREFIX, name);
202         Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
203         checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
204                 ROOT_PACKAGE_PATTERN_STRING);
205         return match.group(0);
206     }
207
208     public static QNameModule getQNameModule(final Class<?> clz) {
209         if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
210                 || Action.class.isAssignableFrom(clz)) {
211             return findQName(clz).getModule();
212         }
213
214         return getModuleInfo(clz).getName().getModule();
215     }
216
217     /**
218      * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
219      *
220      * @param cls data object class
221      * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
222      */
223     public static @NonNull YangModuleInfo getModuleInfo(final Class<?> cls) {
224         final String packageName = getModelRootPackageName(cls.getPackage());
225         final String potentialClassName = getModuleInfoClassName(packageName);
226         final Class<?> moduleInfoClass;
227         try {
228             moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
229         } catch (ClassNotFoundException e) {
230             throw new IllegalStateException("Failed to load " + potentialClassName, e);
231         }
232
233         final Object infoInstance;
234         try {
235             infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
236         } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
237             throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
238         }
239
240         checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
241         return (YangModuleInfo) infoInstance;
242     }
243
244     public static @NonNull String getModuleInfoClassName(final String packageName) {
245         return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
246     }
247
248     /**
249      * Check if supplied class is derived from YANG model.
250      *
251      * @param cls
252      *            Class to check
253      * @return true if class is derived from YANG model.
254      */
255     public static boolean isBindingClass(final Class<?> cls) {
256         if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
257             return true;
258         }
259         return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
260     }
261
262     /**
263      * Checks if supplied method is callback for notifications.
264      *
265      * @param method method to check
266      * @return true if method is notification callback.
267      */
268     public static boolean isNotificationCallback(final Method method) {
269         checkArgument(method != null);
270         if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
271             Class<?> potentialNotification = method.getParameterTypes()[0];
272             if (isNotification(potentialNotification)
273                     && method.getName().equals("on" + potentialNotification.getSimpleName())) {
274                 return true;
275             }
276         }
277         return false;
278     }
279
280     /**
281      * Checks is supplied class is a {@link Notification}.
282      *
283      * @param potentialNotification class to examine
284      * @return True if the class represents a Notification.
285      */
286     public static boolean isNotification(final Class<?> potentialNotification) {
287         checkArgument(potentialNotification != null, "potentialNotification must not be null.");
288         return Notification.class.isAssignableFrom(potentialNotification);
289     }
290
291     /**
292      * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
293      * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
294      *
295      * @return Set of {@link YangModuleInfo} available for current classloader.
296      */
297     public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos() {
298         return loadModuleInfos(Thread.currentThread().getContextClassLoader());
299     }
300
301     /**
302      * Loads {@link YangModuleInfo} infos available on supplied classloader.
303      *
304      * <p>
305      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
306      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
307      * {@link YangModuleInfo}.
308      *
309      * <p>
310      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
311      * collecting results of {@link YangModuleInfo#getImportedModules()}.
312      *
313      * <p>
314      * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
315      *
316      * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
317      * @return Set of {@link YangModuleInfo} available for supplied classloader.
318      */
319     public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
320         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
321         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
322                 loader);
323         for (YangModelBindingProvider bindingProvider : serviceLoader) {
324             YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
325             checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
326             collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
327         }
328         return moduleInfoSet.build();
329     }
330
331     /**
332      * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available
333      * information does not change. Subsequent accesses may return cached values.
334      *
335      * <p>
336      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
337      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
338      * {@link YangModuleInfo}.
339      *
340      * <p>
341      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
342      * collecting results of {@link YangModuleInfo#getImportedModules()}.
343      *
344      * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
345      * @return Set of {@link YangModuleInfo} available for supplied classloader.
346      */
347     @Beta
348     public static @NonNull ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
349         return MODULE_INFO_CACHE.getUnchecked(loader);
350     }
351
352     private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
353             final Builder<YangModuleInfo> moduleInfoSet) {
354         moduleInfoSet.add(moduleInfo);
355         for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
356             collectYangModuleInfo(dependency, moduleInfoSet);
357         }
358     }
359
360     /**
361      * Checks if supplied class represents RPC Input / RPC Output.
362      *
363      * @param targetType
364      *            Class to be checked
365      * @return true if class represents RPC Input or RPC Output class.
366      */
367     public static boolean isRpcType(final Class<? extends DataObject> targetType) {
368         return DataContainer.class.isAssignableFrom(targetType)
369                 && !ChildOf.class.isAssignableFrom(targetType)
370                 && !Notification.class.isAssignableFrom(targetType)
371                 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
372     }
373
374     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
375
376         @Override
377         public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
378             return resolveQNameNoCache(key);
379         }
380
381         /**
382          * Tries to resolve QName for supplied class. Looks up for static field with name from constant
383          * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
384          * {@link #computeQName(Class)} to compute QName for missing types.
385          */
386         private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
387             try {
388                 final Field field;
389                 try {
390                     field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
391                 } catch (NoSuchFieldException e) {
392                     LOG.debug("{} does not have a {} field, falling back to computation", key,
393                         BindingMapping.QNAME_STATIC_FIELD_NAME, e);
394                     return Optional.of(computeQName(key));
395                 }
396
397                 final Object obj = field.get(null);
398                 if (obj instanceof QName qname) {
399                     return Optional.of(qname);
400                 }
401             } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
402                 /*
403                  * It is safe to log this this exception on debug, since this method should not fail. Only failures are
404                  * possible if the runtime / backing is inconsistent.
405                  */
406                 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
407             }
408             return Optional.empty();
409         }
410
411         /**
412          * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
413          * supplied class.
414          *
415          * <p>
416          * If class is
417          * <ul>
418          * <li>rpc input: local name is "input".
419          * <li>rpc output: local name is "output".
420          * <li>augmentation: local name is "module name".
421          * </ul>
422          *
423          * <p>
424          * There is also fallback, if it is not possible to compute QName using following algorithm returns module
425          * QName.
426          *
427          * @throws IllegalStateException If YangModuleInfo could not be resolved
428          * @throws IllegalArgumentException If supplied class was not derived from YANG model.
429          */
430         // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
431         @SuppressWarnings({ "rawtypes", "unchecked" })
432         private static QName computeQName(final Class key) {
433             checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
434
435             final QName module = getModuleInfo(key).getName();
436             if (Augmentation.class.isAssignableFrom(key)) {
437                 return module;
438             } else if (isRpcType(key)) {
439                 final String className = key.getSimpleName();
440                 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
441                     return YangConstants.operationOutputQName(module.getModule()).intern();
442                 }
443
444                 return YangConstants.operationInputQName(module.getModule()).intern();
445             }
446
447             /*
448              * Fallback for Binding types which do not have QNAME field
449              */
450             return module;
451         }
452     }
453
454     /**
455      * Determines if two augmentation classes or case classes represents same data.
456      *
457      * <p>
458      * Two augmentations or cases could be substituted only if and if:
459      * <ul>
460      *   <li>Both implements same interfaces</li>
461      *   <li>Both have same children</li>
462      *   <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
463      *       grouping.</li>
464      *   <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
465      * </ul>
466      *
467      * <p>
468      * <b>Explanation:</b>
469      * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
470      * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
471      * augmentation in particular subtree (via copy constructors, etc).
472      *
473      * @param potential Class which is potential substitution
474      * @param target Class which should be used at particular subtree
475      * @return true if and only if classes represents same data.
476      * @throws NullPointerException if any argument is {@code null}
477      */
478     // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
479     //                   user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
480     //                   a particular world this boils down to a matrix, which can be calculated either on-demand or
481     //                   when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
482     //                   to have a pre-compiled Binding Runtime.
483     @SuppressWarnings({ "rawtypes", "unchecked" })
484     public static boolean isSubstitutionFor(final Class potential, final Class target) {
485         Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
486         Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
487         if (!subImplemented.equals(targetImplemented)) {
488             return false;
489         }
490         if (Augmentation.class.isAssignableFrom(potential)
491                 && !BindingReflections.findAugmentationTarget(potential).equals(
492                         BindingReflections.findAugmentationTarget(target))) {
493             return false;
494         }
495         for (Method potentialMethod : potential.getMethods()) {
496             if (Modifier.isStatic(potentialMethod.getModifiers())) {
497                 // Skip any static methods, as we are not interested in those
498                 continue;
499             }
500
501             try {
502                 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
503                 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
504                     return false;
505                 }
506             } catch (NoSuchMethodException e) {
507                 // Counterpart method is missing, so classes could not be substituted.
508                 return false;
509             } catch (SecurityException e) {
510                 throw new IllegalStateException("Could not compare methods", e);
511             }
512         }
513         return true;
514     }
515 }