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.collect.Sets;
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.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;
31 import java.util.concurrent.TimeUnit;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import javax.annotation.RegEx;
35 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
36 import org.opendaylight.yangtools.util.ClassLoaderUtils;
37 import org.opendaylight.yangtools.yang.binding.Action;
38 import org.opendaylight.yangtools.yang.binding.Augmentable;
39 import org.opendaylight.yangtools.yang.binding.Augmentation;
40 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
41 import org.opendaylight.yangtools.yang.binding.ChildOf;
42 import org.opendaylight.yangtools.yang.binding.DataContainer;
43 import org.opendaylight.yangtools.yang.binding.DataObject;
44 import org.opendaylight.yangtools.yang.binding.Notification;
45 import org.opendaylight.yangtools.yang.binding.RpcService;
46 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
47 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.common.QNameModule;
50 import org.opendaylight.yangtools.yang.common.YangConstants;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public final class BindingReflections {
56 private static final long EXPIRATION_TIME = 60;
59 private static final String ROOT_PACKAGE_PATTERN_STRING =
60 "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.(?:rev[0-9][0-9][0-1][0-9][0-3][0-9]|norev))";
61 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
62 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
64 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
66 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
67 .build(new ClassToQNameLoader());
69 private BindingReflections() {
70 throw new UnsupportedOperationException("Utility class.");
74 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
75 * implemented {@link Augmentation} interface.
78 * {@link Augmentation} subclass for which we want to determine
79 * augmentation target.
80 * @return Augmentation target - class which augmentation provides additional extensions.
82 public static Class<? extends Augmentable<?>> findAugmentationTarget(
83 final Class<? extends Augmentation<?>> augmentation) {
84 return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class);
88 * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
89 * {@link ChildOf} interface.
92 * child class for which we want to find the parent class.
93 * @return Parent class, e.g. class of which the childClass is ChildOf.
95 public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
96 return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class);
100 * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
101 * invoking {@link DataObject#getImplementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
104 * Child object for which the parent needs to be located.
105 * @return Parent class, or null if a parent is not found.
107 public static Class<?> findHierarchicalParent(final DataObject child) {
108 if (child instanceof ChildOf) {
109 return ClassLoaderUtils.findFirstGenericArgument(child.getImplementedInterface(), ChildOf.class);
115 * Returns a QName associated to supplied type.
117 * @param dataType Data type class
118 * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
119 * QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
120 * have name. May return null if QName is not present.
122 public static QName findQName(final Class<?> dataType) {
123 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
127 * Checks if method is RPC invocation.
129 * @param possibleMethod
131 * @return true if method is RPC invocation, false otherwise.
133 public static boolean isRpcMethod(final Method possibleMethod) {
134 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
135 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
136 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
137 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
138 // non input type and two arguments for input type, resolveRpcInputClass() counting
139 // with zero for non input and one for input type
140 && possibleMethod.getParameterCount() <= 2;
144 * Extracts Output class for RPC method.
146 * @param targetMethod
148 * @return Optional.empty() if result type could not be get, or return type is Void.
150 @SuppressWarnings("rawtypes")
151 public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
152 checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
153 Type futureType = targetMethod.getGenericReturnType();
154 Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType);
155 Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType);
156 if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
157 return Optional.of((Class) rpcResultArgument);
159 return Optional.empty();
163 * Extracts input class for RPC method.
165 * @param targetMethod
167 * @return Optional.empty() if RPC has no input, RPC input type otherwise.
169 @SuppressWarnings("rawtypes")
170 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
171 for (Class clazz : targetMethod.getParameterTypes()) {
172 if (DataContainer.class.isAssignableFrom(clazz)) {
173 return Optional.of(clazz);
176 return Optional.empty();
179 public static QName getQName(final Class<? extends BaseIdentity> context) {
180 return findQName(context);
184 * Checks if class is child of augmentation.
186 public static boolean isAugmentationChild(final Class<?> clazz) {
187 // FIXME: Current resolver could be still confused when child node was added by grouping
188 checkArgument(clazz != null);
190 @SuppressWarnings({ "rawtypes", "unchecked" })
191 Class<?> parent = findHierarchicalParent((Class) clazz);
192 if (parent == null) {
193 LOG.debug("Did not find a parent for class {}", clazz);
197 String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
198 String parentModelPackage = getModelRootPackageName(parent.getPackage());
200 return !clazzModelPackage.equals(parentModelPackage);
204 * Returns root package name for suplied package.
207 * Package for which find model root package.
208 * @return Package of model root.
210 public static String getModelRootPackageName(final Package pkg) {
211 return getModelRootPackageName(pkg.getName());
215 * Returns root package name for supplied package name.
218 * Package for which find model root package.
219 * @return Package of model root.
221 public static String getModelRootPackageName(final String name) {
222 checkArgument(name != null, "Package name should not be null.");
223 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
224 BindingMapping.PACKAGE_PREFIX, name);
225 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
226 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
227 ROOT_PACKAGE_PATTERN_STRING);
228 return match.group(0);
231 @SuppressWarnings("checkstyle:illegalCatch")
232 public static QNameModule getQNameModule(final Class<?> clz) {
233 if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
234 || Action.class.isAssignableFrom(clz)) {
235 return findQName(clz).getModule();
238 return BindingReflections.getModuleInfo(clz).getName().getModule();
239 } catch (Exception e) {
240 throw new IllegalStateException("Unable to get QName of defining model.", e);
245 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
247 * @param cls data object class
248 * @return Instance of {@link YangModuleInfo} associated with model, from
249 * which this class was derived.
251 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
252 checkArgument(cls != null);
253 String packageName = getModelRootPackageName(cls.getPackage());
254 final String potentialClassName = getModuleInfoClassName(packageName);
255 return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> {
256 Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
257 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
261 public static String getModuleInfoClassName(final String packageName) {
262 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
266 * Check if supplied class is derived from YANG model.
270 * @return true if class is derived from YANG model.
272 public static boolean isBindingClass(final Class<?> cls) {
273 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
276 return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
280 * Checks if supplied method is callback for notifications.
282 * @param method method to check
283 * @return true if method is notification callback.
285 public static boolean isNotificationCallback(final Method method) {
286 checkArgument(method != null);
287 if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
288 Class<?> potentialNotification = method.getParameterTypes()[0];
289 if (isNotification(potentialNotification)
290 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
298 * Checks is supplied class is a {@link Notification}.
300 * @param potentialNotification class to examine
301 * @return True if the class represents a Notification.
303 public static boolean isNotification(final Class<?> potentialNotification) {
304 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
305 return Notification.class.isAssignableFrom(potentialNotification);
309 * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
310 * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
312 * @return Set of {@link YangModuleInfo} available for current classloader.
314 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
315 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
319 * Loads {@link YangModuleInfo} infos available on supplied classloader.
322 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
323 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
324 * {@link YangModuleInfo}.
327 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
328 * collecting results of {@link YangModuleInfo#getImportedModules()}.
331 * Classloader for which {@link YangModuleInfo} should be
333 * @return Set of {@link YangModuleInfo} available for supplied classloader.
335 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
336 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
337 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
339 for (YangModelBindingProvider bindingProvider : serviceLoader) {
340 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
341 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
342 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
344 return moduleInfoSet.build();
347 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
348 final Builder<YangModuleInfo> moduleInfoSet) {
349 moduleInfoSet.add(moduleInfo);
350 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
351 collectYangModuleInfo(dependency, moduleInfoSet);
356 * Checks if supplied class represents RPC Input / RPC Output.
359 * Class to be checked
360 * @return true if class represents RPC Input or RPC Output class.
362 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
363 return DataContainer.class.isAssignableFrom(targetType)
364 && !ChildOf.class.isAssignableFrom(targetType)
365 && !Notification.class.isAssignableFrom(targetType)
366 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
370 * Scans supplied class and returns an iterable of all data children classes.
373 * YANG Modeled Entity derived from DataContainer
374 * @return Iterable of all data children, which have YANG modeled entity
376 @SuppressWarnings("unchecked")
377 public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
378 checkArgument(type != null, "Target type must not be null");
379 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
380 List<Class<? extends DataObject>> ret = new LinkedList<>();
381 for (Method method : type.getMethods()) {
382 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method,
383 BindingMapping.GETTER_PREFIX);
384 if (entity.isPresent()) {
385 ret.add((Class<? extends DataObject>) entity.get());
392 * Scans supplied class and returns an iterable of all data children classes.
395 * YANG Modeled Entity derived from DataContainer
396 * @return Iterable of all data children, which have YANG modeled entity
398 public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
399 return getChildrenClassToMethod(type, BindingMapping.GETTER_PREFIX);
402 private static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type, final String prefix) {
403 checkArgument(type != null, "Target type must not be null");
404 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
406 Map<Class<?>, Method> ret = new HashMap<>();
407 for (Method method : type.getMethods()) {
408 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method, prefix);
409 if (entity.isPresent()) {
410 ret.put(entity.get(), method);
417 public static Map<Class<?>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
418 return getChildrenClassToMethod(type, BindingMapping.NONNULL_PREFIX);
421 @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" })
422 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
423 final String prefix) {
424 final String methodName = method.getName();
425 if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
426 return Optional.empty();
429 Class returnType = method.getReturnType();
430 if (DataContainer.class.isAssignableFrom(returnType)) {
431 return Optional.of(returnType);
433 if (List.class.isAssignableFrom(returnType)) {
435 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> {
436 Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
437 if (listResult instanceof Class && DataContainer.class.isAssignableFrom((Class) listResult)) {
438 return Optional.of((Class) listResult);
440 return Optional.empty();
442 } catch (Exception e) {
444 * It is safe to log this this exception on debug, since this
445 * method should not fail. Only failures are possible if the
448 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
451 return Optional.empty();
454 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
457 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
458 return resolveQNameNoCache(key);
462 * Tries to resolve QName for supplied class. Looks up for static field with name from constant
463 * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
464 * {@link #computeQName(Class)} to compute QName for missing types.
466 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
470 field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
471 } catch (NoSuchFieldException e) {
472 LOG.debug("{} does not have a {} field, falling back to computation", key,
473 BindingMapping.QNAME_STATIC_FIELD_NAME, e);
474 return Optional.of(computeQName(key));
477 final Object obj = field.get(null);
478 if (obj instanceof QName) {
479 return Optional.of((QName) obj);
481 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
483 * It is safe to log this this exception on debug, since this method should not fail. Only failures are
484 * possible if the runtime / backing is inconsistent.
486 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
488 return Optional.empty();
492 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
498 * <li>rpc input: local name is "input".
499 * <li>rpc output: local name is "output".
500 * <li>augmentation: local name is "module name".
504 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
507 * @throws IllegalStateException If YangModuleInfo could not be resolved
508 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
510 // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
511 @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
512 private static QName computeQName(final Class key) {
513 checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
515 YangModuleInfo moduleInfo;
517 moduleInfo = getModuleInfo(key);
518 } catch (Exception e) {
519 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
522 final QName module = moduleInfo.getName();
523 if (Augmentation.class.isAssignableFrom(key)) {
525 } else if (isRpcType(key)) {
526 final String className = key.getSimpleName();
527 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
528 return YangConstants.operationOutputQName(module.getModule()).intern();
531 return YangConstants.operationInputQName(module.getModule()).intern();
535 * Fallback for Binding types which do not have QNAME field
542 * Extracts augmentation from Binding DTO field using reflection.
545 * Instance of DataObject which is augmentable and may contain
547 * @return Map of augmentations if read was successful, otherwise empty map.
549 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
550 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
554 * Determines if two augmentation classes or case classes represents same
558 * Two augmentations or cases could be substituted only if and if:
560 * <li>Both implements same interfaces</li>
561 * <li>Both have same children</li>
562 * <li>If augmentations: Both have same augmentation target class. Target
563 * class was generated for data node in grouping.</li>
564 * <li>If cases: Both are from same choice. Choice class was generated for
565 * data node in grouping.</li>
569 * <b>Explanation:</b> Binding Specification reuses classes generated for
570 * groupings as part of normal data tree, this classes from grouping could
571 * be used at various locations and user may not be aware of it and may use
572 * incorrect case or augmentation in particular subtree (via copy
573 * constructors, etc).
576 * Class which is potential substitution
578 * Class which should be used at particular subtree
579 * @return true if and only if classes represents same data.
581 @SuppressWarnings({ "rawtypes", "unchecked" })
582 public static boolean isSubstitutionFor(final Class potential, final Class target) {
583 HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
584 HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
585 if (!subImplemented.equals(targetImplemented)) {
588 if (Augmentation.class.isAssignableFrom(potential)
589 && !BindingReflections.findAugmentationTarget(potential).equals(
590 BindingReflections.findAugmentationTarget(target))) {
593 for (Method potentialMethod : potential.getMethods()) {
595 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
596 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
599 } catch (NoSuchMethodException e) {
600 // Counterpart method is missing, so classes could not be substituted.
602 } catch (SecurityException e) {
603 throw new IllegalStateException("Could not compare methods", e);