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.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.lang.reflect.Modifier;
24 import java.lang.reflect.Type;
25 import java.util.Arrays;
26 import java.util.HashSet;
27 import java.util.Optional;
28 import java.util.ServiceLoader;
30 import java.util.concurrent.TimeUnit;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import org.checkerframework.checker.regex.qual.Regex;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
36 import org.opendaylight.yangtools.util.ClassLoaderUtils;
37 import org.opendaylight.yangtools.yang.binding.Action;
38 import org.opendaylight.yangtools.yang.binding.Augmentable;
39 import org.opendaylight.yangtools.yang.binding.Augmentation;
40 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
41 import org.opendaylight.yangtools.yang.binding.BindingContract;
42 import org.opendaylight.yangtools.yang.binding.ChildOf;
43 import org.opendaylight.yangtools.yang.binding.DataContainer;
44 import org.opendaylight.yangtools.yang.binding.DataObject;
45 import org.opendaylight.yangtools.yang.binding.Notification;
46 import org.opendaylight.yangtools.yang.binding.Rpc;
47 import org.opendaylight.yangtools.yang.binding.RpcService;
48 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
49 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.common.QNameModule;
52 import org.opendaylight.yangtools.yang.common.YangConstants;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 public final class BindingReflections {
58 private static final long EXPIRATION_TIME = 60;
61 private static final String ROOT_PACKAGE_PATTERN_STRING =
62 "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.(?:rev[0-9][0-9][0-1][0-9][0-3][0-9]|norev))";
63 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
64 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
66 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
68 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
69 .build(new ClassToQNameLoader());
71 private static final LoadingCache<ClassLoader, ImmutableSet<YangModuleInfo>> MODULE_INFO_CACHE =
72 CacheBuilder.newBuilder().weakKeys().weakValues().build(
73 new CacheLoader<ClassLoader, ImmutableSet<YangModuleInfo>>() {
75 public ImmutableSet<YangModuleInfo> load(final ClassLoader key) {
76 return loadModuleInfos(key);
80 private BindingReflections() {
85 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
86 * implemented {@link Augmentation} interface.
89 * {@link Augmentation} subclass for which we want to determine
90 * augmentation target.
91 * @return Augmentation target - class which augmentation provides additional extensions.
93 public static Class<? extends Augmentable<?>> findAugmentationTarget(
94 final Class<? extends Augmentation<?>> augmentation) {
95 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
97 return opt.orElse(null);
101 * Returns a QName associated to supplied type.
103 * @param dataType Data type class
104 * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
105 * QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
106 * have name. May return null if QName is not present.
108 public static QName findQName(final Class<?> dataType) {
109 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
113 * Checks if method is RPC invocation.
115 * @param possibleMethod
117 * @return true if method is RPC invocation, false otherwise.
119 public static boolean isRpcMethod(final Method possibleMethod) {
120 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
121 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
122 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
123 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
124 // non input type and two arguments for input type, resolveRpcInputClass() counting
125 // with zero for non input and one for input type
126 && possibleMethod.getParameterCount() <= 2;
130 * Extracts Output class for RPC method.
132 * @param targetMethod method to scan
133 * @return Optional.empty() if result type could not be get, or return type is Void.
134 * @deprecated This method is unused and scheduled for removal
136 @Deprecated(since = "10.0.4", forRemoval = true)
137 @SuppressWarnings("rawtypes")
138 public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
139 checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
140 Type futureType = targetMethod.getGenericReturnType();
141 Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType).orElse(null);
142 Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType).orElse(null);
143 if (rpcResultArgument instanceof Class cls && !Void.class.equals(rpcResultArgument)) {
144 return Optional.of(cls);
146 return Optional.empty();
150 * Extracts input class for RPC method.
152 * @param targetMethod method to scan
153 * @return Optional.empty() if RPC has no input, RPC input type otherwise.
154 * @deprecated This method is unused and scheduled for removal
156 @Deprecated(since = "10.0.4", forRemoval = true)
157 @SuppressWarnings("rawtypes")
158 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
159 for (Class clazz : targetMethod.getParameterTypes()) {
160 if (DataContainer.class.isAssignableFrom(clazz)) {
161 return Optional.of(clazz);
164 return Optional.empty();
167 public static @NonNull QName getQName(final BaseIdentity identity) {
168 return getContractQName(identity);
171 public static @NonNull QName getQName(final Rpc<?, ?> rpc) {
172 return getContractQName(rpc);
175 private static @NonNull QName getContractQName(final BindingContract<?> contract) {
176 return CLASS_TO_QNAME.getUnchecked(contract.implementedInterface())
177 .orElseThrow(() -> new IllegalStateException("Failed to resolve QName of " + contract));
181 * Returns root package name for supplied package.
184 * Package for which find model root package.
185 * @return Package of model root.
187 public static String getModelRootPackageName(final Package pkg) {
188 return getModelRootPackageName(pkg.getName());
192 * Returns root package name for supplied package name.
195 * Package for which find model root package.
196 * @return Package of model root.
198 public static String getModelRootPackageName(final String name) {
199 checkArgument(name != null, "Package name should not be null.");
200 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
201 BindingMapping.PACKAGE_PREFIX, name);
202 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
203 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
204 ROOT_PACKAGE_PATTERN_STRING);
205 return match.group(0);
208 public static QNameModule getQNameModule(final Class<?> clz) {
209 if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
210 || Action.class.isAssignableFrom(clz)) {
211 return findQName(clz).getModule();
214 return getModuleInfo(clz).getName().getModule();
218 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
220 * @param cls data object class
221 * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
223 public static @NonNull YangModuleInfo getModuleInfo(final Class<?> cls) {
224 final String packageName = getModelRootPackageName(cls.getPackage());
225 final String potentialClassName = getModuleInfoClassName(packageName);
226 final Class<?> moduleInfoClass;
228 moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
229 } catch (ClassNotFoundException e) {
230 throw new IllegalStateException("Failed to load " + potentialClassName, e);
233 final Object infoInstance;
235 infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
236 } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
237 throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
240 checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
241 return (YangModuleInfo) infoInstance;
244 public static @NonNull String getModuleInfoClassName(final String packageName) {
245 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
249 * Check if supplied class is derived from YANG model.
253 * @return true if class is derived from YANG model.
255 public static boolean isBindingClass(final Class<?> cls) {
256 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
259 return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
263 * Checks if supplied method is callback for notifications.
265 * @param method method to check
266 * @return true if method is notification callback.
268 public static boolean isNotificationCallback(final Method method) {
269 checkArgument(method != null);
270 if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
271 Class<?> potentialNotification = method.getParameterTypes()[0];
272 if (isNotification(potentialNotification)
273 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
281 * Checks is supplied class is a {@link Notification}.
283 * @param potentialNotification class to examine
284 * @return True if the class represents a Notification.
286 public static boolean isNotification(final Class<?> potentialNotification) {
287 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
288 return Notification.class.isAssignableFrom(potentialNotification);
292 * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
293 * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
295 * @return Set of {@link YangModuleInfo} available for current classloader.
297 public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos() {
298 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
302 * Loads {@link YangModuleInfo} infos available on supplied classloader.
305 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
306 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
307 * {@link YangModuleInfo}.
310 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
311 * collecting results of {@link YangModuleInfo#getImportedModules()}.
314 * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
316 * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
317 * @return Set of {@link YangModuleInfo} available for supplied classloader.
319 public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
320 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
321 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
323 for (YangModelBindingProvider bindingProvider : serviceLoader) {
324 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
325 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
326 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
328 return moduleInfoSet.build();
332 * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available
333 * information does not change. Subsequent accesses may return cached values.
336 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
337 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
338 * {@link YangModuleInfo}.
341 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
342 * collecting results of {@link YangModuleInfo#getImportedModules()}.
344 * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
345 * @return Set of {@link YangModuleInfo} available for supplied classloader.
348 public static @NonNull ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
349 return MODULE_INFO_CACHE.getUnchecked(loader);
352 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
353 final Builder<YangModuleInfo> moduleInfoSet) {
354 moduleInfoSet.add(moduleInfo);
355 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
356 collectYangModuleInfo(dependency, moduleInfoSet);
361 * Checks if supplied class represents RPC Input / RPC Output.
364 * Class to be checked
365 * @return true if class represents RPC Input or RPC Output class.
367 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
368 return DataContainer.class.isAssignableFrom(targetType)
369 && !ChildOf.class.isAssignableFrom(targetType)
370 && !Notification.class.isAssignableFrom(targetType)
371 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
374 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
377 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
378 return resolveQNameNoCache(key);
382 * Tries to resolve QName for supplied class. Looks up for static field with name from constant
383 * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
384 * {@link #computeQName(Class)} to compute QName for missing types.
386 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
390 field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
391 } catch (NoSuchFieldException e) {
392 LOG.debug("{} does not have a {} field, falling back to computation", key,
393 BindingMapping.QNAME_STATIC_FIELD_NAME, e);
394 return Optional.of(computeQName(key));
397 final Object obj = field.get(null);
398 if (obj instanceof QName qname) {
399 return Optional.of(qname);
401 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
403 * It is safe to log this this exception on debug, since this method should not fail. Only failures are
404 * possible if the runtime / backing is inconsistent.
406 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
408 return Optional.empty();
412 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
418 * <li>rpc input: local name is "input".
419 * <li>rpc output: local name is "output".
420 * <li>augmentation: local name is "module name".
424 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
427 * @throws IllegalStateException If YangModuleInfo could not be resolved
428 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
430 // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
431 @SuppressWarnings({ "rawtypes", "unchecked" })
432 private static QName computeQName(final Class key) {
433 checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
435 final QName module = getModuleInfo(key).getName();
436 if (Augmentation.class.isAssignableFrom(key)) {
438 } else if (isRpcType(key)) {
439 final String className = key.getSimpleName();
440 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
441 return YangConstants.operationOutputQName(module.getModule()).intern();
444 return YangConstants.operationInputQName(module.getModule()).intern();
448 * Fallback for Binding types which do not have QNAME field
455 * Determines if two augmentation classes or case classes represents same data.
458 * Two augmentations or cases could be substituted only if and if:
460 * <li>Both implements same interfaces</li>
461 * <li>Both have same children</li>
462 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
464 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
468 * <b>Explanation:</b>
469 * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
470 * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
471 * augmentation in particular subtree (via copy constructors, etc).
473 * @param potential Class which is potential substitution
474 * @param target Class which should be used at particular subtree
475 * @return true if and only if classes represents same data.
476 * @throws NullPointerException if any argument is {@code null}
478 // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
479 // user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
480 // a particular world this boils down to a matrix, which can be calculated either on-demand or
481 // when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
482 // to have a pre-compiled Binding Runtime.
483 @SuppressWarnings({ "rawtypes", "unchecked" })
484 public static boolean isSubstitutionFor(final Class potential, final Class target) {
485 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
486 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
487 if (!subImplemented.equals(targetImplemented)) {
490 if (Augmentation.class.isAssignableFrom(potential)
491 && !BindingReflections.findAugmentationTarget(potential).equals(
492 BindingReflections.findAugmentationTarget(target))) {
495 for (Method potentialMethod : potential.getMethods()) {
496 if (Modifier.isStatic(potentialMethod.getModifiers())) {
497 // Skip any static methods, as we are not interested in those
502 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
503 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
506 } catch (NoSuchMethodException e) {
507 // Counterpart method is missing, so classes could not be substituted.
509 } catch (SecurityException e) {
510 throw new IllegalStateException("Could not compare methods", e);