Hide BindingReflections.getModuleInfo()
[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     public static QNameModule getQNameModule(final Class<?> clz) {
127         if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
128                 || Action.class.isAssignableFrom(clz)) {
129             return findQName(clz).getModule();
130         }
131
132         return getModuleInfo(clz).getName().getModule();
133     }
134
135     /**
136      * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
137      *
138      * @param cls data object class
139      * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
140      */
141     private static @NonNull YangModuleInfo getModuleInfo(final Class<?> cls) {
142         final String packageName = Naming.getModelRootPackageName(cls.getPackage().getName());
143         final String potentialClassName = getModuleInfoClassName(packageName);
144         final Class<?> moduleInfoClass;
145         try {
146             moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
147         } catch (ClassNotFoundException e) {
148             throw new IllegalStateException("Failed to load " + potentialClassName, e);
149         }
150
151         final Object infoInstance;
152         try {
153             infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
154         } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
155             throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
156         }
157
158         checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
159         return (YangModuleInfo) infoInstance;
160     }
161
162     public static @NonNull String getModuleInfoClassName(final String packageName) {
163         return packageName + "." + Naming.MODULE_INFO_CLASS_NAME;
164     }
165
166     /**
167      * Check if supplied class is derived from YANG model.
168      *
169      * @param cls
170      *            Class to check
171      * @return true if class is derived from YANG model.
172      */
173     public static boolean isBindingClass(final Class<?> cls) {
174         if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
175             return true;
176         }
177         return cls.getName().startsWith(Naming.PACKAGE_PREFIX);
178     }
179
180     /**
181      * Checks if supplied method is callback for notifications.
182      *
183      * @param method method to check
184      * @return true if method is notification callback.
185      */
186     public static boolean isNotificationCallback(final Method method) {
187         checkArgument(method != null);
188         if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
189             Class<?> potentialNotification = method.getParameterTypes()[0];
190             if (isNotification(potentialNotification)
191                     && method.getName().equals("on" + potentialNotification.getSimpleName())) {
192                 return true;
193             }
194         }
195         return false;
196     }
197
198     /**
199      * Checks is supplied class is a {@link Notification}.
200      *
201      * @param potentialNotification class to examine
202      * @return True if the class represents a Notification.
203      */
204     @VisibleForTesting
205     static boolean isNotification(final Class<?> potentialNotification) {
206         checkArgument(potentialNotification != null, "potentialNotification must not be null.");
207         return Notification.class.isAssignableFrom(potentialNotification);
208     }
209
210     /**
211      * Loads {@link YangModuleInfo} infos available on supplied classloader.
212      *
213      * <p>
214      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
215      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
216      * {@link YangModuleInfo}.
217      *
218      * <p>
219      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
220      * collecting results of {@link YangModuleInfo#getImportedModules()}.
221      *
222      * <p>
223      * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
224      *
225      * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
226      * @return Set of {@link YangModuleInfo} available for supplied classloader.
227      */
228     public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
229         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
230         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
231                 loader);
232         for (YangModelBindingProvider bindingProvider : serviceLoader) {
233             YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
234             checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
235             collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
236         }
237         return moduleInfoSet.build();
238     }
239
240     /**
241      * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available
242      * information does not change. Subsequent accesses may return cached values.
243      *
244      * <p>
245      * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
246      * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
247      * {@link YangModuleInfo}.
248      *
249      * <p>
250      * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
251      * collecting results of {@link YangModuleInfo#getImportedModules()}.
252      *
253      * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
254      * @return Set of {@link YangModuleInfo} available for supplied classloader.
255      */
256     @Beta
257     public static @NonNull ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
258         return MODULE_INFO_CACHE.getUnchecked(loader);
259     }
260
261     private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
262             final Builder<YangModuleInfo> moduleInfoSet) {
263         moduleInfoSet.add(moduleInfo);
264         for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
265             collectYangModuleInfo(dependency, moduleInfoSet);
266         }
267     }
268
269     /**
270      * Checks if supplied class represents RPC Input / RPC Output.
271      *
272      * @param targetType
273      *            Class to be checked
274      * @return true if class represents RPC Input or RPC Output class.
275      */
276     public static boolean isRpcType(final Class<? extends DataObject> targetType) {
277         return DataContainer.class.isAssignableFrom(targetType)
278                 && !ChildOf.class.isAssignableFrom(targetType)
279                 && !Notification.class.isAssignableFrom(targetType)
280                 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
281     }
282
283     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
284
285         @Override
286         public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
287             return resolveQNameNoCache(key);
288         }
289
290         /**
291          * Tries to resolve QName for supplied class. Looks up for static field with name from constant
292          * {@link Naming#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
293          * {@link #computeQName(Class)} to compute QName for missing types.
294          */
295         private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
296             try {
297                 final Field field;
298                 try {
299                     field = key.getField(Naming.QNAME_STATIC_FIELD_NAME);
300                 } catch (NoSuchFieldException e) {
301                     LOG.debug("{} does not have a {} field, falling back to computation", key,
302                         Naming.QNAME_STATIC_FIELD_NAME, e);
303                     return Optional.of(computeQName(key));
304                 }
305
306                 final Object obj = field.get(null);
307                 if (obj instanceof QName qname) {
308                     return Optional.of(qname);
309                 }
310             } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
311                 /*
312                  * It is safe to log this this exception on debug, since this method should not fail. Only failures are
313                  * possible if the runtime / backing is inconsistent.
314                  */
315                 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
316             }
317             return Optional.empty();
318         }
319
320         /**
321          * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
322          * supplied class.
323          *
324          * <p>
325          * If class is
326          * <ul>
327          * <li>rpc input: local name is "input".
328          * <li>rpc output: local name is "output".
329          * <li>augmentation: local name is "module name".
330          * </ul>
331          *
332          * <p>
333          * There is also fallback, if it is not possible to compute QName using following algorithm returns module
334          * QName.
335          *
336          * @throws IllegalStateException If YangModuleInfo could not be resolved
337          * @throws IllegalArgumentException If supplied class was not derived from YANG model.
338          */
339         // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
340         @SuppressWarnings({ "rawtypes", "unchecked" })
341         private static QName computeQName(final Class key) {
342             checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
343
344             final QName module = getModuleInfo(key).getName();
345             if (Augmentation.class.isAssignableFrom(key)) {
346                 return module;
347             } else if (isRpcType(key)) {
348                 final String className = key.getSimpleName();
349                 if (className.endsWith(Naming.RPC_OUTPUT_SUFFIX)) {
350                     return YangConstants.operationOutputQName(module.getModule()).intern();
351                 }
352
353                 return YangConstants.operationInputQName(module.getModule()).intern();
354             }
355
356             /*
357              * Fallback for Binding types which do not have QNAME field
358              */
359             return module;
360         }
361     }
362 }