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));
127 * Returns root package name for supplied package.
129 * @param pkg Package for which find model root package.
130 * @deprecated Use {@link Naming#getModelRootPackageName(String)} instead.
132 @Deprecated(since = "11.0.3", forRemoval = true)
133 public static String getModelRootPackageName(final Package pkg) {
134 return getModelRootPackageName(pkg.getName());
138 * Returns root package name for supplied package name.
140 * @param name Package for which find model root package.
141 * @return Package of model root.
142 * @deprecated Use {@link Naming#getModelRootPackageName(String)} instead.
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);
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();
156 return getModuleInfo(clz).getName().getModule();
160 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
162 * @param cls data object class
163 * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
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;
170 moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
171 } catch (ClassNotFoundException e) {
172 throw new IllegalStateException("Failed to load " + potentialClassName, e);
175 final Object infoInstance;
177 infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
178 } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
179 throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
182 checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
183 return (YangModuleInfo) infoInstance;
186 public static @NonNull String getModuleInfoClassName(final String packageName) {
187 return packageName + "." + Naming.MODULE_INFO_CLASS_NAME;
191 * Check if supplied class is derived from YANG model.
195 * @return true if class is derived from YANG model.
197 public static boolean isBindingClass(final Class<?> cls) {
198 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
201 return cls.getName().startsWith(Naming.PACKAGE_PREFIX);
205 * Checks if supplied method is callback for notifications.
207 * @param method method to check
208 * @return true if method is notification callback.
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())) {
223 * Checks is supplied class is a {@link Notification}.
225 * @param potentialNotification class to examine
226 * @return True if the class represents a Notification.
229 static boolean isNotification(final Class<?> potentialNotification) {
230 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
231 return Notification.class.isAssignableFrom(potentialNotification);
235 * Loads {@link YangModuleInfo} infos available on supplied classloader.
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}.
243 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
244 * collecting results of {@link YangModuleInfo#getImportedModules()}.
247 * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
249 * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
250 * @return Set of {@link YangModuleInfo} available for supplied classloader.
252 public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
253 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
254 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
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);
261 return moduleInfoSet.build();
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.
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}.
274 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
275 * collecting results of {@link YangModuleInfo#getImportedModules()}.
277 * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
278 * @return Set of {@link YangModuleInfo} available for supplied classloader.
281 public static @NonNull ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
282 return MODULE_INFO_CACHE.getUnchecked(loader);
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);
294 * Checks if supplied class represents RPC Input / RPC Output.
297 * Class to be checked
298 * @return true if class represents RPC Input or RPC Output class.
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"));
307 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
310 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
311 return resolveQNameNoCache(key);
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.
319 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
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));
330 final Object obj = field.get(null);
331 if (obj instanceof QName qname) {
332 return Optional.of(qname);
334 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
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.
339 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
341 return Optional.empty();
345 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
351 * <li>rpc input: local name is "input".
352 * <li>rpc output: local name is "output".
353 * <li>augmentation: local name is "module name".
357 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
360 * @throws IllegalStateException If YangModuleInfo could not be resolved
361 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
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);
368 final QName module = getModuleInfo(key).getName();
369 if (Augmentation.class.isAssignableFrom(key)) {
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();
377 return YangConstants.operationInputQName(module.getModule()).intern();
381 * Fallback for Binding types which do not have QNAME field