2 * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.javav2.runtime.reflection;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Optional;
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.collect.Sets;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.Method;
22 import java.lang.reflect.Type;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.LinkedList;
27 import java.util.List;
29 import java.util.ServiceLoader;
30 import java.util.concurrent.Callable;
31 import java.util.concurrent.Future;
32 import java.util.concurrent.TimeUnit;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35 import javax.annotation.Nonnull;
36 import org.opendaylight.mdsal.binding.javav2.spec.base.BaseIdentity;
37 import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable;
38 import org.opendaylight.mdsal.binding.javav2.spec.base.Notification;
39 import org.opendaylight.mdsal.binding.javav2.spec.base.Operation;
40 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
41 import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModelBindingProvider;
42 import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModuleInfo;
43 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable;
44 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
45 import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode;
46 import org.opendaylight.yangtools.util.ClassLoaderUtils;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.QNameModule;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 public final class BindingReflections {
55 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
57 private static final long EXPIRATION_TIME = 60;
58 private static final String QNAME_STATIC_FIELD_NAME = "QNAME";
59 private static final String OPERATION_ACTION_OUTPUT_SUFFIX = "Output";
60 private static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl";
61 private static final String PACKAGE_PREFIX = "org.opendaylight.mdsal.gen.javav2";
62 private static final String ROOT_PACKAGE_PATTERN_STRING =
63 "(org.opendaylight.mdsal.gen.javav2.[a-z0-9_\\.]*\\.rev[0-9][0-9][0-1][0-9][0-3][0-9])";
65 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
67 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder().weakKeys()
68 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS).build(new ClassToQNameLoader());
70 private BindingReflections() {
71 throw new UnsupportedOperationException("Utility class.");
75 * Find augmentation target class from concrete Augmentation class
77 * This method uses first generic argument of implemented
78 * {@link Augmentation} interface.
81 * {@link Augmentation} subclass for which we want to determine
82 * augmentation target.
83 * @return Augmentation target - class which augmentation provides
84 * additional extensions.
86 public static Class<? extends Augmentable<?>> findAugmentationTarget(
87 final Class<? extends Augmentation<?>> augmentation) {
88 return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class);
92 * Find data hierarchy parent from concrete Tree Node class
94 * This method uses first generic argument of implemented
95 * {@link TreeChildNode} interface.
98 * - child class for which we want to find the parent class
99 * @return Parent class, e.g. class of which the childClass is ChildOf
101 static Class<?> findHierarchicalParent(final Class<? extends TreeChildNode<?, ?>> childClass) {
102 return ClassLoaderUtils.findFirstGenericArgument(childClass, TreeChildNode.class);
106 * Returns a QName associated to supplied type
110 * @return QName associated to supplied dataType. If dataType is
111 * Augmentation method does not return canonical QName, but QName
112 * with correct namespace revision, but virtual local name, since
113 * augmentations do not have name.
115 * May return null if QName is not present.
117 public static QName findQName(final Class<?> dataType) {
118 return CLASS_TO_QNAME.getUnchecked(dataType).orNull();
122 * Checks if method is RPC or Action invocation
124 * @param possibleMethod
126 * @return true if method is RPC or Action invocation, false otherwise.
128 public static boolean isOperationMethod(final Method possibleMethod) {
129 return possibleMethod != null && Operation.class.isAssignableFrom(possibleMethod.getDeclaringClass())
130 && Future.class.isAssignableFrom(possibleMethod.getReturnType())
131 // length <= 2: it seemed to be impossible to get correct OperationMethodInvoker because of
132 // resolveOperationInputClass() check.While OperationMethodInvoker counts with one argument
134 // non input type and two arguments for input type, resolveOperationInputClass() counting
135 // with zero for non input and one for input type
136 && possibleMethod.getParameterTypes().length <= 2;
140 * Extracts Output class for RPC method
142 * @param targetMethod
144 * @return Optional.absent() if result type could not be get, or return type
147 @SuppressWarnings("rawtypes")
148 public static Optional<Class<?>> resolveOperationOutputClass(final Method targetMethod) {
149 checkState(isOperationMethod(targetMethod), "Supplied method is not a RPC or Action invocation method");
150 final Type futureType = targetMethod.getGenericReturnType();
151 final Type operationResultType = ClassLoaderUtils.getFirstGenericParameter(futureType);
152 final Type operationResultArgument = ClassLoaderUtils.getFirstGenericParameter(operationResultType);
153 if (operationResultArgument instanceof Class && !Void.class.equals(operationResultArgument)) {
154 return Optional.of((Class) operationResultArgument);
156 return Optional.absent();
160 * Extracts input class for RPC or Action
162 * @param targetMethod
164 * @return Optional.absent() if RPC or Action has no input, RPC input type
167 @SuppressWarnings({ "rawtypes", "unchecked" })
168 public static Optional<Class<? extends Instantiable<?>>> resolveOperationInputClass(final Method targetMethod) {
169 for (final Class clazz : targetMethod.getParameterTypes()) {
170 if (Instantiable.class.isAssignableFrom(clazz)) {
171 return Optional.of(clazz);
174 return Optional.absent();
178 * Find qname of base identity context.
181 * - base identity type context
182 * @return QName of base identity context
184 public static QName getQName(final Class<? extends BaseIdentity> context) {
185 return findQName(context);
189 * Checks if class is child of augmentation.
193 * @return true if is augmentation, false otherwise
195 public static boolean isAugmentationChild(final Class<?> clazz) {
196 // FIXME: Current resolver could be still confused when child node was
198 checkArgument(clazz != null);
200 @SuppressWarnings({ "rawtypes", "unchecked" })
201 final Class<?> parent = findHierarchicalParent((Class) clazz);
202 if (parent == null) {
203 LOG.debug("Did not find a parent for class {}", clazz);
207 final String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
208 final String parentModelPackage = getModelRootPackageName(parent.getPackage());
210 return !clazzModelPackage.equals(parentModelPackage);
214 * Returns root package name for supplied package.
217 * Package for which find model root package.
218 * @return Package of model root.
220 public static String getModelRootPackageName(final Package pkg) {
221 return getModelRootPackageName(pkg.getName());
225 * Returns root package name for supplied package name.
228 * - package for which find model root package
229 * @return Package of model root
231 public static String getModelRootPackageName(final String name) {
232 checkArgument(name != null, "Package name should not be null.");
233 checkArgument(name.startsWith(PACKAGE_PREFIX), "Package name not starting with %s, is: %s", PACKAGE_PREFIX,
235 final Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
236 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
237 ROOT_PACKAGE_PATTERN_STRING);
238 return match.group(0);
242 * Get QName module of specific Binding object class.
245 * - class of binding object
246 * @return QName module of binding object
248 public static final QNameModule getQNameModule(final Class<?> clz) {
249 if (Instantiable.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)) {
250 return findQName(clz).getModule();
253 final YangModuleInfo modInfo = BindingReflections.getModuleInfo(clz);
254 return getQNameModule(modInfo);
255 } catch (final Exception e) {
256 throw new IllegalStateException("Unable to get QName of defining model.", e);
261 * Returns module QName.
265 * @return {@link QNameModule} from module info
267 public static final QNameModule getQNameModule(final YangModuleInfo modInfo) {
268 return QNameModule.create(URI.create(modInfo.getNamespace()), QName.parseRevision(modInfo.getRevision()));
272 * Returns instance of {@link YangModuleInfo} of declaring model for
276 * - class for getting info
277 * @return Instance of {@link YangModuleInfo} associated with model, from
278 * which this class was derived.
281 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
282 checkArgument(cls != null);
283 final String packageName = getModelRootPackageName(cls.getPackage());
284 final String potentialClassName = getModuleInfoClassName(packageName);
285 return ClassLoaderUtils.withClassLoader(cls.getClassLoader(), (Callable<YangModuleInfo>) () -> {
286 final Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
287 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
292 * Returns name of module info class.
296 * @return name of module info class
298 public static String getModuleInfoClassName(final String packageName) {
299 return packageName + "." + MODULE_INFO_CLASS_NAME;
303 * Check if supplied class is derived from YANG model.
307 * @return true if class is derived from YANG model.
309 public static boolean isBindingClass(final Class<?> cls) {
310 if (Instantiable.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)
311 || TreeNode.class.isAssignableFrom(cls)) {
314 return cls.getName().startsWith(PACKAGE_PREFIX);
318 * Checks if supplied method is callback for notifications.
322 * @return true if method is notification callback
324 public static boolean isNotificationCallback(final Method method) {
325 checkArgument(method != null);
326 if (method.getName().startsWith("on") && method.getParameterTypes().length == 1) {
327 final Class<?> potentialNotification = method.getParameterTypes()[0];
328 if (isNotification(potentialNotification)
329 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
337 * Check if supplied class is Notification.
339 * @param potentialNotification
341 * @return true if class is notification, false otherwise
343 public static boolean isNotification(final Class<?> potentialNotification) {
344 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
345 return Notification.class.isAssignableFrom(potentialNotification);
349 * Loads {@link YangModuleInfo} info available on current classloader.
351 * This method is shorthand for {@link #loadModuleInfos(ClassLoader)} with
352 * {@link Thread#getContextClassLoader()} for current thread.
354 * @return Set of {@link YangModuleInfo} available for current classloader.
356 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
357 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
361 * Loads {@link YangModuleInfo} info available on supplied classloader.
363 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for
364 * {@link YangModelBindingProvider}. {@link YangModelBindingProvider} are
365 * simple classes which holds only pointers to actual instance
366 * {@link YangModuleInfo}.
368 * When {@link YangModuleInfo} is available, all dependencies are
369 * recursively collected into returning set by collecting results of
370 * {@link YangModuleInfo#getImportedModules()}.
373 * - classloader for which {@link YangModuleInfo} should be
375 * @return Set of {@link YangModuleInfo} available for supplied classloader.
377 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
378 final Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
379 final ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
381 for (final YangModelBindingProvider bindingProvider : serviceLoader) {
382 final YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
383 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
384 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
386 return moduleInfoSet.build();
389 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
390 final Builder<YangModuleInfo> moduleInfoSet) {
391 moduleInfoSet.add(moduleInfo);
392 for (final YangModuleInfo dependency : moduleInfo.getImportedModules()) {
393 collectYangModuleInfo(dependency, moduleInfoSet);
398 * Checks if supplied class represents RPC or Action input/output.
401 * - class to be checked
402 * @return true if class represents RPC or Action input/output class
404 public static boolean isOperationType(final Class<? extends TreeNode> targetType) {
405 return Instantiable.class.isAssignableFrom(targetType) && !TreeChildNode.class.isAssignableFrom(targetType)
406 && !Notification.class.isAssignableFrom(targetType)
407 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
411 * Scans supplied class and returns an iterable of all data children
415 * - YANG Modeled Entity derived from DataContainer
416 * @return Iterable of all data children, which have YANG modeled entity
418 @SuppressWarnings("unchecked")
419 public static Iterable<Class<? extends TreeNode>> getChildrenClasses(final Class<? extends Instantiable<?>> type) {
420 checkArgument(type != null, "Target type must not be null");
421 checkArgument(Instantiable.class.isAssignableFrom(type), "Supplied type must be derived from Instantiable");
422 final List<Class<? extends TreeNode>> ret = new LinkedList<>();
423 for (final Method method : type.getMethods()) {
424 final Optional<Class<? extends Instantiable<?>>> entity = getYangModeledReturnType(method);
425 if (entity.isPresent()) {
426 ret.add((Class<? extends TreeNode>) entity.get());
433 * Scans supplied class and returns an iterable of all data children
437 * - YANG Modeled Entity derived from DataContainer
438 * @return Iterable of all data children, which have YANG modeled entity
440 public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
441 checkArgument(type != null, "Target type must not be null");
442 checkArgument(Instantiable.class.isAssignableFrom(type), "Supplied type must be derived from Instantiable");
443 final Map<Class<?>, Method> ret = new HashMap<>();
444 for (final Method method : type.getMethods()) {
445 final Optional<Class<? extends Instantiable<?>>> entity = getYangModeledReturnType(method);
446 if (entity.isPresent()) {
447 ret.put(entity.get(), method);
453 @SuppressWarnings({ "unchecked", "rawtypes" })
454 private static Optional<Class<? extends Instantiable<?>>> getYangModeledReturnType(final Method method) {
455 if ("getClass".equals(method.getName()) || !method.getName().startsWith("get")
456 || method.getParameterTypes().length > 0) {
457 return Optional.absent();
460 final Class returnType = method.getReturnType();
461 if (Instantiable.class.isAssignableFrom(returnType)) {
462 return Optional.of(returnType);
463 } else if (List.class.isAssignableFrom(returnType)) {
465 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
466 (Callable<Optional<Class<? extends Instantiable<?>>>>) () -> {
467 final Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
468 if (listResult instanceof Class
469 && Instantiable.class.isAssignableFrom((Class) listResult)) {
470 return Optional.of((Class) listResult);
472 return Optional.absent();
474 } catch (final 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.absent();
487 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
490 public Optional<QName> load(@Nonnull final Class<?> key) throws Exception {
491 return resolveQNameNoCache(key);
495 * Tries to resolve QName for supplied class.
497 * Looks up for static field with name from constant {@link #QNAME_STATIC_FIELD_NAME} and returns
500 * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types.
503 * - class for resolving QName
504 * @return resolved QName
506 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
508 final Field field = key.getField(QNAME_STATIC_FIELD_NAME);
509 final Object obj = field.get(null);
510 if (obj instanceof QName) {
511 return Optional.of((QName) obj);
514 } catch (final NoSuchFieldException e) {
515 return Optional.of(computeQName(key));
516 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
518 * It is safe to log this this exception on debug, since this method
519 * should not fail. Only failures are possible if the runtime /
522 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
524 return Optional.absent();
528 * Computes QName for supplied class
530 * Namespace and revision are same as {@link YangModuleInfo} associated
531 * with supplied class.
535 * <li>rpc/action input: local name is "input".
536 * <li>rpc/action output: local name is "output".
537 * <li>augmentation: local name is "module name".
540 * There is also fallback, if it is not possible to compute QName using
541 * following algorithm returns module QName.
543 * FIXME: Extend this algorithm to also provide QName for YANG modeled
546 * @throws IllegalStateException
547 * - if YangModuleInfo could not be resolved
548 * @throws IllegalArgumentException
549 * - if supplied class was not derived from YANG model
552 @SuppressWarnings({ "rawtypes", "unchecked" })
553 private static QName computeQName(final Class key) {
554 if (isBindingClass(key)) {
555 YangModuleInfo moduleInfo;
557 moduleInfo = getModuleInfo(key);
558 } catch (final Exception e) {
559 throw new IllegalStateException("Unable to get QName for " + key
560 + ". YangModuleInfo was not found.", e);
562 final QName module = getModuleQName(moduleInfo).intern();
563 if (Augmentation.class.isAssignableFrom(key)) {
565 } else if (isOperationType(key)) {
566 final String className = key.getSimpleName();
567 if (className.endsWith(OPERATION_ACTION_OUTPUT_SUFFIX)) {
568 return QName.create(module, "output").intern();
570 return QName.create(module, "input").intern();
574 * Fallback for Binding types which do not have QNAME field
578 throw new IllegalArgumentException("Supplied class " + key + "is not derived from YANG.");
585 * Given a {@link YangModuleInfo}, create a QName representing it. The QName
586 * is formed by reusing the module's namespace and revision using the
587 * module's name as the QName's local name.
591 * @return QName representing the module
593 public static QName getModuleQName(final YangModuleInfo moduleInfo) {
594 checkArgument(moduleInfo != null, "moduleInfo must not be null.");
595 return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(), moduleInfo.getName());
599 * Extracts augmentation from Binding DTO field using reflection
602 * Instance of DataObject which is augmentable and may contain
604 * @return Map of augmentations if read was successful, otherwise empty map.
606 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
607 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
611 * Determines if two augmentation classes or case classes represents same
614 * Two augmentations or cases could be substituted only if and if:
616 * <li>Both implements same interfaces</li>
617 * <li>Both have same children</li>
618 * <li>If augmentations: Both have same augmentation target class. Target
619 * class was generated for data node in grouping.</li>
620 * <li>If cases: Both are from same choice. Choice class was generated for
621 * data node in grouping.</li>
624 * <b>Explanation:</b> Binding Specification reuses classes generated for
625 * groupings as part of normal data tree, this classes from grouping could
626 * be used at various locations and user may not be aware of it and may use
627 * incorrect case or augmentation in particular subtree (via copy
628 * constructors, etc).
631 * - class which is potential substitution
633 * - class which should be used at particular subtree
634 * @return true if and only if classes represents same data.
636 @SuppressWarnings({ "rawtypes", "unchecked" })
637 public static boolean isSubstitutionFor(final Class potential, final Class target) {
638 final HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
639 final HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
640 if (!subImplemented.equals(targetImplemented)) {
643 if (Augmentation.class.isAssignableFrom(potential)
644 && !BindingReflections.findAugmentationTarget(potential).equals(
645 BindingReflections.findAugmentationTarget(target))) {
648 for (final Method potentialMethod : potential.getMethods()) {
650 final Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
651 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
654 } catch (final NoSuchMethodException e) {
655 // Counterpart method is missing, so classes could not be
658 } catch (final SecurityException e) {
659 throw new IllegalStateException("Could not compare methods", e);