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