Deprecate BindingReflections.isNotification()
[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      * @deprecated This method is only used internally and is schedule for removal
286      */
287     @Deprecated(since = "10.0.4", forRemoval = true)
288     public static boolean isNotification(final Class<?> potentialNotification) {
289         checkArgument(potentialNotification != null, "potentialNotification must not be null.");
290         return Notification.class.isAssignableFrom(potentialNotification);
291     }
292
293     /**
294      * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
295      * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
296      *
297      * @return Set of {@link YangModuleInfo} available for current classloader.
298      */
299     public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos() {
300         return loadModuleInfos(Thread.currentThread().getContextClassLoader());
301     }
302
303     /**
304      * Loads {@link YangModuleInfo} infos available on supplied classloader.
305      *
306      * <p>
307      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
308      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
309      * {@link YangModuleInfo}.
310      *
311      * <p>
312      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
313      * collecting results of {@link YangModuleInfo#getImportedModules()}.
314      *
315      * <p>
316      * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
317      *
318      * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
319      * @return Set of {@link YangModuleInfo} available for supplied classloader.
320      */
321     public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
322         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
323         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
324                 loader);
325         for (YangModelBindingProvider bindingProvider : serviceLoader) {
326             YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
327             checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
328             collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
329         }
330         return moduleInfoSet.build();
331     }
332
333     /**
334      * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available
335      * information does not change. Subsequent accesses may return cached values.
336      *
337      * <p>
338      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
339      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
340      * {@link YangModuleInfo}.
341      *
342      * <p>
343      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
344      * collecting results of {@link YangModuleInfo#getImportedModules()}.
345      *
346      * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
347      * @return Set of {@link YangModuleInfo} available for supplied classloader.
348      */
349     @Beta
350     public static @NonNull ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
351         return MODULE_INFO_CACHE.getUnchecked(loader);
352     }
353
354     private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
355             final Builder<YangModuleInfo> moduleInfoSet) {
356         moduleInfoSet.add(moduleInfo);
357         for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
358             collectYangModuleInfo(dependency, moduleInfoSet);
359         }
360     }
361
362     /**
363      * Checks if supplied class represents RPC Input / RPC Output.
364      *
365      * @param targetType
366      *            Class to be checked
367      * @return true if class represents RPC Input or RPC Output class.
368      */
369     public static boolean isRpcType(final Class<? extends DataObject> targetType) {
370         return DataContainer.class.isAssignableFrom(targetType)
371                 && !ChildOf.class.isAssignableFrom(targetType)
372                 && !Notification.class.isAssignableFrom(targetType)
373                 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
374     }
375
376     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
377
378         @Override
379         public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
380             return resolveQNameNoCache(key);
381         }
382
383         /**
384          * Tries to resolve QName for supplied class. Looks up for static field with name from constant
385          * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
386          * {@link #computeQName(Class)} to compute QName for missing types.
387          */
388         private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
389             try {
390                 final Field field;
391                 try {
392                     field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
393                 } catch (NoSuchFieldException e) {
394                     LOG.debug("{} does not have a {} field, falling back to computation", key,
395                         BindingMapping.QNAME_STATIC_FIELD_NAME, e);
396                     return Optional.of(computeQName(key));
397                 }
398
399                 final Object obj = field.get(null);
400                 if (obj instanceof QName qname) {
401                     return Optional.of(qname);
402                 }
403             } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
404                 /*
405                  * It is safe to log this this exception on debug, since this method should not fail. Only failures are
406                  * possible if the runtime / backing is inconsistent.
407                  */
408                 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
409             }
410             return Optional.empty();
411         }
412
413         /**
414          * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
415          * supplied class.
416          *
417          * <p>
418          * If class is
419          * <ul>
420          * <li>rpc input: local name is "input".
421          * <li>rpc output: local name is "output".
422          * <li>augmentation: local name is "module name".
423          * </ul>
424          *
425          * <p>
426          * There is also fallback, if it is not possible to compute QName using following algorithm returns module
427          * QName.
428          *
429          * @throws IllegalStateException If YangModuleInfo could not be resolved
430          * @throws IllegalArgumentException If supplied class was not derived from YANG model.
431          */
432         // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
433         @SuppressWarnings({ "rawtypes", "unchecked" })
434         private static QName computeQName(final Class key) {
435             checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
436
437             final QName module = getModuleInfo(key).getName();
438             if (Augmentation.class.isAssignableFrom(key)) {
439                 return module;
440             } else if (isRpcType(key)) {
441                 final String className = key.getSimpleName();
442                 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
443                     return YangConstants.operationOutputQName(module.getModule()).intern();
444                 }
445
446                 return YangConstants.operationInputQName(module.getModule()).intern();
447             }
448
449             /*
450              * Fallback for Binding types which do not have QNAME field
451              */
452             return module;
453         }
454     }
455
456     /**
457      * Determines if two augmentation classes or case classes represents same data.
458      *
459      * <p>
460      * Two augmentations or cases could be substituted only if and if:
461      * <ul>
462      *   <li>Both implements same interfaces</li>
463      *   <li>Both have same children</li>
464      *   <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
465      *       grouping.</li>
466      *   <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
467      * </ul>
468      *
469      * <p>
470      * <b>Explanation:</b>
471      * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
472      * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
473      * augmentation in particular subtree (via copy constructors, etc).
474      *
475      * @param potential Class which is potential substitution
476      * @param target Class which should be used at particular subtree
477      * @return true if and only if classes represents same data.
478      * @throws NullPointerException if any argument is {@code null}
479      */
480     // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
481     //                   user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
482     //                   a particular world this boils down to a matrix, which can be calculated either on-demand or
483     //                   when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
484     //                   to have a pre-compiled Binding Runtime.
485     @SuppressWarnings({ "rawtypes", "unchecked" })
486     public static boolean isSubstitutionFor(final Class potential, final Class target) {
487         Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
488         Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
489         if (!subImplemented.equals(targetImplemented)) {
490             return false;
491         }
492         if (Augmentation.class.isAssignableFrom(potential)
493                 && !BindingReflections.findAugmentationTarget(potential).equals(
494                         BindingReflections.findAugmentationTarget(target))) {
495             return false;
496         }
497         for (Method potentialMethod : potential.getMethods()) {
498             if (Modifier.isStatic(potentialMethod.getModifiers())) {
499                 // Skip any static methods, as we are not interested in those
500                 continue;
501             }
502
503             try {
504                 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
505                 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
506                     return false;
507                 }
508             } catch (NoSuchMethodException e) {
509                 // Counterpart method is missing, so classes could not be substituted.
510                 return false;
511             } catch (SecurityException e) {
512                 throw new IllegalStateException("Could not compare methods", e);
513             }
514         }
515         return true;
516     }
517 }