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