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 javax.annotation.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.BaseIdentity;
42 import org.opendaylight.yangtools.yang.binding.ChildOf;
43 import org.opendaylight.yangtools.yang.binding.DataContainer;
44 import org.opendaylight.yangtools.yang.binding.DataObject;
45 import org.opendaylight.yangtools.yang.binding.Notification;
46 import org.opendaylight.yangtools.yang.binding.RpcService;
47 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
48 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.QNameModule;
51 import org.opendaylight.yangtools.yang.common.YangConstants;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 public final class BindingReflections {
57 private static final long EXPIRATION_TIME = 60;
60 private static final String ROOT_PACKAGE_PATTERN_STRING =
61 "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.(?:rev[0-9][0-9][0-1][0-9][0-3][0-9]|norev))";
62 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
63 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
65 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
67 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
68 .build(new ClassToQNameLoader());
70 private BindingReflections() {
71 throw new UnsupportedOperationException("Utility class.");
75 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
76 * implemented {@link Augmentation} interface.
79 * {@link Augmentation} subclass for which we want to determine
80 * augmentation target.
81 * @return Augmentation target - class which augmentation provides additional extensions.
83 public static Class<? extends Augmentable<?>> findAugmentationTarget(
84 final Class<? extends Augmentation<?>> augmentation) {
85 return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class);
89 * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
90 * {@link ChildOf} interface.
93 * child class for which we want to find the parent class.
94 * @return Parent class, e.g. class of which the childClass is ChildOf.
96 public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
97 return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class);
101 * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
102 * invoking {@link DataObject#implementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
105 * Child object for which the parent needs to be located.
106 * @return Parent class, or null if a parent is not found.
108 public static Class<?> findHierarchicalParent(final DataObject child) {
109 if (child instanceof ChildOf) {
110 return ClassLoaderUtils.findFirstGenericArgument(child.implementedInterface(), ChildOf.class);
116 * Returns a QName associated to supplied type.
118 * @param dataType Data type class
119 * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
120 * QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
121 * have name. May return null if QName is not present.
123 public static QName findQName(final Class<?> dataType) {
124 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
128 * Checks if method is RPC invocation.
130 * @param possibleMethod
132 * @return true if method is RPC invocation, false otherwise.
134 public static boolean isRpcMethod(final Method possibleMethod) {
135 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
136 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
137 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
138 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
139 // non input type and two arguments for input type, resolveRpcInputClass() counting
140 // with zero for non input and one for input type
141 && possibleMethod.getParameterCount() <= 2;
145 * Extracts Output class for RPC method.
147 * @param targetMethod
149 * @return Optional.empty() if result type could not be get, or return type is Void.
151 @SuppressWarnings("rawtypes")
152 public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
153 checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
154 Type futureType = targetMethod.getGenericReturnType();
155 Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType);
156 Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType);
157 if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
158 return Optional.of((Class) rpcResultArgument);
160 return Optional.empty();
164 * Extracts input class for RPC method.
166 * @param targetMethod
168 * @return Optional.empty() if RPC has no input, RPC input type otherwise.
170 @SuppressWarnings("rawtypes")
171 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
172 for (Class clazz : targetMethod.getParameterTypes()) {
173 if (DataContainer.class.isAssignableFrom(clazz)) {
174 return Optional.of(clazz);
177 return Optional.empty();
180 public static QName getQName(final Class<? extends BaseIdentity> context) {
181 return findQName(context);
185 * Checks if class is child of augmentation.
187 public static boolean isAugmentationChild(final Class<?> clazz) {
188 // FIXME: Current resolver could be still confused when child node was added by grouping
189 checkArgument(clazz != null);
191 @SuppressWarnings({ "rawtypes", "unchecked" })
192 Class<?> parent = findHierarchicalParent((Class) clazz);
193 if (parent == null) {
194 LOG.debug("Did not find a parent for class {}", clazz);
198 String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
199 String parentModelPackage = getModelRootPackageName(parent.getPackage());
201 return !clazzModelPackage.equals(parentModelPackage);
205 * Returns root package name for supplied package.
208 * Package for which find model root package.
209 * @return Package of model root.
211 public static String getModelRootPackageName(final Package pkg) {
212 return getModelRootPackageName(pkg.getName());
216 * Returns root package name for supplied package name.
219 * Package for which find model root package.
220 * @return Package of model root.
222 public static String getModelRootPackageName(final String name) {
223 checkArgument(name != null, "Package name should not be null.");
224 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
225 BindingMapping.PACKAGE_PREFIX, name);
226 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
227 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
228 ROOT_PACKAGE_PATTERN_STRING);
229 return match.group(0);
232 @SuppressWarnings("checkstyle:illegalCatch")
233 public static QNameModule getQNameModule(final Class<?> clz) {
234 if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
235 || Action.class.isAssignableFrom(clz)) {
236 return findQName(clz).getModule();
239 return BindingReflections.getModuleInfo(clz).getName().getModule();
240 } catch (Exception e) {
241 throw new IllegalStateException("Unable to get QName of defining model.", e);
246 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
248 * @param cls data object class
249 * @return Instance of {@link YangModuleInfo} associated with model, from
250 * which this class was derived.
252 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
253 checkArgument(cls != null);
254 String packageName = getModelRootPackageName(cls.getPackage());
255 final String potentialClassName = getModuleInfoClassName(packageName);
256 return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> {
257 Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
258 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
262 public static String getModuleInfoClassName(final String packageName) {
263 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
267 * Check if supplied class is derived from YANG model.
271 * @return true if class is derived from YANG model.
273 public static boolean isBindingClass(final Class<?> cls) {
274 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
277 return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
281 * Checks if supplied method is callback for notifications.
283 * @param method method to check
284 * @return true if method is notification callback.
286 public static boolean isNotificationCallback(final Method method) {
287 checkArgument(method != null);
288 if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
289 Class<?> potentialNotification = method.getParameterTypes()[0];
290 if (isNotification(potentialNotification)
291 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
299 * Checks is supplied class is a {@link Notification}.
301 * @param potentialNotification class to examine
302 * @return True if the class represents a Notification.
304 public static boolean isNotification(final Class<?> potentialNotification) {
305 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
306 return Notification.class.isAssignableFrom(potentialNotification);
310 * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
311 * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
313 * @return Set of {@link YangModuleInfo} available for current classloader.
315 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
316 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
320 * Loads {@link YangModuleInfo} infos available on supplied classloader.
323 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
324 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
325 * {@link YangModuleInfo}.
328 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
329 * collecting results of {@link YangModuleInfo#getImportedModules()}.
332 * Classloader for which {@link YangModuleInfo} should be
334 * @return Set of {@link YangModuleInfo} available for supplied classloader.
336 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
337 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
338 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
340 for (YangModelBindingProvider bindingProvider : serviceLoader) {
341 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
342 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
343 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
345 return moduleInfoSet.build();
348 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
349 final Builder<YangModuleInfo> moduleInfoSet) {
350 moduleInfoSet.add(moduleInfo);
351 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
352 collectYangModuleInfo(dependency, moduleInfoSet);
357 * Checks if supplied class represents RPC Input / RPC Output.
360 * Class to be checked
361 * @return true if class represents RPC Input or RPC Output class.
363 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
364 return DataContainer.class.isAssignableFrom(targetType)
365 && !ChildOf.class.isAssignableFrom(targetType)
366 && !Notification.class.isAssignableFrom(targetType)
367 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
371 * Scans supplied class and returns an iterable of all data children classes.
374 * YANG Modeled Entity derived from DataContainer
375 * @return Iterable of all data children, which have YANG modeled entity
377 @SuppressWarnings("unchecked")
378 public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
379 checkArgument(type != null, "Target type must not be null");
380 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
381 List<Class<? extends DataObject>> ret = new LinkedList<>();
382 for (Method method : type.getMethods()) {
383 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method,
384 BindingMapping.GETTER_PREFIX);
385 if (entity.isPresent()) {
386 ret.add((Class<? extends DataObject>) entity.get());
393 * Scans supplied class and returns an iterable of all data children classes.
396 * YANG Modeled Entity derived from DataContainer
397 * @return Iterable of all data children, which have YANG modeled entity
399 public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
400 return getChildrenClassToMethod(type, BindingMapping.GETTER_PREFIX);
403 private static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type, final String prefix) {
404 checkArgument(type != null, "Target type must not be null");
405 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
407 Map<Class<?>, Method> ret = new HashMap<>();
408 for (Method method : type.getMethods()) {
409 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method, prefix);
410 if (entity.isPresent()) {
411 ret.put(entity.get(), method);
418 public static Map<Class<?>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
419 return getChildrenClassToMethod(type, BindingMapping.NONNULL_PREFIX);
422 @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" })
423 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
424 final String prefix) {
425 final String methodName = method.getName();
426 if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
427 return Optional.empty();
430 Class returnType = method.getReturnType();
431 if (DataContainer.class.isAssignableFrom(returnType)) {
432 return Optional.of(returnType);
434 if (List.class.isAssignableFrom(returnType)) {
436 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> {
437 Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
438 if (listResult instanceof Class && DataContainer.class.isAssignableFrom((Class) listResult)) {
439 return Optional.of((Class) listResult);
441 return Optional.empty();
443 } catch (Exception e) {
445 * It is safe to log this this exception on debug, since this
446 * method should not fail. Only failures are possible if the
449 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
452 return Optional.empty();
455 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
458 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
459 return resolveQNameNoCache(key);
463 * Tries to resolve QName for supplied class. Looks up for static field with name from constant
464 * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
465 * {@link #computeQName(Class)} to compute QName for missing types.
467 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
471 field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
472 } catch (NoSuchFieldException e) {
473 LOG.debug("{} does not have a {} field, falling back to computation", key,
474 BindingMapping.QNAME_STATIC_FIELD_NAME, e);
475 return Optional.of(computeQName(key));
478 final Object obj = field.get(null);
479 if (obj instanceof QName) {
480 return Optional.of((QName) obj);
482 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
484 * It is safe to log this this exception on debug, since this method should not fail. Only failures are
485 * possible if the runtime / backing is inconsistent.
487 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
489 return Optional.empty();
493 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
499 * <li>rpc input: local name is "input".
500 * <li>rpc output: local name is "output".
501 * <li>augmentation: local name is "module name".
505 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
508 * @throws IllegalStateException If YangModuleInfo could not be resolved
509 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
511 // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
512 @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
513 private static QName computeQName(final Class key) {
514 checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
516 YangModuleInfo moduleInfo;
518 moduleInfo = getModuleInfo(key);
519 } catch (Exception e) {
520 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
523 final QName module = moduleInfo.getName();
524 if (Augmentation.class.isAssignableFrom(key)) {
526 } else if (isRpcType(key)) {
527 final String className = key.getSimpleName();
528 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
529 return YangConstants.operationOutputQName(module.getModule()).intern();
532 return YangConstants.operationInputQName(module.getModule()).intern();
536 * Fallback for Binding types which do not have QNAME field
543 * Extracts augmentation from Binding DTO field using reflection.
546 * Instance of DataObject which is augmentable and may contain
548 * @return Map of augmentations if read was successful, otherwise empty map.
550 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
551 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
555 * Determines if two augmentation classes or case classes represents same
559 * Two augmentations or cases could be substituted only if and if:
561 * <li>Both implements same interfaces</li>
562 * <li>Both have same children</li>
563 * <li>If augmentations: Both have same augmentation target class. Target
564 * class was generated for data node in grouping.</li>
565 * <li>If cases: Both are from same choice. Choice class was generated for
566 * data node in grouping.</li>
570 * <b>Explanation:</b> Binding Specification reuses classes generated for
571 * groupings as part of normal data tree, this classes from grouping could
572 * be used at various locations and user may not be aware of it and may use
573 * incorrect case or augmentation in particular subtree (via copy
574 * constructors, etc).
577 * Class which is potential substitution
579 * Class which should be used at particular subtree
580 * @return true if and only if classes represents same data.
582 @SuppressWarnings({ "rawtypes", "unchecked" })
583 public static boolean isSubstitutionFor(final Class potential, final Class target) {
584 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
585 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
586 if (!subImplemented.equals(targetImplemented)) {
589 if (Augmentation.class.isAssignableFrom(potential)
590 && !BindingReflections.findAugmentationTarget(potential).equals(
591 BindingReflections.findAugmentationTarget(target))) {
594 for (Method potentialMethod : potential.getMethods()) {
596 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
597 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
600 } catch (NoSuchMethodException e) {
601 // Counterpart method is missing, so classes could not be substituted.
603 } catch (SecurityException e) {
604 throw new IllegalStateException("Could not compare methods", e);