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.spec.util;
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.Action;
37 import org.opendaylight.mdsal.binding.javav2.spec.base.BaseIdentity;
38 import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable;
39 import org.opendaylight.mdsal.binding.javav2.spec.base.Notification;
40 import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc;
41 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
42 import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModelBindingProvider;
43 import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModuleInfo;
44 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable;
45 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
46 import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode;
47 import org.opendaylight.yangtools.util.ClassLoaderUtils;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.common.QNameModule;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 public final class BindingReflections {
56 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
58 private static final long EXPIRATION_TIME = 60;
59 private static final String QNAME_STATIC_FIELD_NAME = "QNAME";
60 private static final String RPC_ACTION_OUTPUT_SUFFIX = "Output";
61 private static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl";
62 private static final String PACKAGE_PREFIX = "org.opendaylight.mdsal.gen.javav2";
63 private static final String ROOT_PACKAGE_PATTERN_STRING =
64 "(org.opendaylight.mdsal.gen.javav2.[a-z0-9_\\.]*\\.rev[0-9][0-9][0-1][0-9][0-3][0-9])";
66 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
68 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder().weakKeys()
69 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS).build(new ClassToQNameLoader());
71 private BindingReflections() {
72 throw new UnsupportedOperationException("Utility class.");
76 * Find augmentation target class from concrete Augmentation class
78 * This method uses first generic argument of implemented
79 * {@link Augmentation} interface.
82 * {@link Augmentation} subclass for which we want to determine
83 * augmentation target.
84 * @return Augmentation target - class which augmentation provides
85 * additional extensions.
87 public static Class<? extends Augmentable<?>> findAugmentationTarget(
88 final Class<? extends Augmentation<?>> augmentation) {
89 return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class);
93 * Find data hierarchy parent from concrete Tree Node class
95 * This method uses first generic argument of implemented
96 * {@link TreeChildNode} interface.
99 * - child class for which we want to find the parent class
100 * @return Parent class, e.g. class of which the childClass is ChildOf
102 static Class<?> findHierarchicalParent(final Class<? extends TreeChildNode<?, ?>> childClass) {
103 return ClassLoaderUtils.findFirstGenericArgument(childClass, TreeChildNode.class);
107 * Returns a QName associated to supplied type
111 * @return QName associated to supplied dataType. If dataType is
112 * Augmentation method does not return canonical QName, but QName
113 * with correct namespace revision, but virtual local name, since
114 * augmentations do not have name.
116 * May return null if QName is not present.
118 public static QName findQName(final Class<?> dataType) {
119 return CLASS_TO_QNAME.getUnchecked(dataType).orNull();
123 * Checks if method is RPC or Action invocation
125 * @param possibleMethod
127 * @return true if method is RPC or Action invocation, false otherwise.
129 public static boolean isRpcOrActionMethod(final Method possibleMethod) {
130 return possibleMethod != null && (Rpc.class.isAssignableFrom(possibleMethod.getDeclaringClass())
131 || Action.class.isAssignableFrom(possibleMethod.getDeclaringClass()))
132 && Future.class.isAssignableFrom(possibleMethod.getReturnType())
133 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
134 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
135 // non input type and two arguments for input type, resolveRpcInputClass() counting
136 // with zero for non input and one for input type
137 && possibleMethod.getParameterTypes().length <= 2;
141 * Extracts Output class for RPC method
143 * @param targetMethod
145 * @return Optional.absent() if result type could not be get, or return type
148 @SuppressWarnings("rawtypes")
149 public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
150 checkState(isRpcOrActionMethod(targetMethod), "Supplied method is not a RPC or Action invocation method");
151 final Type futureType = targetMethod.getGenericReturnType();
152 final Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType);
153 final Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType);
154 if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
155 return Optional.of((Class) rpcResultArgument);
157 return Optional.absent();
161 * Extracts input class for RPC or Action
163 * @param targetMethod
165 * @return Optional.absent() if RPC or Action has no input, RPC input type
168 @SuppressWarnings({ "rawtypes", "unchecked" })
169 public static Optional<Class<? extends Instantiable<?>>> resolveRpcInputClass(final Method targetMethod) {
170 for (final Class clazz : targetMethod.getParameterTypes()) {
171 if (Instantiable.class.isAssignableFrom(clazz)) {
172 return Optional.of(clazz);
175 return Optional.absent();
179 * Find qname of base identity context.
182 * - base identity type context
183 * @return QName of base identity context
185 public static QName getQName(final Class<? extends BaseIdentity> context) {
186 return findQName(context);
190 * Checks if class is child of augmentation.
194 * @return true if is augmentation, false otherwise
196 public static boolean isAugmentationChild(final Class<?> clazz) {
197 // FIXME: Current resolver could be still confused when child node was
199 checkArgument(clazz != null);
201 @SuppressWarnings({ "rawtypes", "unchecked" })
202 final Class<?> parent = findHierarchicalParent((Class) clazz);
203 if (parent == null) {
204 LOG.debug("Did not find a parent for class {}", clazz);
208 final String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
209 final String parentModelPackage = getModelRootPackageName(parent.getPackage());
211 return !clazzModelPackage.equals(parentModelPackage);
215 * Returns root package name for supplied package.
218 * Package for which find model root package.
219 * @return Package of model root.
221 public static String getModelRootPackageName(final Package pkg) {
222 return getModelRootPackageName(pkg.getName());
226 * Returns root package name for supplied package name.
229 * - package for which find model root package
230 * @return Package of model root
232 public static String getModelRootPackageName(final String name) {
233 checkArgument(name != null, "Package name should not be null.");
234 checkArgument(name.startsWith(PACKAGE_PREFIX), "Package name not starting with %s, is: %s", PACKAGE_PREFIX,
236 final Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
237 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
238 ROOT_PACKAGE_PATTERN_STRING);
239 return match.group(0);
243 * Get QName module of specific Binding object class.
246 * - class of binding object
247 * @return QName module of binding object
249 public static final QNameModule getQNameModule(final Class<?> clz) {
250 if (Instantiable.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)) {
251 return findQName(clz).getModule();
254 final YangModuleInfo modInfo = BindingReflections.getModuleInfo(clz);
255 return getQNameModule(modInfo);
256 } catch (final Exception e) {
257 throw new IllegalStateException("Unable to get QName of defining model.", e);
262 * Returns module QName.
266 * @return {@link QNameModule} from module info
268 public static final QNameModule getQNameModule(final YangModuleInfo modInfo) {
269 return QNameModule.create(URI.create(modInfo.getNamespace()), QName.parseRevision(modInfo.getRevision()));
273 * Returns instance of {@link YangModuleInfo} of declaring model for
277 * - class for getting info
278 * @return Instance of {@link YangModuleInfo} associated with model, from
279 * which this class was derived.
282 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
283 checkArgument(cls != null);
284 final String packageName = getModelRootPackageName(cls.getPackage());
285 final String potentialClassName = getModuleInfoClassName(packageName);
286 return ClassLoaderUtils.withClassLoader(cls.getClassLoader(), (Callable<YangModuleInfo>) () -> {
287 final Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
288 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
293 * Returns name of module info class.
297 * @return name of module info class
299 public static String getModuleInfoClassName(final String packageName) {
300 return packageName + "." + MODULE_INFO_CLASS_NAME;
304 * Check if supplied class is derived from YANG model.
308 * @return true if class is derived from YANG model.
310 public static boolean isBindingClass(final Class<?> cls) {
311 if (Instantiable.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)
312 || TreeNode.class.isAssignableFrom(cls)) {
315 return cls.getName().startsWith(PACKAGE_PREFIX);
319 * Checks if supplied method is callback for notifications.
323 * @return true if method is notification callback
325 public static boolean isNotificationCallback(final Method method) {
326 checkArgument(method != null);
327 if (method.getName().startsWith("on") && method.getParameterTypes().length == 1) {
328 final Class<?> potentialNotification = method.getParameterTypes()[0];
329 if (isNotification(potentialNotification)
330 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
338 * Check if supplied class is Notification.
340 * @param potentialNotification
342 * @return true if class is notification, false otherwise
344 public static boolean isNotification(final Class<?> potentialNotification) {
345 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
346 return Notification.class.isAssignableFrom(potentialNotification);
350 * Loads {@link YangModuleInfo} info available on current classloader.
352 * This method is shorthand for {@link #loadModuleInfos(ClassLoader)} with
353 * {@link Thread#getContextClassLoader()} for current thread.
355 * @return Set of {@link YangModuleInfo} available for current classloader.
357 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
358 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
362 * Loads {@link YangModuleInfo} info available on supplied classloader.
364 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for
365 * {@link YangModelBindingProvider}. {@link YangModelBindingProvider} are
366 * simple classes which holds only pointers to actual instance
367 * {@link YangModuleInfo}.
369 * When {@link YangModuleInfo} is available, all dependencies are
370 * recursively collected into returning set by collecting results of
371 * {@link YangModuleInfo#getImportedModules()}.
374 * - classloader for which {@link YangModuleInfo} should be
376 * @return Set of {@link YangModuleInfo} available for supplied classloader.
378 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
379 final Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
380 final ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
382 for (final YangModelBindingProvider bindingProvider : serviceLoader) {
383 final YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
384 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
385 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
387 return moduleInfoSet.build();
390 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
391 final Builder<YangModuleInfo> moduleInfoSet) {
392 moduleInfoSet.add(moduleInfo);
393 for (final YangModuleInfo dependency : moduleInfo.getImportedModules()) {
394 collectYangModuleInfo(dependency, moduleInfoSet);
399 * Checks if supplied class represents RPC or Action input/output.
402 * - class to be checked
403 * @return true if class represents RPC or Action input/output class
405 public static boolean isRpcOrActionType(final Class<? extends TreeNode> targetType) {
406 return Instantiable.class.isAssignableFrom(targetType) && !TreeChildNode.class.isAssignableFrom(targetType)
407 && !Notification.class.isAssignableFrom(targetType)
408 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
412 * Scans supplied class and returns an iterable of all data children
416 * - YANG Modeled Entity derived from DataContainer
417 * @return Iterable of all data children, which have YANG modeled entity
419 @SuppressWarnings("unchecked")
420 public static Iterable<Class<? extends TreeNode>> getChildrenClasses(final Class<? extends Instantiable<?>> type) {
421 checkArgument(type != null, "Target type must not be null");
422 checkArgument(Instantiable.class.isAssignableFrom(type), "Supplied type must be derived from Instantiable");
423 final List<Class<? extends TreeNode>> ret = new LinkedList<>();
424 for (final Method method : type.getMethods()) {
425 final Optional<Class<? extends Instantiable<?>>> entity = getYangModeledReturnType(method);
426 if (entity.isPresent()) {
427 ret.add((Class<? extends TreeNode>) entity.get());
434 * Scans supplied class and returns an iterable of all data children
438 * - YANG Modeled Entity derived from DataContainer
439 * @return Iterable of all data children, which have YANG modeled entity
441 public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
442 checkArgument(type != null, "Target type must not be null");
443 checkArgument(Instantiable.class.isAssignableFrom(type), "Supplied type must be derived from Instantiable");
444 final Map<Class<?>, Method> ret = new HashMap<>();
445 for (final Method method : type.getMethods()) {
446 final Optional<Class<? extends Instantiable<?>>> entity = getYangModeledReturnType(method);
447 if (entity.isPresent()) {
448 ret.put(entity.get(), method);
454 @SuppressWarnings({ "unchecked", "rawtypes" })
455 private static Optional<Class<? extends Instantiable<?>>> getYangModeledReturnType(final Method method) {
456 if ("getClass".equals(method.getName()) || !method.getName().startsWith("get")
457 || method.getParameterTypes().length > 0) {
458 return Optional.absent();
461 final Class returnType = method.getReturnType();
462 if (Instantiable.class.isAssignableFrom(returnType)) {
463 return Optional.of(returnType);
464 } else if (List.class.isAssignableFrom(returnType)) {
466 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
467 (Callable<Optional<Class<? extends Instantiable<?>>>>) () -> {
468 final Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
469 if (listResult instanceof Class
470 && Instantiable.class.isAssignableFrom((Class) listResult)) {
471 return Optional.of((Class) listResult);
473 return Optional.absent();
475 } catch (final Exception e) {
478 * It is safe to log this this exception on debug, since this
479 * method should not fail. Only failures are possible if the
482 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
485 return Optional.absent();
488 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
491 public Optional<QName> load(@Nonnull final Class<?> key) throws Exception {
492 return resolveQNameNoCache(key);
496 * Tries to resolve QName for supplied class.
498 * Looks up for static field with name from constant {@link #QNAME_STATIC_FIELD_NAME} and returns
501 * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types.
504 * - class for resolving QName
505 * @return resolved QName
507 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
509 final Field field = key.getField(QNAME_STATIC_FIELD_NAME);
510 final Object obj = field.get(null);
511 if (obj instanceof QName) {
512 return Optional.of((QName) obj);
515 } catch (final NoSuchFieldException e) {
516 return Optional.of(computeQName(key));
517 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
519 * It is safe to log this this exception on debug, since this method
520 * should not fail. Only failures are possible if the runtime /
523 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
525 return Optional.absent();
529 * Computes QName for supplied class
531 * Namespace and revision are same as {@link YangModuleInfo} associated
532 * with supplied class.
536 * <li>rpc/action input: local name is "input".
537 * <li>rpc/action output: local name is "output".
538 * <li>augmentation: local name is "module name".
541 * There is also fallback, if it is not possible to compute QName using
542 * following algorithm returns module QName.
544 * FIXME: Extend this algorithm to also provide QName for YANG modeled
547 * @throws IllegalStateException
548 * - if YangModuleInfo could not be resolved
549 * @throws IllegalArgumentException
550 * - if supplied class was not derived from YANG model
553 @SuppressWarnings({ "rawtypes", "unchecked" })
554 private static QName computeQName(final Class key) {
555 if (isBindingClass(key)) {
556 YangModuleInfo moduleInfo;
558 moduleInfo = getModuleInfo(key);
559 } catch (final Exception e) {
560 throw new IllegalStateException("Unable to get QName for " + key
561 + ". YangModuleInfo was not found.", e);
563 final QName module = getModuleQName(moduleInfo).intern();
564 if (Augmentation.class.isAssignableFrom(key)) {
566 } else if (isRpcOrActionType(key)) {
567 final String className = key.getSimpleName();
568 if (className.endsWith(RPC_ACTION_OUTPUT_SUFFIX)) {
569 return QName.create(module, "output").intern();
571 return QName.create(module, "input").intern();
575 * Fallback for Binding types which do not have QNAME field
579 throw new IllegalArgumentException("Supplied class " + key + "is not derived from YANG.");
586 * Given a {@link YangModuleInfo}, create a QName representing it. The QName
587 * is formed by reusing the module's namespace and revision using the
588 * module's name as the QName's local name.
592 * @return QName representing the module
594 public static QName getModuleQName(final YangModuleInfo moduleInfo) {
595 checkArgument(moduleInfo != null, "moduleInfo must not be null.");
596 return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(), moduleInfo.getName());
600 * Extracts augmentation from Binding DTO field using reflection
603 * Instance of DataObject which is augmentable and may contain
605 * @return Map of augmentations if read was successful, otherwise empty map.
607 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
608 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
612 * Determines if two augmentation classes or case classes represents same
615 * Two augmentations or cases could be substituted only if and if:
617 * <li>Both implements same interfaces</li>
618 * <li>Both have same children</li>
619 * <li>If augmentations: Both have same augmentation target class. Target
620 * class was generated for data node in grouping.</li>
621 * <li>If cases: Both are from same choice. Choice class was generated for
622 * data node in grouping.</li>
625 * <b>Explanation:</b> Binding Specification reuses classes generated for
626 * groupings as part of normal data tree, this classes from grouping could
627 * be used at various locations and user may not be aware of it and may use
628 * incorrect case or augmentation in particular subtree (via copy
629 * constructors, etc).
632 * - class which is potential substitution
634 * - class which should be used at particular subtree
635 * @return true if and only if classes represents same data.
637 @SuppressWarnings({ "rawtypes", "unchecked" })
638 public static boolean isSubstitutionFor(final Class potential, final Class target) {
639 final HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
640 final HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
641 if (!subImplemented.equals(targetImplemented)) {
644 if (Augmentation.class.isAssignableFrom(potential)
645 && !BindingReflections.findAugmentationTarget(potential).equals(
646 BindingReflections.findAugmentationTarget(target))) {
649 for (final Method potentialMethod : potential.getMethods()) {
651 final Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
652 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
655 } catch (final NoSuchMethodException e) {
656 // Counterpart method is missing, so classes could not be
659 } catch (final SecurityException e) {
660 throw new IllegalStateException("Could not compare methods", e);