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 java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import org.checkerframework.checker.regex.qual.Regex;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
32 import org.opendaylight.yangtools.util.ClassLoaderUtils;
33 import org.opendaylight.yangtools.yang.binding.Action;
34 import org.opendaylight.yangtools.yang.binding.Augmentable;
35 import org.opendaylight.yangtools.yang.binding.Augmentation;
36 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
37 import org.opendaylight.yangtools.yang.binding.BindingContract;
38 import org.opendaylight.yangtools.yang.binding.ChildOf;
39 import org.opendaylight.yangtools.yang.binding.DataContainer;
40 import org.opendaylight.yangtools.yang.binding.DataObject;
41 import org.opendaylight.yangtools.yang.binding.Notification;
42 import org.opendaylight.yangtools.yang.binding.Rpc;
43 import org.opendaylight.yangtools.yang.binding.RpcService;
44 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
45 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.common.QNameModule;
48 import org.opendaylight.yangtools.yang.common.YangConstants;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 public final class BindingReflections {
54 private static final long EXPIRATION_TIME = 60;
57 private static final String ROOT_PACKAGE_PATTERN_STRING =
58 "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.(?:rev[0-9][0-9][0-1][0-9][0-3][0-9]|norev))";
59 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
60 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
62 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
64 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
65 .build(new ClassToQNameLoader());
67 private static final LoadingCache<ClassLoader, ImmutableSet<YangModuleInfo>> MODULE_INFO_CACHE =
68 CacheBuilder.newBuilder().weakKeys().weakValues().build(
69 new CacheLoader<ClassLoader, ImmutableSet<YangModuleInfo>>() {
71 public ImmutableSet<YangModuleInfo> load(final ClassLoader key) {
72 return loadModuleInfos(key);
76 private BindingReflections() {
81 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
82 * implemented {@link Augmentation} interface.
85 * {@link Augmentation} subclass for which we want to determine
86 * augmentation target.
87 * @return Augmentation target - class which augmentation provides additional extensions.
89 public static Class<? extends Augmentable<?>> findAugmentationTarget(
90 final Class<? extends Augmentation<?>> augmentation) {
91 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
93 return opt.orElse(null);
97 * Returns a QName associated to supplied type.
99 * @param dataType Data type class
100 * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
101 * QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
102 * have name. May return null if QName is not present.
104 public static QName findQName(final Class<?> dataType) {
105 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
109 * Checks if method is RPC invocation.
111 * @param possibleMethod
113 * @return true if method is RPC invocation, false otherwise.
115 public static boolean isRpcMethod(final Method possibleMethod) {
116 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
117 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
118 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
119 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
120 // non input type and two arguments for input type, resolveRpcInputClass() counting
121 // with zero for non input and one for input type
122 && possibleMethod.getParameterCount() <= 2;
125 public static @NonNull QName getQName(final BaseIdentity identity) {
126 return getContractQName(identity);
129 public static @NonNull QName getQName(final Rpc<?, ?> rpc) {
130 return getContractQName(rpc);
133 private static @NonNull QName getContractQName(final BindingContract<?> contract) {
134 return CLASS_TO_QNAME.getUnchecked(contract.implementedInterface())
135 .orElseThrow(() -> new IllegalStateException("Failed to resolve QName of " + contract));
139 * Returns root package name for supplied package.
142 * Package for which find model root package.
143 * @return Package of model root.
145 public static String getModelRootPackageName(final Package pkg) {
146 return getModelRootPackageName(pkg.getName());
150 * Returns root package name for supplied package name.
153 * Package for which find model root package.
154 * @return Package of model root.
156 public static String getModelRootPackageName(final String name) {
157 checkArgument(name != null, "Package name should not be null.");
158 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
159 BindingMapping.PACKAGE_PREFIX, name);
160 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
161 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
162 ROOT_PACKAGE_PATTERN_STRING);
163 return match.group(0);
166 public static QNameModule getQNameModule(final Class<?> clz) {
167 if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
168 || Action.class.isAssignableFrom(clz)) {
169 return findQName(clz).getModule();
172 return getModuleInfo(clz).getName().getModule();
176 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
178 * @param cls data object class
179 * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
181 public static @NonNull YangModuleInfo getModuleInfo(final Class<?> cls) {
182 final String packageName = getModelRootPackageName(cls.getPackage());
183 final String potentialClassName = getModuleInfoClassName(packageName);
184 final Class<?> moduleInfoClass;
186 moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
187 } catch (ClassNotFoundException e) {
188 throw new IllegalStateException("Failed to load " + potentialClassName, e);
191 final Object infoInstance;
193 infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
194 } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
195 throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
198 checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
199 return (YangModuleInfo) infoInstance;
202 public static @NonNull String getModuleInfoClassName(final String packageName) {
203 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
207 * Check if supplied class is derived from YANG model.
211 * @return true if class is derived from YANG model.
213 public static boolean isBindingClass(final Class<?> cls) {
214 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
217 return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
221 * Checks if supplied method is callback for notifications.
223 * @param method method to check
224 * @return true if method is notification callback.
226 public static boolean isNotificationCallback(final Method method) {
227 checkArgument(method != null);
228 if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
229 Class<?> potentialNotification = method.getParameterTypes()[0];
230 if (isNotification(potentialNotification)
231 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
239 * Checks is supplied class is a {@link Notification}.
241 * @param potentialNotification class to examine
242 * @return True if the class represents a Notification.
245 static boolean isNotification(final Class<?> potentialNotification) {
246 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
247 return Notification.class.isAssignableFrom(potentialNotification);
251 * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
252 * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
254 * @return Set of {@link YangModuleInfo} available for current classloader.
256 public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos() {
257 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
261 * Loads {@link YangModuleInfo} infos available on supplied classloader.
264 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
265 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
266 * {@link YangModuleInfo}.
269 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
270 * collecting results of {@link YangModuleInfo#getImportedModules()}.
273 * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
275 * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
276 * @return Set of {@link YangModuleInfo} available for supplied classloader.
278 public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
279 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
280 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
282 for (YangModelBindingProvider bindingProvider : serviceLoader) {
283 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
284 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
285 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
287 return moduleInfoSet.build();
291 * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available
292 * information does not change. Subsequent accesses may return cached values.
295 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
296 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
297 * {@link YangModuleInfo}.
300 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
301 * collecting results of {@link YangModuleInfo#getImportedModules()}.
303 * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
304 * @return Set of {@link YangModuleInfo} available for supplied classloader.
307 public static @NonNull ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
308 return MODULE_INFO_CACHE.getUnchecked(loader);
311 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
312 final Builder<YangModuleInfo> moduleInfoSet) {
313 moduleInfoSet.add(moduleInfo);
314 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
315 collectYangModuleInfo(dependency, moduleInfoSet);
320 * Checks if supplied class represents RPC Input / RPC Output.
323 * Class to be checked
324 * @return true if class represents RPC Input or RPC Output class.
326 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
327 return DataContainer.class.isAssignableFrom(targetType)
328 && !ChildOf.class.isAssignableFrom(targetType)
329 && !Notification.class.isAssignableFrom(targetType)
330 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
333 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
336 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
337 return resolveQNameNoCache(key);
341 * Tries to resolve QName for supplied class. Looks up for static field with name from constant
342 * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
343 * {@link #computeQName(Class)} to compute QName for missing types.
345 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
349 field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
350 } catch (NoSuchFieldException e) {
351 LOG.debug("{} does not have a {} field, falling back to computation", key,
352 BindingMapping.QNAME_STATIC_FIELD_NAME, e);
353 return Optional.of(computeQName(key));
356 final Object obj = field.get(null);
357 if (obj instanceof QName qname) {
358 return Optional.of(qname);
360 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
362 * It is safe to log this this exception on debug, since this method should not fail. Only failures are
363 * possible if the runtime / backing is inconsistent.
365 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
367 return Optional.empty();
371 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
377 * <li>rpc input: local name is "input".
378 * <li>rpc output: local name is "output".
379 * <li>augmentation: local name is "module name".
383 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
386 * @throws IllegalStateException If YangModuleInfo could not be resolved
387 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
389 // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
390 @SuppressWarnings({ "rawtypes", "unchecked" })
391 private static QName computeQName(final Class key) {
392 checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
394 final QName module = getModuleInfo(key).getName();
395 if (Augmentation.class.isAssignableFrom(key)) {
397 } else if (isRpcType(key)) {
398 final String className = key.getSimpleName();
399 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
400 return YangConstants.operationOutputQName(module.getModule()).intern();
403 return YangConstants.operationInputQName(module.getModule()).intern();
407 * Fallback for Binding types which do not have QNAME field