Remove BindingReflections.resolveRpc{In,Out}putClass()
[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.annotations.VisibleForTesting;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.ImmutableSet.Builder;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import java.lang.reflect.Field;
22 import java.lang.reflect.InvocationTargetException;
23 import java.lang.reflect.Method;
24 import java.util.Optional;
25 import java.util.ServiceLoader;
26 import java.util.concurrent.TimeUnit;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import org.checkerframework.checker.regex.qual.Regex;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
32 import org.opendaylight.yangtools.util.ClassLoaderUtils;
33 import org.opendaylight.yangtools.yang.binding.Action;
34 import org.opendaylight.yangtools.yang.binding.Augmentable;
35 import org.opendaylight.yangtools.yang.binding.Augmentation;
36 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
37 import org.opendaylight.yangtools.yang.binding.BindingContract;
38 import org.opendaylight.yangtools.yang.binding.ChildOf;
39 import org.opendaylight.yangtools.yang.binding.DataContainer;
40 import org.opendaylight.yangtools.yang.binding.DataObject;
41 import org.opendaylight.yangtools.yang.binding.Notification;
42 import org.opendaylight.yangtools.yang.binding.Rpc;
43 import org.opendaylight.yangtools.yang.binding.RpcService;
44 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
45 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.common.QNameModule;
48 import org.opendaylight.yangtools.yang.common.YangConstants;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 public final class BindingReflections {
53
54     private static final long EXPIRATION_TIME = 60;
55
56     @Regex
57     private static final String ROOT_PACKAGE_PATTERN_STRING =
58             "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.(?:rev[0-9][0-9][0-1][0-9][0-3][0-9]|norev))";
59     private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
60     private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
61
62     private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
63             .weakKeys()
64             .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
65             .build(new ClassToQNameLoader());
66
67     private static final LoadingCache<ClassLoader, ImmutableSet<YangModuleInfo>> MODULE_INFO_CACHE =
68             CacheBuilder.newBuilder().weakKeys().weakValues().build(
69                 new CacheLoader<ClassLoader, ImmutableSet<YangModuleInfo>>() {
70                     @Override
71                     public ImmutableSet<YangModuleInfo> load(final ClassLoader key) {
72                         return loadModuleInfos(key);
73                     }
74                 });
75
76     private BindingReflections() {
77         // Hidden on purpose
78     }
79
80     /**
81      * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
82      * implemented {@link Augmentation} interface.
83      *
84      * @param augmentation
85      *            {@link Augmentation} subclass for which we want to determine
86      *            augmentation target.
87      * @return Augmentation target - class which augmentation provides additional extensions.
88      */
89     public static Class<? extends Augmentable<?>> findAugmentationTarget(
90             final Class<? extends Augmentation<?>> augmentation) {
91         final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
92             Augmentation.class);
93         return opt.orElse(null);
94     }
95
96     /**
97      * Returns a QName associated to supplied type.
98      *
99      * @param dataType Data type class
100      * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
101      *         QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
102      *         have name. May return null if QName is not present.
103      */
104     public static QName findQName(final Class<?> dataType) {
105         return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
106     }
107
108     /**
109      * Checks if method is RPC invocation.
110      *
111      * @param possibleMethod
112      *            Method to check
113      * @return true if method is RPC invocation, false otherwise.
114      */
115     public static boolean isRpcMethod(final Method possibleMethod) {
116         return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
117                 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
118                 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
119                 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
120                 // non input type and two arguments for input type, resolveRpcInputClass() counting
121                 // with zero for non input and one for input type
122                 && possibleMethod.getParameterCount() <= 2;
123     }
124
125     public static @NonNull QName getQName(final BaseIdentity identity) {
126         return getContractQName(identity);
127     }
128
129     public static @NonNull QName getQName(final Rpc<?, ?> rpc) {
130         return getContractQName(rpc);
131     }
132
133     private static @NonNull QName getContractQName(final BindingContract<?> contract) {
134         return CLASS_TO_QNAME.getUnchecked(contract.implementedInterface())
135             .orElseThrow(() -> new IllegalStateException("Failed to resolve QName of " + contract));
136     }
137
138     /**
139      * Returns root package name for supplied package.
140      *
141      * @param pkg
142      *            Package for which find model root package.
143      * @return Package of model root.
144      */
145     public static String getModelRootPackageName(final Package pkg) {
146         return getModelRootPackageName(pkg.getName());
147     }
148
149     /**
150      * Returns root package name for supplied package name.
151      *
152      * @param name
153      *            Package for which find model root package.
154      * @return Package of model root.
155      */
156     public static String getModelRootPackageName(final String name) {
157         checkArgument(name != null, "Package name should not be null.");
158         checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
159                 BindingMapping.PACKAGE_PREFIX, name);
160         Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
161         checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
162                 ROOT_PACKAGE_PATTERN_STRING);
163         return match.group(0);
164     }
165
166     public static QNameModule getQNameModule(final Class<?> clz) {
167         if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
168                 || Action.class.isAssignableFrom(clz)) {
169             return findQName(clz).getModule();
170         }
171
172         return getModuleInfo(clz).getName().getModule();
173     }
174
175     /**
176      * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
177      *
178      * @param cls data object class
179      * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
180      */
181     public static @NonNull YangModuleInfo getModuleInfo(final Class<?> cls) {
182         final String packageName = getModelRootPackageName(cls.getPackage());
183         final String potentialClassName = getModuleInfoClassName(packageName);
184         final Class<?> moduleInfoClass;
185         try {
186             moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
187         } catch (ClassNotFoundException e) {
188             throw new IllegalStateException("Failed to load " + potentialClassName, e);
189         }
190
191         final Object infoInstance;
192         try {
193             infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
194         } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
195             throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
196         }
197
198         checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
199         return (YangModuleInfo) infoInstance;
200     }
201
202     public static @NonNull String getModuleInfoClassName(final String packageName) {
203         return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
204     }
205
206     /**
207      * Check if supplied class is derived from YANG model.
208      *
209      * @param cls
210      *            Class to check
211      * @return true if class is derived from YANG model.
212      */
213     public static boolean isBindingClass(final Class<?> cls) {
214         if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
215             return true;
216         }
217         return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
218     }
219
220     /**
221      * Checks if supplied method is callback for notifications.
222      *
223      * @param method method to check
224      * @return true if method is notification callback.
225      */
226     public static boolean isNotificationCallback(final Method method) {
227         checkArgument(method != null);
228         if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
229             Class<?> potentialNotification = method.getParameterTypes()[0];
230             if (isNotification(potentialNotification)
231                     && method.getName().equals("on" + potentialNotification.getSimpleName())) {
232                 return true;
233             }
234         }
235         return false;
236     }
237
238     /**
239      * Checks is supplied class is a {@link Notification}.
240      *
241      * @param potentialNotification class to examine
242      * @return True if the class represents a Notification.
243      */
244     @VisibleForTesting
245     static boolean isNotification(final Class<?> potentialNotification) {
246         checkArgument(potentialNotification != null, "potentialNotification must not be null.");
247         return Notification.class.isAssignableFrom(potentialNotification);
248     }
249
250     /**
251      * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
252      * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
253      *
254      * @return Set of {@link YangModuleInfo} available for current classloader.
255      */
256     public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos() {
257         return loadModuleInfos(Thread.currentThread().getContextClassLoader());
258     }
259
260     /**
261      * Loads {@link YangModuleInfo} infos available on supplied classloader.
262      *
263      * <p>
264      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
265      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
266      * {@link YangModuleInfo}.
267      *
268      * <p>
269      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
270      * collecting results of {@link YangModuleInfo#getImportedModules()}.
271      *
272      * <p>
273      * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
274      *
275      * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
276      * @return Set of {@link YangModuleInfo} available for supplied classloader.
277      */
278     public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
279         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
280         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
281                 loader);
282         for (YangModelBindingProvider bindingProvider : serviceLoader) {
283             YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
284             checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
285             collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
286         }
287         return moduleInfoSet.build();
288     }
289
290     /**
291      * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available
292      * information does not change. Subsequent accesses may return cached values.
293      *
294      * <p>
295      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
296      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
297      * {@link YangModuleInfo}.
298      *
299      * <p>
300      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
301      * collecting results of {@link YangModuleInfo#getImportedModules()}.
302      *
303      * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
304      * @return Set of {@link YangModuleInfo} available for supplied classloader.
305      */
306     @Beta
307     public static @NonNull ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
308         return MODULE_INFO_CACHE.getUnchecked(loader);
309     }
310
311     private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
312             final Builder<YangModuleInfo> moduleInfoSet) {
313         moduleInfoSet.add(moduleInfo);
314         for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
315             collectYangModuleInfo(dependency, moduleInfoSet);
316         }
317     }
318
319     /**
320      * Checks if supplied class represents RPC Input / RPC Output.
321      *
322      * @param targetType
323      *            Class to be checked
324      * @return true if class represents RPC Input or RPC Output class.
325      */
326     public static boolean isRpcType(final Class<? extends DataObject> targetType) {
327         return DataContainer.class.isAssignableFrom(targetType)
328                 && !ChildOf.class.isAssignableFrom(targetType)
329                 && !Notification.class.isAssignableFrom(targetType)
330                 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
331     }
332
333     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
334
335         @Override
336         public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
337             return resolveQNameNoCache(key);
338         }
339
340         /**
341          * Tries to resolve QName for supplied class. Looks up for static field with name from constant
342          * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
343          * {@link #computeQName(Class)} to compute QName for missing types.
344          */
345         private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
346             try {
347                 final Field field;
348                 try {
349                     field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
350                 } catch (NoSuchFieldException e) {
351                     LOG.debug("{} does not have a {} field, falling back to computation", key,
352                         BindingMapping.QNAME_STATIC_FIELD_NAME, e);
353                     return Optional.of(computeQName(key));
354                 }
355
356                 final Object obj = field.get(null);
357                 if (obj instanceof QName qname) {
358                     return Optional.of(qname);
359                 }
360             } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
361                 /*
362                  * It is safe to log this this exception on debug, since this method should not fail. Only failures are
363                  * possible if the runtime / backing is inconsistent.
364                  */
365                 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
366             }
367             return Optional.empty();
368         }
369
370         /**
371          * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
372          * supplied class.
373          *
374          * <p>
375          * If class is
376          * <ul>
377          * <li>rpc input: local name is "input".
378          * <li>rpc output: local name is "output".
379          * <li>augmentation: local name is "module name".
380          * </ul>
381          *
382          * <p>
383          * There is also fallback, if it is not possible to compute QName using following algorithm returns module
384          * QName.
385          *
386          * @throws IllegalStateException If YangModuleInfo could not be resolved
387          * @throws IllegalArgumentException If supplied class was not derived from YANG model.
388          */
389         // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
390         @SuppressWarnings({ "rawtypes", "unchecked" })
391         private static QName computeQName(final Class key) {
392             checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
393
394             final QName module = getModuleInfo(key).getName();
395             if (Augmentation.class.isAssignableFrom(key)) {
396                 return module;
397             } else if (isRpcType(key)) {
398                 final String className = key.getSimpleName();
399                 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
400                     return YangConstants.operationOutputQName(module.getModule()).intern();
401                 }
402
403                 return YangConstants.operationInputQName(module.getModule()).intern();
404             }
405
406             /*
407              * Fallback for Binding types which do not have QNAME field
408              */
409             return module;
410         }
411     }
412 }