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;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.annotations.Beta;
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.Method;
23 import java.lang.reflect.Type;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.LinkedList;
28 import java.util.List;
30 import java.util.Optional;
31 import java.util.ServiceLoader;
33 import java.util.concurrent.TimeUnit;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import org.checkerframework.checker.regex.qual.Regex;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
39 import org.opendaylight.yangtools.util.ClassLoaderUtils;
40 import org.opendaylight.yangtools.yang.binding.Action;
41 import org.opendaylight.yangtools.yang.binding.Augmentable;
42 import org.opendaylight.yangtools.yang.binding.Augmentation;
43 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
44 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
45 import org.opendaylight.yangtools.yang.binding.ChildOf;
46 import org.opendaylight.yangtools.yang.binding.DataContainer;
47 import org.opendaylight.yangtools.yang.binding.DataObject;
48 import org.opendaylight.yangtools.yang.binding.Notification;
49 import org.opendaylight.yangtools.yang.binding.RpcService;
50 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
51 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.QNameModule;
54 import org.opendaylight.yangtools.yang.common.YangConstants;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 public final class BindingReflections {
60 private static final long EXPIRATION_TIME = 60;
63 private static final String ROOT_PACKAGE_PATTERN_STRING =
64 "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.(?:rev[0-9][0-9][0-1][0-9][0-3][0-9]|norev))";
65 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
66 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
68 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
70 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
71 .build(new ClassToQNameLoader());
73 private static final LoadingCache<ClassLoader, ImmutableSet<YangModuleInfo>> MODULE_INFO_CACHE =
74 CacheBuilder.newBuilder().weakKeys().weakValues().build(
75 new CacheLoader<ClassLoader, ImmutableSet<YangModuleInfo>>() {
77 public ImmutableSet<YangModuleInfo> load(final ClassLoader key) {
78 return loadModuleInfos(key);
82 private BindingReflections() {
83 throw new UnsupportedOperationException("Utility class.");
87 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
88 * implemented {@link Augmentation} interface.
91 * {@link Augmentation} subclass for which we want to determine
92 * augmentation target.
93 * @return Augmentation target - class which augmentation provides additional extensions.
95 public static Class<? extends Augmentable<?>> findAugmentationTarget(
96 final Class<? extends Augmentation<?>> augmentation) {
97 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
99 return opt.orElse(null);
103 * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
104 * {@link ChildOf} interface.
107 * child class for which we want to find the parent class.
108 * @return Parent class, e.g. class of which the childClass is ChildOf.
110 public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
111 return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class).orElse(null);
115 * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
116 * invoking {@link DataObject#implementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
119 * Child object for which the parent needs to be located.
120 * @return Parent class, or null if a parent is not found.
122 public static Class<?> findHierarchicalParent(final DataObject child) {
123 if (child instanceof ChildOf) {
124 return ClassLoaderUtils.findFirstGenericArgument(child.implementedInterface(), ChildOf.class).orElse(null);
130 * Returns a QName associated to supplied type.
132 * @param dataType Data type class
133 * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
134 * QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
135 * have name. May return null if QName is not present.
137 public static QName findQName(final Class<?> dataType) {
138 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
142 * Checks if method is RPC invocation.
144 * @param possibleMethod
146 * @return true if method is RPC invocation, false otherwise.
148 public static boolean isRpcMethod(final Method possibleMethod) {
149 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
150 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
151 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
152 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
153 // non input type and two arguments for input type, resolveRpcInputClass() counting
154 // with zero for non input and one for input type
155 && possibleMethod.getParameterCount() <= 2;
159 * Extracts Output class for RPC method.
161 * @param targetMethod
163 * @return Optional.empty() if result type could not be get, or return type is Void.
165 @SuppressWarnings("rawtypes")
166 public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
167 checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
168 Type futureType = targetMethod.getGenericReturnType();
169 Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType).orElse(null);
170 Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType).orElse(null);
171 if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
172 return Optional.of((Class) rpcResultArgument);
174 return Optional.empty();
178 * Extracts input class for RPC method.
180 * @param targetMethod
182 * @return Optional.empty() if RPC has no input, RPC input type otherwise.
184 @SuppressWarnings("rawtypes")
185 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
186 for (Class clazz : targetMethod.getParameterTypes()) {
187 if (DataContainer.class.isAssignableFrom(clazz)) {
188 return Optional.of(clazz);
191 return Optional.empty();
194 public static @NonNull QName getQName(final Class<? extends BaseIdentity> bindingClass) {
195 final Optional<QName> qname = CLASS_TO_QNAME.getUnchecked(requireNonNull(bindingClass));
196 checkState(qname.isPresent(), "Failed to resolve QName of %s", bindingClass);
201 * Checks if class is child of augmentation.
203 public static boolean isAugmentationChild(final Class<?> clazz) {
204 // FIXME: Current resolver could be still confused when child node was added by grouping
205 checkArgument(clazz != null);
207 @SuppressWarnings({ "rawtypes", "unchecked" })
208 Class<?> parent = findHierarchicalParent((Class) clazz);
209 if (parent == null) {
210 LOG.debug("Did not find a parent for class {}", clazz);
214 String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
215 String parentModelPackage = getModelRootPackageName(parent.getPackage());
217 return !clazzModelPackage.equals(parentModelPackage);
221 * Returns root package name for supplied package.
224 * Package for which find model root package.
225 * @return Package of model root.
227 public static String getModelRootPackageName(final Package pkg) {
228 return getModelRootPackageName(pkg.getName());
232 * Returns root package name for supplied package name.
235 * Package for which find model root package.
236 * @return Package of model root.
238 public static String getModelRootPackageName(final String name) {
239 checkArgument(name != null, "Package name should not be null.");
240 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
241 BindingMapping.PACKAGE_PREFIX, name);
242 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
243 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
244 ROOT_PACKAGE_PATTERN_STRING);
245 return match.group(0);
248 @SuppressWarnings("checkstyle:illegalCatch")
249 public static QNameModule getQNameModule(final Class<?> clz) {
250 if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
251 || Action.class.isAssignableFrom(clz)) {
252 return findQName(clz).getModule();
255 return BindingReflections.getModuleInfo(clz).getName().getModule();
256 } catch (Exception e) {
257 throw new IllegalStateException("Unable to get QName of defining model.", e);
262 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
264 * @param cls data object class
265 * @return Instance of {@link YangModuleInfo} associated with model, from
266 * which this class was derived.
268 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
269 checkArgument(cls != null);
270 String packageName = getModelRootPackageName(cls.getPackage());
271 final String potentialClassName = getModuleInfoClassName(packageName);
272 return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> {
273 Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
274 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
278 public static String getModuleInfoClassName(final String packageName) {
279 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
283 * Check if supplied class is derived from YANG model.
287 * @return true if class is derived from YANG model.
289 public static boolean isBindingClass(final Class<?> cls) {
290 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
293 return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
297 * Checks if supplied method is callback for notifications.
299 * @param method method to check
300 * @return true if method is notification callback.
302 public static boolean isNotificationCallback(final Method method) {
303 checkArgument(method != null);
304 if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
305 Class<?> potentialNotification = method.getParameterTypes()[0];
306 if (isNotification(potentialNotification)
307 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
315 * Checks is supplied class is a {@link Notification}.
317 * @param potentialNotification class to examine
318 * @return True if the class represents a Notification.
320 public static boolean isNotification(final Class<?> potentialNotification) {
321 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
322 return Notification.class.isAssignableFrom(potentialNotification);
326 * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
327 * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
329 * @return Set of {@link YangModuleInfo} available for current classloader.
331 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
332 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
336 * Loads {@link YangModuleInfo} infos available on supplied classloader.
339 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
340 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
341 * {@link YangModuleInfo}.
344 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
345 * collecting results of {@link YangModuleInfo#getImportedModules()}.
348 * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
350 * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
351 * @return Set of {@link YangModuleInfo} available for supplied classloader.
353 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
354 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
355 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
357 for (YangModelBindingProvider bindingProvider : serviceLoader) {
358 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
359 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
360 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
362 return moduleInfoSet.build();
366 * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available
367 * information does not change. Subsequent accesses may return cached values.
370 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
371 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
372 * {@link YangModuleInfo}.
375 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
376 * collecting results of {@link YangModuleInfo#getImportedModules()}.
378 * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
379 * @return Set of {@link YangModuleInfo} available for supplied classloader.
382 public static ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
383 return MODULE_INFO_CACHE.getUnchecked(loader);
386 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
387 final Builder<YangModuleInfo> moduleInfoSet) {
388 moduleInfoSet.add(moduleInfo);
389 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
390 collectYangModuleInfo(dependency, moduleInfoSet);
395 * Checks if supplied class represents RPC Input / RPC Output.
398 * Class to be checked
399 * @return true if class represents RPC Input or RPC Output class.
401 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
402 return DataContainer.class.isAssignableFrom(targetType)
403 && !ChildOf.class.isAssignableFrom(targetType)
404 && !Notification.class.isAssignableFrom(targetType)
405 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
409 * Scans supplied class and returns an iterable of all data children classes.
412 * YANG Modeled Entity derived from DataContainer
413 * @return Iterable of all data children, which have YANG modeled entity
415 @SuppressWarnings("unchecked")
416 public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
417 checkArgument(type != null, "Target type must not be null");
418 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
419 List<Class<? extends DataObject>> ret = new LinkedList<>();
420 for (Method method : type.getMethods()) {
421 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method,
422 BindingMapping.GETTER_PREFIX);
423 if (entity.isPresent()) {
424 ret.add((Class<? extends DataObject>) entity.get());
431 * Scans supplied class and returns an iterable of all data children classes.
434 * YANG Modeled Entity derived from DataContainer
435 * @return Iterable of all data children, which have YANG modeled entity
437 public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
438 return getChildrenClassToMethod(type, BindingMapping.GETTER_PREFIX);
441 private static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type, final String prefix) {
442 checkArgument(type != null, "Target type must not be null");
443 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
445 Map<Class<?>, Method> ret = new HashMap<>();
446 for (Method method : type.getMethods()) {
447 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method, prefix);
448 if (entity.isPresent()) {
449 ret.put(entity.get(), method);
456 public static Map<Class<?>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
457 return getChildrenClassToMethod(type, BindingMapping.NONNULL_PREFIX);
460 @SuppressWarnings("checkstyle:illegalCatch")
461 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
462 final String prefix) {
463 final String methodName = method.getName();
464 if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
465 return Optional.empty();
468 final Class<?> returnType = method.getReturnType();
469 if (DataContainer.class.isAssignableFrom(returnType)) {
470 return optionalDataContainer(returnType);
471 } else if (List.class.isAssignableFrom(returnType)) {
473 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> {
474 return ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType()).flatMap(
475 result -> result instanceof Class ? optionalCast((Class<?>) result) : Optional.empty());
477 } catch (Exception e) {
479 * It is safe to log this this exception on debug, since this
480 * method should not fail. Only failures are possible if the
483 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
486 return Optional.empty();
489 private static Optional<Class<? extends DataContainer>> optionalCast(final Class<?> type) {
490 return DataContainer.class.isAssignableFrom(type) ? optionalDataContainer(type) : Optional.empty();
493 private static Optional<Class<? extends DataContainer>> optionalDataContainer(final Class<?> type) {
494 return Optional.of(type.asSubclass(DataContainer.class));
497 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
500 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
501 return resolveQNameNoCache(key);
505 * Tries to resolve QName for supplied class. Looks up for static field with name from constant
506 * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
507 * {@link #computeQName(Class)} to compute QName for missing types.
509 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
513 field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
514 } catch (NoSuchFieldException e) {
515 LOG.debug("{} does not have a {} field, falling back to computation", key,
516 BindingMapping.QNAME_STATIC_FIELD_NAME, e);
517 return Optional.of(computeQName(key));
520 final Object obj = field.get(null);
521 if (obj instanceof QName) {
522 return Optional.of((QName) obj);
524 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
526 * It is safe to log this this exception on debug, since this method should not fail. Only failures are
527 * possible if the runtime / backing is inconsistent.
529 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
531 return Optional.empty();
535 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
541 * <li>rpc input: local name is "input".
542 * <li>rpc output: local name is "output".
543 * <li>augmentation: local name is "module name".
547 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
550 * @throws IllegalStateException If YangModuleInfo could not be resolved
551 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
553 // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
554 @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
555 private static QName computeQName(final Class key) {
556 checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
558 YangModuleInfo moduleInfo;
560 moduleInfo = getModuleInfo(key);
561 } catch (Exception e) {
562 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
565 final QName module = moduleInfo.getName();
566 if (Augmentation.class.isAssignableFrom(key)) {
568 } else if (isRpcType(key)) {
569 final String className = key.getSimpleName();
570 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
571 return YangConstants.operationOutputQName(module.getModule()).intern();
574 return YangConstants.operationInputQName(module.getModule()).intern();
578 * Fallback for Binding types which do not have QNAME field
585 * Extracts augmentation from Binding DTO field using reflection.
588 * Instance of DataObject which is augmentable and may contain
590 * @return Map of augmentations if read was successful, otherwise empty map.
592 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
593 if (input instanceof AugmentationHolder) {
594 return ((AugmentationHolder) input).augmentations();
596 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
600 * Determines if two augmentation classes or case classes represents same
604 * Two augmentations or cases could be substituted only if and if:
606 * <li>Both implements same interfaces</li>
607 * <li>Both have same children</li>
608 * <li>If augmentations: Both have same augmentation target class. Target
609 * class was generated for data node in grouping.</li>
610 * <li>If cases: Both are from same choice. Choice class was generated for
611 * data node in grouping.</li>
615 * <b>Explanation:</b> Binding Specification reuses classes generated for
616 * groupings as part of normal data tree, this classes from grouping could
617 * be used at various locations and user may not be aware of it and may use
618 * incorrect case or augmentation in particular subtree (via copy
619 * constructors, etc).
622 * Class which is potential substitution
624 * Class which should be used at particular subtree
625 * @return true if and only if classes represents same data.
627 @SuppressWarnings({ "rawtypes", "unchecked" })
628 public static boolean isSubstitutionFor(final Class potential, final Class target) {
629 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
630 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
631 if (!subImplemented.equals(targetImplemented)) {
634 if (Augmentation.class.isAssignableFrom(potential)
635 && !BindingReflections.findAugmentationTarget(potential).equals(
636 BindingReflections.findAugmentationTarget(target))) {
639 for (Method potentialMethod : potential.getMethods()) {
641 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
642 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
645 } catch (NoSuchMethodException e) {
646 // Counterpart method is missing, so classes could not be substituted.
648 } catch (SecurityException e) {
649 throw new IllegalStateException("Could not compare methods", e);