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.yangtools.yang.binding.util;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
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.RegEx;
36 import org.opendaylight.yangtools.util.ClassLoaderUtils;
37 import org.opendaylight.yangtools.yang.binding.Augmentable;
38 import org.opendaylight.yangtools.yang.binding.Augmentation;
39 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
40 import org.opendaylight.yangtools.yang.binding.BindingMapping;
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.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 public class BindingReflections {
55 private static final long EXPIRATION_TIME = 60;
58 private static final String ROOT_PACKAGE_PATTERN_STRING =
59 "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.rev[0-9][0-9][0-1][0-9][0-3][0-9])";
60 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
61 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
63 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
65 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS)
66 .build(new ClassToQNameLoader());
68 private BindingReflections() {
69 throw new UnsupportedOperationException("Utility class.");
73 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
74 * implemented {@link Augmentation} interface.
77 * {@link Augmentation} subclass for which we want to determine
78 * augmentation target.
79 * @return Augmentation target - class which augmentation provides additional extensions.
81 public static Class<? extends Augmentable<?>> findAugmentationTarget(
82 final Class<? extends Augmentation<?>> augmentation) {
83 return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class);
87 * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
88 * {@link ChildOf} interface.
91 * child class for which we want to find the parent class.
92 * @return Parent class, e.g. class of which the childClass is ChildOf.
94 public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
95 return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class);
99 * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
100 * invoking {@link DataObject#getImplementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
103 * Child object for which the parent needs to be located.
104 * @return Parent class, or null if a parent is not found.
106 public static Class<?> findHierarchicalParent(final DataObject child) {
107 if (child instanceof ChildOf) {
108 return ClassLoaderUtils.findFirstGenericArgument(child.getImplementedInterface(), ChildOf.class);
114 * Returns a QName associated to supplied type.
116 * @param dataType Data type class
117 * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
118 * QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
119 * have name. May return null if QName is not present.
121 public static final QName findQName(final Class<?> dataType) {
122 return CLASS_TO_QNAME.getUnchecked(dataType).orNull();
126 * Checks if method is RPC invocation.
128 * @param possibleMethod
130 * @return true if method is RPC invocation, false otherwise.
132 public static boolean isRpcMethod(final Method possibleMethod) {
133 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
134 && Future.class.isAssignableFrom(possibleMethod.getReturnType())
135 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
136 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
137 // non input type and two arguments for input type, resolveRpcInputClass() counting
138 // with zero for non input and one for input type
139 && possibleMethod.getParameterTypes().length <= 2;
143 * Extracts Output class for RPC method.
145 * @param targetMethod
147 * @return Optional.absent() if result type could not be get, or return type is Void.
149 @SuppressWarnings("rawtypes")
150 public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
151 checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
152 Type futureType = targetMethod.getGenericReturnType();
153 Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType);
154 Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType);
155 if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
156 return Optional.of((Class) rpcResultArgument);
158 return Optional.absent();
162 * Extracts input class for RPC method.
164 * @param targetMethod
166 * @return Optional.absent() if RPC has no input, RPC input type otherwise.
168 @SuppressWarnings("rawtypes")
169 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
170 for (Class clazz : targetMethod.getParameterTypes()) {
171 if (DataContainer.class.isAssignableFrom(clazz)) {
172 return Optional.of(clazz);
175 return Optional.absent();
178 public static QName getQName(final Class<? extends BaseIdentity> context) {
179 return findQName(context);
183 * Checks if class is child of augmentation.
185 public static boolean isAugmentationChild(final Class<?> clazz) {
186 // FIXME: Current resolver could be still confused when child node was added by grouping
187 checkArgument(clazz != null);
189 @SuppressWarnings({ "rawtypes", "unchecked" })
190 Class<?> parent = findHierarchicalParent((Class) clazz);
191 if (parent == null) {
192 LOG.debug("Did not find a parent for class {}", clazz);
196 String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
197 String parentModelPackage = getModelRootPackageName(parent.getPackage());
199 return !clazzModelPackage.equals(parentModelPackage);
203 * Returns root package name for suplied package.
206 * Package for which find model root package.
207 * @return Package of model root.
209 public static String getModelRootPackageName(final Package pkg) {
210 return getModelRootPackageName(pkg.getName());
214 * Returns root package name for supplied package name.
217 * Package for which find model root package.
218 * @return Package of model root.
220 public static String getModelRootPackageName(final String name) {
221 checkArgument(name != null, "Package name should not be null.");
222 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
223 BindingMapping.PACKAGE_PREFIX, name);
224 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
225 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
226 ROOT_PACKAGE_PATTERN_STRING);
227 return match.group(0);
230 @SuppressWarnings("checkstyle:illegalCatch")
231 public static final QNameModule getQNameModule(final Class<?> clz) {
232 if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)) {
233 return findQName(clz).getModule();
236 YangModuleInfo modInfo = BindingReflections.getModuleInfo(clz);
237 return getQNameModule(modInfo);
238 } catch (Exception e) {
239 throw new IllegalStateException("Unable to get QName of defining model.", e);
243 public static final QNameModule getQNameModule(final YangModuleInfo modInfo) {
244 return QNameModule.create(URI.create(modInfo.getNamespace()), QName.parseRevision(modInfo.getRevision()));
248 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
250 * @param cls data object class
251 * @return Instance of {@link YangModuleInfo} associated with model, from
252 * which this class was derived.
254 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
255 checkArgument(cls != null);
256 String packageName = getModelRootPackageName(cls.getPackage());
257 final String potentialClassName = getModuleInfoClassName(packageName);
258 return ClassLoaderUtils.withClassLoader(cls.getClassLoader(), (Callable<YangModuleInfo>) () -> {
259 Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
260 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
264 public static String getModuleInfoClassName(final String packageName) {
265 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
269 * Check if supplied class is derived from YANG model.
273 * @return true if class is derived from YANG model.
275 public static boolean isBindingClass(final Class<?> cls) {
276 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
279 return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
283 * Checks if supplied method is callback for notifications.
285 * @param method method to check
286 * @return true if method is notification callback.
288 public static boolean isNotificationCallback(final Method method) {
289 checkArgument(method != null);
290 if (method.getName().startsWith("on") && method.getParameterTypes().length == 1) {
291 Class<?> potentialNotification = method.getParameterTypes()[0];
292 if (isNotification(potentialNotification)
293 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
301 * Checks is supplied class is a {@link Notification}.
303 * @param potentialNotification class to examine
304 * @return True if the class represents a Notification.
306 public static boolean isNotification(final Class<?> potentialNotification) {
307 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
308 return Notification.class.isAssignableFrom(potentialNotification);
312 * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
313 * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
315 * @return Set of {@link YangModuleInfo} available for current classloader.
317 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
318 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
322 * Loads {@link YangModuleInfo} infos available on supplied classloader.
325 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
326 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
327 * {@link YangModuleInfo}.
330 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
331 * collecting results of {@link YangModuleInfo#getImportedModules()}.
334 * Classloader for which {@link YangModuleInfo} should be
336 * @return Set of {@link YangModuleInfo} available for supplied classloader.
338 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
339 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
340 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
342 for (YangModelBindingProvider bindingProvider : serviceLoader) {
343 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
344 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
345 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
347 return moduleInfoSet.build();
350 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
351 final Builder<YangModuleInfo> moduleInfoSet) {
352 moduleInfoSet.add(moduleInfo);
353 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
354 collectYangModuleInfo(dependency, moduleInfoSet);
359 * Checks if supplied class represents RPC Input / RPC Output.
362 * Class to be checked
363 * @return true if class represents RPC Input or RPC Output class.
365 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
366 return DataContainer.class.isAssignableFrom(targetType)
367 && !ChildOf.class.isAssignableFrom(targetType)
368 && !Notification.class.isAssignableFrom(targetType)
369 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
373 * Scans supplied class and returns an iterable of all data children classes.
376 * YANG Modeled Entity derived from DataContainer
377 * @return Iterable of all data children, which have YANG modeled entity
379 @SuppressWarnings("unchecked")
380 public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
381 checkArgument(type != null, "Target type must not be null");
382 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
383 List<Class<? extends DataObject>> ret = new LinkedList<>();
384 for (Method method : type.getMethods()) {
385 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
386 if (entity.isPresent()) {
387 ret.add((Class<? extends DataObject>) entity.get());
394 * Scans supplied class and returns an iterable of all data children classes.
397 * YANG Modeled Entity derived from DataContainer
398 * @return Iterable of all data children, which have YANG modeled entity
400 public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
401 checkArgument(type != null, "Target type must not be null");
402 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
403 Map<Class<?>, Method> ret = new HashMap<>();
404 for (Method method : type.getMethods()) {
405 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
406 if (entity.isPresent()) {
407 ret.put(entity.get(), method);
413 @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" })
414 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
415 if ("getClass".equals(method.getName()) || !method.getName().startsWith("get")
416 || method.getParameterTypes().length > 0) {
417 return Optional.absent();
420 Class returnType = method.getReturnType();
421 if (DataContainer.class.isAssignableFrom(returnType)) {
422 return Optional.of(returnType);
423 } else if (List.class.isAssignableFrom(returnType)) {
425 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
426 (Callable<Optional<Class<? extends DataContainer>>>) () -> {
427 Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
428 if (listResult instanceof Class
429 && DataContainer.class.isAssignableFrom((Class) listResult)) {
430 return Optional.of((Class) listResult);
432 return Optional.absent();
434 } catch (Exception e) {
436 * It is safe to log this this exception on debug, since this
437 * method should not fail. Only failures are possible if the
440 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
443 return Optional.absent();
446 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
449 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
450 return resolveQNameNoCache(key);
454 * Tries to resolve QName for supplied class. Looks up for static field with name from constant
455 * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
456 * {@link #computeQName(Class)} to compute QName for missing types.
458 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
460 Field field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
461 Object obj = field.get(null);
462 if (obj instanceof QName) {
463 return Optional.of((QName) obj);
466 } catch (NoSuchFieldException e) {
467 return Optional.of(computeQName(key));
469 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
472 * It is safe to log this this exception on debug, since this method
473 * should not fail. Only failures are possible if the runtime /
476 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
478 return Optional.absent();
482 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
488 * <li>rpc input: local name is "input".
489 * <li>rpc output: local name is "output".
490 * <li>augmentation: local name is "module name".
494 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
497 * @throws IllegalStateException If YangModuleInfo could not be resolved
498 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
500 // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
501 @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
502 private static QName computeQName(final Class key) {
503 checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
505 YangModuleInfo moduleInfo;
507 moduleInfo = getModuleInfo(key);
508 } catch (Exception e) {
509 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
512 final QName module = getModuleQName(moduleInfo).intern();
513 if (Augmentation.class.isAssignableFrom(key)) {
515 } else if (isRpcType(key)) {
516 final String className = key.getSimpleName();
517 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
518 return QName.create(module, "output").intern();
520 return QName.create(module, "input").intern();
525 * Fallback for Binding types which do not have QNAME field
533 * Given a {@link YangModuleInfo}, create a QName representing it. The QName is formed by reusing the module's
534 * namespace and revision using the module's name as the QName's local name.
538 * @return QName representing the module
540 public static QName getModuleQName(final YangModuleInfo moduleInfo) {
541 checkArgument(moduleInfo != null, "moduleInfo must not be null.");
542 return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(), moduleInfo.getName());
546 * Extracts augmentation from Binding DTO field using reflection.
549 * Instance of DataObject which is augmentable and may contain
551 * @return Map of augmentations if read was successful, otherwise empty map.
553 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
554 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
558 * Determines if two augmentation classes or case classes represents same
562 * Two augmentations or cases could be substituted only if and if:
564 * <li>Both implements same interfaces</li>
565 * <li>Both have same children</li>
566 * <li>If augmentations: Both have same augmentation target class. Target
567 * class was generated for data node in grouping.</li>
568 * <li>If cases: Both are from same choice. Choice class was generated for
569 * data node in grouping.</li>
573 * <b>Explanation:</b> Binding Specification reuses classes generated for
574 * groupings as part of normal data tree, this classes from grouping could
575 * be used at various locations and user may not be aware of it and may use
576 * incorrect case or augmentation in particular subtree (via copy
577 * constructors, etc).
580 * Class which is potential substition
582 * Class which should be used at particular subtree
583 * @return true if and only if classes represents same data.
585 @SuppressWarnings({ "rawtypes", "unchecked" })
586 public static boolean isSubstitutionFor(final Class potential, final Class target) {
587 HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
588 HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
589 if (!subImplemented.equals(targetImplemented)) {
592 if (Augmentation.class.isAssignableFrom(potential)
593 && !BindingReflections.findAugmentationTarget(potential).equals(
594 BindingReflections.findAugmentationTarget(target))) {
597 for (Method potentialMethod : potential.getMethods()) {
599 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
600 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
603 } catch (NoSuchMethodException e) {
604 // Counterpart method is missing, so classes could not be
607 } catch (SecurityException e) {
608 throw new IllegalStateException("Could not compare methods", e);