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.Method;
22 import java.lang.reflect.Type;
23 import java.util.Arrays;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.LinkedList;
27 import java.util.List;
29 import java.util.Optional;
30 import java.util.ServiceLoader;
32 import java.util.concurrent.TimeUnit;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35 import org.checkerframework.checker.regex.qual.Regex;
36 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
37 import org.opendaylight.yangtools.util.ClassLoaderUtils;
38 import org.opendaylight.yangtools.yang.binding.Action;
39 import org.opendaylight.yangtools.yang.binding.Augmentable;
40 import org.opendaylight.yangtools.yang.binding.Augmentation;
41 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
42 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
43 import org.opendaylight.yangtools.yang.binding.ChildOf;
44 import org.opendaylight.yangtools.yang.binding.DataContainer;
45 import org.opendaylight.yangtools.yang.binding.DataObject;
46 import org.opendaylight.yangtools.yang.binding.Notification;
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() {
81 throw new UnsupportedOperationException("Utility class.");
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 * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
102 * {@link ChildOf} interface.
105 * child class for which we want to find the parent class.
106 * @return Parent class, e.g. class of which the childClass is ChildOf.
108 public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
109 return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class).orElse(null);
113 * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
114 * invoking {@link DataObject#implementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
117 * Child object for which the parent needs to be located.
118 * @return Parent class, or null if a parent is not found.
120 public static Class<?> findHierarchicalParent(final DataObject child) {
121 if (child instanceof ChildOf) {
122 return ClassLoaderUtils.findFirstGenericArgument(child.implementedInterface(), ChildOf.class).orElse(null);
128 * Returns a QName associated to supplied type.
130 * @param dataType Data type class
131 * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
132 * QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
133 * have name. May return null if QName is not present.
135 public static QName findQName(final Class<?> dataType) {
136 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
140 * Checks if method is RPC invocation.
142 * @param possibleMethod
144 * @return true if method is RPC invocation, false otherwise.
146 public static boolean isRpcMethod(final Method possibleMethod) {
147 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
148 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
149 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
150 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
151 // non input type and two arguments for input type, resolveRpcInputClass() counting
152 // with zero for non input and one for input type
153 && possibleMethod.getParameterCount() <= 2;
157 * Extracts Output class for RPC method.
159 * @param targetMethod
161 * @return Optional.empty() if result type could not be get, or return type is Void.
163 @SuppressWarnings("rawtypes")
164 public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
165 checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
166 Type futureType = targetMethod.getGenericReturnType();
167 Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType).orElse(null);
168 Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType).orElse(null);
169 if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
170 return Optional.of((Class) rpcResultArgument);
172 return Optional.empty();
176 * Extracts input class for RPC method.
178 * @param targetMethod
180 * @return Optional.empty() if RPC has no input, RPC input type otherwise.
182 @SuppressWarnings("rawtypes")
183 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
184 for (Class clazz : targetMethod.getParameterTypes()) {
185 if (DataContainer.class.isAssignableFrom(clazz)) {
186 return Optional.of(clazz);
189 return Optional.empty();
192 public static QName getQName(final Class<? extends BaseIdentity> context) {
193 return findQName(context);
197 * Checks if class is child of augmentation.
199 public static boolean isAugmentationChild(final Class<?> clazz) {
200 // FIXME: Current resolver could be still confused when child node was added by grouping
201 checkArgument(clazz != null);
203 @SuppressWarnings({ "rawtypes", "unchecked" })
204 Class<?> parent = findHierarchicalParent((Class) clazz);
205 if (parent == null) {
206 LOG.debug("Did not find a parent for class {}", clazz);
210 String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
211 String parentModelPackage = getModelRootPackageName(parent.getPackage());
213 return !clazzModelPackage.equals(parentModelPackage);
217 * Returns root package name for supplied package.
220 * Package for which find model root package.
221 * @return Package of model root.
223 public static String getModelRootPackageName(final Package pkg) {
224 return getModelRootPackageName(pkg.getName());
228 * Returns root package name for supplied package name.
231 * Package for which find model root package.
232 * @return Package of model root.
234 public static String getModelRootPackageName(final String name) {
235 checkArgument(name != null, "Package name should not be null.");
236 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
237 BindingMapping.PACKAGE_PREFIX, name);
238 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
239 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
240 ROOT_PACKAGE_PATTERN_STRING);
241 return match.group(0);
244 @SuppressWarnings("checkstyle:illegalCatch")
245 public static QNameModule getQNameModule(final Class<?> clz) {
246 if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
247 || Action.class.isAssignableFrom(clz)) {
248 return findQName(clz).getModule();
251 return BindingReflections.getModuleInfo(clz).getName().getModule();
252 } catch (Exception e) {
253 throw new IllegalStateException("Unable to get QName of defining model.", e);
258 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
260 * @param cls data object class
261 * @return Instance of {@link YangModuleInfo} associated with model, from
262 * which this class was derived.
264 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
265 checkArgument(cls != null);
266 String packageName = getModelRootPackageName(cls.getPackage());
267 final String potentialClassName = getModuleInfoClassName(packageName);
268 return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> {
269 Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
270 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
274 public static String getModuleInfoClassName(final String packageName) {
275 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
279 * Check if supplied class is derived from YANG model.
283 * @return true if class is derived from YANG model.
285 public static boolean isBindingClass(final Class<?> cls) {
286 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
289 return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
293 * Checks if supplied method is callback for notifications.
295 * @param method method to check
296 * @return true if method is notification callback.
298 public static boolean isNotificationCallback(final Method method) {
299 checkArgument(method != null);
300 if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
301 Class<?> potentialNotification = method.getParameterTypes()[0];
302 if (isNotification(potentialNotification)
303 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
311 * Checks is supplied class is a {@link Notification}.
313 * @param potentialNotification class to examine
314 * @return True if the class represents a Notification.
316 public static boolean isNotification(final Class<?> potentialNotification) {
317 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
318 return Notification.class.isAssignableFrom(potentialNotification);
322 * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
323 * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
325 * @return Set of {@link YangModuleInfo} available for current classloader.
327 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
328 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
332 * Loads {@link YangModuleInfo} infos available on supplied classloader.
335 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
336 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
337 * {@link YangModuleInfo}.
340 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
341 * collecting results of {@link YangModuleInfo#getImportedModules()}.
344 * Consider using {@link #cacheModuleInfos(ClassLoader)} if the classloader is known to be immutable.
346 * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
347 * @return Set of {@link YangModuleInfo} available for supplied classloader.
349 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
350 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
351 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
353 for (YangModelBindingProvider bindingProvider : serviceLoader) {
354 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
355 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
356 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
358 return moduleInfoSet.build();
362 * Loads {@link YangModuleInfo} instances available on supplied {@link ClassLoader}, assuming the set of available
363 * information does not change. Subsequent accesses may return cached values.
366 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
367 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
368 * {@link YangModuleInfo}.
371 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
372 * collecting results of {@link YangModuleInfo#getImportedModules()}.
374 * @param loader Class loader for which {@link YangModuleInfo} should be retrieved.
375 * @return Set of {@link YangModuleInfo} available for supplied classloader.
378 public static ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
379 return MODULE_INFO_CACHE.getUnchecked(loader);
382 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
383 final Builder<YangModuleInfo> moduleInfoSet) {
384 moduleInfoSet.add(moduleInfo);
385 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
386 collectYangModuleInfo(dependency, moduleInfoSet);
391 * Checks if supplied class represents RPC Input / RPC Output.
394 * Class to be checked
395 * @return true if class represents RPC Input or RPC Output class.
397 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
398 return DataContainer.class.isAssignableFrom(targetType)
399 && !ChildOf.class.isAssignableFrom(targetType)
400 && !Notification.class.isAssignableFrom(targetType)
401 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
405 * Scans supplied class and returns an iterable of all data children classes.
408 * YANG Modeled Entity derived from DataContainer
409 * @return Iterable of all data children, which have YANG modeled entity
411 @SuppressWarnings("unchecked")
412 public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
413 checkArgument(type != null, "Target type must not be null");
414 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
415 List<Class<? extends DataObject>> ret = new LinkedList<>();
416 for (Method method : type.getMethods()) {
417 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method,
418 BindingMapping.GETTER_PREFIX);
419 if (entity.isPresent()) {
420 ret.add((Class<? extends DataObject>) entity.get());
427 * Scans supplied class and returns an iterable of all data children classes.
430 * YANG Modeled Entity derived from DataContainer
431 * @return Iterable of all data children, which have YANG modeled entity
433 public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
434 return getChildrenClassToMethod(type, BindingMapping.GETTER_PREFIX);
437 private static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type, final String prefix) {
438 checkArgument(type != null, "Target type must not be null");
439 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
441 Map<Class<?>, Method> ret = new HashMap<>();
442 for (Method method : type.getMethods()) {
443 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method, prefix);
444 if (entity.isPresent()) {
445 ret.put(entity.get(), method);
452 public static Map<Class<?>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
453 return getChildrenClassToMethod(type, BindingMapping.NONNULL_PREFIX);
456 @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" })
457 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
458 final String prefix) {
459 final String methodName = method.getName();
460 if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
461 return Optional.empty();
464 Class returnType = method.getReturnType();
465 if (DataContainer.class.isAssignableFrom(returnType)) {
466 return Optional.of(returnType);
468 if (List.class.isAssignableFrom(returnType)) {
470 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> {
471 return ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType()).flatMap(
472 result -> result instanceof Class && DataContainer.class.isAssignableFrom((Class) result)
473 ? Optional.of((Class) result) : Optional.empty());
475 } catch (Exception e) {
477 * It is safe to log this this exception on debug, since this
478 * method should not fail. Only failures are possible if the
481 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
484 return Optional.empty();
487 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
490 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
491 return resolveQNameNoCache(key);
495 * Tries to resolve QName for supplied class. Looks up for static field with name from constant
496 * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
497 * {@link #computeQName(Class)} to compute QName for missing types.
499 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
503 field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
504 } catch (NoSuchFieldException e) {
505 LOG.debug("{} does not have a {} field, falling back to computation", key,
506 BindingMapping.QNAME_STATIC_FIELD_NAME, e);
507 return Optional.of(computeQName(key));
510 final Object obj = field.get(null);
511 if (obj instanceof QName) {
512 return Optional.of((QName) obj);
514 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
516 * It is safe to log this this exception on debug, since this method should not fail. Only failures are
517 * possible if the runtime / backing is inconsistent.
519 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
521 return Optional.empty();
525 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
531 * <li>rpc input: local name is "input".
532 * <li>rpc output: local name is "output".
533 * <li>augmentation: local name is "module name".
537 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
540 * @throws IllegalStateException If YangModuleInfo could not be resolved
541 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
543 // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
544 @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
545 private static QName computeQName(final Class key) {
546 checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
548 YangModuleInfo moduleInfo;
550 moduleInfo = getModuleInfo(key);
551 } catch (Exception e) {
552 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
555 final QName module = moduleInfo.getName();
556 if (Augmentation.class.isAssignableFrom(key)) {
558 } else if (isRpcType(key)) {
559 final String className = key.getSimpleName();
560 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
561 return YangConstants.operationOutputQName(module.getModule()).intern();
564 return YangConstants.operationInputQName(module.getModule()).intern();
568 * Fallback for Binding types which do not have QNAME field
575 * Extracts augmentation from Binding DTO field using reflection.
578 * Instance of DataObject which is augmentable and may contain
580 * @return Map of augmentations if read was successful, otherwise empty map.
582 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
583 if (input instanceof AugmentationHolder) {
584 return ((AugmentationHolder) input).augmentations();
586 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
590 * Determines if two augmentation classes or case classes represents same
594 * Two augmentations or cases could be substituted only if and if:
596 * <li>Both implements same interfaces</li>
597 * <li>Both have same children</li>
598 * <li>If augmentations: Both have same augmentation target class. Target
599 * class was generated for data node in grouping.</li>
600 * <li>If cases: Both are from same choice. Choice class was generated for
601 * data node in grouping.</li>
605 * <b>Explanation:</b> Binding Specification reuses classes generated for
606 * groupings as part of normal data tree, this classes from grouping could
607 * be used at various locations and user may not be aware of it and may use
608 * incorrect case or augmentation in particular subtree (via copy
609 * constructors, etc).
612 * Class which is potential substitution
614 * Class which should be used at particular subtree
615 * @return true if and only if classes represents same data.
617 @SuppressWarnings({ "rawtypes", "unchecked" })
618 public static boolean isSubstitutionFor(final Class potential, final Class target) {
619 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
620 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
621 if (!subImplemented.equals(targetImplemented)) {
624 if (Augmentation.class.isAssignableFrom(potential)
625 && !BindingReflections.findAugmentationTarget(potential).equals(
626 BindingReflections.findAugmentationTarget(target))) {
629 for (Method potentialMethod : potential.getMethods()) {
631 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
632 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
635 } catch (NoSuchMethodException e) {
636 // Counterpart method is missing, so classes could not be substituted.
638 } catch (SecurityException e) {
639 throw new IllegalStateException("Could not compare methods", e);