2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.spec.reflect;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
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;
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()
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>>() {
59 public ImmutableSet<YangModuleInfo> load(final ClassLoader key) {
60 return loadModuleInfos(key);
64 private BindingReflections() {
69 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
70 * implemented {@link Augmentation} interface.
73 * {@link Augmentation} subclass for which we want to determine
74 * augmentation target.
75 * @return Augmentation target - class which augmentation provides additional extensions.
77 public static Class<? extends Augmentable<?>> findAugmentationTarget(
78 final Class<? extends Augmentation<?>> augmentation) {
79 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
81 return opt.orElse(null);
85 * Returns a QName associated to supplied type.
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.
92 public static QName findQName(final Class<?> dataType) {
93 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
97 * Checks if method is RPC invocation.
99 * @param possibleMethod
101 * @return true if method is RPC invocation, false otherwise.
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;
113 public static @NonNull QName getQName(final BaseIdentity identity) {
114 return getContractQName(identity);
117 public static @NonNull QName getQName(final Rpc<?, ?> rpc) {
118 return getContractQName(rpc);
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));
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();
132 return getModuleInfo(clz).getName().getModule();
136 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
138 * @param cls data object class
139 * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
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;
146 moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
147 } catch (ClassNotFoundException e) {
148 throw new IllegalStateException("Failed to load " + potentialClassName, e);
151 final Object infoInstance;
153 infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
154 } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
155 throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
158 checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
159 return (YangModuleInfo) infoInstance;
162 public static @NonNull String getModuleInfoClassName(final String packageName) {
163 return packageName + "." + Naming.MODULE_INFO_CLASS_NAME;
167 * Check if supplied class is derived from YANG model.
171 * @return true if class is derived from YANG model.
173 public static boolean isBindingClass(final Class<?> cls) {
174 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
177 return cls.getName().startsWith(Naming.PACKAGE_PREFIX);
181 * Checks if supplied method is callback for notifications.
183 * @param method method to check
184 * @return true if method is notification callback.
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())) {
199 * Checks is supplied class is a {@link Notification}.
201 * @param potentialNotification class to examine
202 * @return True if the class represents a Notification.
205 static boolean isNotification(final Class<?> potentialNotification) {
206 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
207 return Notification.class.isAssignableFrom(potentialNotification);
211 * Loads {@link YangModuleInfo} infos available on supplied classloader.
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}.
219 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
220 * collecting results of {@link YangModuleInfo#getImportedModules()}.
223 * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
225 * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
226 * @return Set of {@link YangModuleInfo} available for supplied classloader.
228 public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
229 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
230 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
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);
237 return moduleInfoSet.build();
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.
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}.
250 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
251 * collecting results of {@link YangModuleInfo#getImportedModules()}.
253 * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
254 * @return Set of {@link YangModuleInfo} available for supplied classloader.
257 public static @NonNull ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
258 return MODULE_INFO_CACHE.getUnchecked(loader);
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);
270 * Checks if supplied class represents RPC Input / RPC Output.
273 * Class to be checked
274 * @return true if class represents RPC Input or RPC Output class.
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"));
283 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
286 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
287 return resolveQNameNoCache(key);
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.
295 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
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));
306 final Object obj = field.get(null);
307 if (obj instanceof QName qname) {
308 return Optional.of(qname);
310 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
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.
315 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
317 return Optional.empty();
321 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
327 * <li>rpc input: local name is "input".
328 * <li>rpc output: local name is "output".
329 * <li>augmentation: local name is "module name".
333 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
336 * @throws IllegalStateException If YangModuleInfo could not be resolved
337 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
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);
344 final QName module = getModuleInfo(key).getName();
345 if (Augmentation.class.isAssignableFrom(key)) {
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();
353 return YangConstants.operationInputQName(module.getModule()).intern();
357 * Fallback for Binding types which do not have QNAME field