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.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.lang.reflect.Type;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.LinkedList;
28 import java.util.List;
30 import java.util.ServiceLoader;
31 import java.util.concurrent.Callable;
32 import java.util.concurrent.Future;
33 import java.util.concurrent.TimeUnit;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
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;
56 private static final String ROOT_PACKAGE_PATTERN_STRING = "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.rev[0-9][0-9][0-1][0-9][0-3][0-9])";
57 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
58 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
60 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder() //
62 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS) //
63 .build(new ClassToQNameLoader());
65 private BindingReflections() {
66 throw new UnsupportedOperationException("Utility class.");
70 * Find augmentation target class from concrete Augmentation class
72 * This method uses first generic argument of implemented
73 * {@link Augmentation} interface.
76 * {@link Augmentation} subclass for which we want to determine
77 * augmentation target.
78 * @return Augmentation target - class which augmentation provides
79 * 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
89 * This method uses first generic argument of implemented {@link ChildOf}
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
103 * This method is shorthand which gets DataObject class by invoking
104 * {@link DataObject#getImplementedInterface()} and uses
105 * {@link #findHierarchicalParent(Class)}.
108 * Child object for which the parent needs to be located.
109 * @return Parent class, or null if a parent is not found.
111 public static Class<?> findHierarchicalParent(final DataObject child) {
112 if (child instanceof ChildOf) {
113 return ClassLoaderUtils.findFirstGenericArgument(child.getImplementedInterface(), ChildOf.class);
119 * Returns a QName associated to supplied type
122 * @return QName associated to supplied dataType. If dataType is
123 * Augmentation method does not return canonical QName, but QName
124 * with correct namespace revision, but virtual local name, since
125 * augmentations do not have name.
127 * May return null if QName is not present.
129 public static final QName findQName(final Class<?> dataType) {
130 return CLASS_TO_QNAME.getUnchecked(dataType).orNull();
134 * Checks if method is RPC invocation
138 * @param possibleMethod
140 * @return true if method is RPC invocation, false otherwise.
142 public static boolean isRpcMethod(final Method possibleMethod) {
143 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
144 && Future.class.isAssignableFrom(possibleMethod.getReturnType())
145 && possibleMethod.getParameterTypes().length <= 1;
150 * Extracts Output class for RPC method
152 * @param targetMethod
154 * @return Optional.absent() if result type could not be get, or return type
157 @SuppressWarnings("rawtypes")
158 public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
159 checkState(isRpcMethod(targetMethod), "Supplied method is not Rpc invocation method");
160 Type futureType = targetMethod.getGenericReturnType();
161 Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType);
162 Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType);
163 if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
164 return Optional.<Class<?>> of((Class) rpcResultArgument);
166 return Optional.absent();
171 * Extracts input class for RPC method
173 * @param targetMethod
175 * @return Optional.absent() if rpc has no input, Rpc input type otherwise.
177 @SuppressWarnings("unchecked")
178 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
179 @SuppressWarnings("rawtypes")
180 Class[] types = targetMethod.getParameterTypes();
181 if (types.length == 0) {
182 return Optional.absent();
184 if (types.length == 1) {
185 return Optional.<Class<? extends DataContainer>> of(types[0]);
187 throw new IllegalArgumentException("Method has 2 or more arguments.");
190 public static QName getQName(final Class<? extends BaseIdentity> context) {
191 return findQName(context);
196 * Checks if class is child of augmentation.
202 public static boolean isAugmentationChild(final Class<?> clazz) {
203 // FIXME: Current resolver could be still confused when
204 // child node was added by grouping
205 checkArgument(clazz != null);
207 @SuppressWarnings({ "rawtypes", "unchecked" })
208 Class<?> parent = findHierarchicalParent((Class) clazz);
209 if (parent == null) {
210 LOG.debug("Did not find a parent for class {}", clazz);
214 String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
215 String parentModelPackage = getModelRootPackageName(parent.getPackage());
217 return !clazzModelPackage.equals(parentModelPackage);
221 * Returns root package name for suplied package.
224 * Package for which find model root package.
225 * @return Package of model root.
227 public static String getModelRootPackageName(final Package pkg) {
228 return getModelRootPackageName(pkg.getName());
232 * Returns root package name for supplied package name.
235 * Package for which find model root package.
236 * @return Package of model root.
238 public static String getModelRootPackageName(final String name) {
239 checkArgument(name != null, "Package name should not be null.");
240 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
241 BindingMapping.PACKAGE_PREFIX, name);
242 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
243 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
244 ROOT_PACKAGE_PATTERN_STRING);
245 return match.group(0);
248 public static final QNameModule getQNameModule(Class<?> clz) {
249 if(DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)) {
250 return findQName(clz).getModule();
253 YangModuleInfo modInfo = BindingReflections.getModuleInfo(clz);
254 return getQNameModule(modInfo);
255 } catch (Exception e) {
256 throw new IllegalStateException("Unable to get QName of defining model.", e);
260 public static final QNameModule getQNameModule(YangModuleInfo modInfo) {
261 return QNameModule.create(URI.create(modInfo.getNamespace()), QName.parseRevision(modInfo.getRevision()));
266 * Returns instance of {@link YangModuleInfo} of declaring model for
270 * @return Instance of {@link YangModuleInfo} associated with model, from
271 * which this class was derived.
274 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
275 checkArgument(cls != null);
276 String packageName = getModelRootPackageName(cls.getPackage());
277 final String potentialClassName = getModuleInfoClassName(packageName);
278 return ClassLoaderUtils.withClassLoader(cls.getClassLoader(), new Callable<YangModuleInfo>() {
280 public YangModuleInfo call() throws ClassNotFoundException, IllegalAccessException,
281 IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
282 Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
283 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
288 public static String getModuleInfoClassName(final String packageName) {
289 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
294 * Check if supplied class is derived from YANG model.
298 * @return true if class is derived from YANG model.
300 public static boolean isBindingClass(final Class<?> cls) {
301 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
304 return (cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX));
309 * Checks if supplied method is callback for notifications.
312 * @return true if method is notification callback.
314 public static boolean isNotificationCallback(final Method method) {
315 checkArgument(method != null);
316 if (method.getName().startsWith("on") && method.getParameterTypes().length == 1) {
317 Class<?> potentialNotification = method.getParameterTypes()[0];
318 if (isNotification(potentialNotification)
319 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
328 * Checks is supplied class is Notification.
330 * @param potentialNotification
333 public static boolean isNotification(final Class<?> potentialNotification) {
334 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
335 return Notification.class.isAssignableFrom(potentialNotification);
340 * Loads {@link YangModuleInfo} infos available on current classloader.
342 * This method is shorthand for {@link #loadModuleInfos(ClassLoader)} with
343 * {@link Thread#getContextClassLoader()} for current thread.
345 * @return Set of {@link YangModuleInfo} available for current classloader.
347 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
348 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
353 * Loads {@link YangModuleInfo} infos available on supplied classloader.
355 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for
356 * {@link YangModelBindingProvider}. {@link YangModelBindingProvider} are
357 * simple classes which holds only pointers to actual instance
358 * {@link YangModuleInfo}.
360 * When {@link YangModuleInfo} is available, all dependencies are
361 * recursivelly collected into returning set by collecting results of
362 * {@link YangModuleInfo#getImportedModules()}.
366 * Classloader for which {@link YangModuleInfo} should be
368 * @return Set of {@link YangModuleInfo} available for supplied classloader.
370 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
371 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.<YangModuleInfo> builder();
372 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
374 for (YangModelBindingProvider bindingProvider : serviceLoader) {
375 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
376 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
377 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
379 return moduleInfoSet.build();
382 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
383 final Builder<YangModuleInfo> moduleInfoSet) {
384 moduleInfoSet.add(moduleInfo);
385 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
386 collectYangModuleInfo(dependency, moduleInfoSet);
392 * Checks if supplied class represents RPC Input / RPC Output.
395 * Class to be checked
396 * @return true if class represents RPC Input or RPC Output class.
398 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
399 return DataContainer.class.isAssignableFrom(targetType) //
400 && !ChildOf.class.isAssignableFrom(targetType) //
401 && !Notification.class.isAssignableFrom(targetType) //
402 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
407 * Scans supplied class and returns an iterable of all data children
411 * YANG Modeled Entity derived from DataContainer
412 * @return Iterable of all data children, which have YANG modeled entity
414 @SuppressWarnings("unchecked")
415 public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
416 checkArgument(type != null, "Target type must not be null");
417 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
418 List<Class<? extends DataObject>> ret = new LinkedList<>();
419 for (Method method : type.getMethods()) {
420 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
421 if (entity.isPresent()) {
422 ret.add((Class<? extends DataObject>) entity.get());
430 * Scans supplied class and returns an iterable of all data children
434 * YANG Modeled Entity derived from DataContainer
435 * @return Iterable of all data children, which have YANG modeled entity
437 public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
438 checkArgument(type != null, "Target type must not be null");
439 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
440 Map<Class<?>, Method> ret = new HashMap<>();
441 for (Method method : type.getMethods()) {
442 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
443 if (entity.isPresent()) {
444 ret.put(entity.get(), method);
450 @SuppressWarnings("unchecked")
451 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
452 if (method.getName().equals("getClass") || !method.getName().startsWith("get")
453 || method.getParameterTypes().length > 0) {
454 return Optional.absent();
457 @SuppressWarnings("rawtypes")
458 Class returnType = method.getReturnType();
459 if (DataContainer.class.isAssignableFrom(returnType)) {
460 return Optional.<Class<? extends DataContainer>> of(returnType);
461 } else if (List.class.isAssignableFrom(returnType)) {
463 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
464 new Callable<Optional<Class<? extends DataContainer>>>() {
465 @SuppressWarnings("rawtypes")
467 public Optional<Class<? extends DataContainer>> call() {
468 Type listResult = ClassLoaderUtils.getFirstGenericParameter(method
469 .getGenericReturnType());
470 if (listResult instanceof Class
471 && DataContainer.class.isAssignableFrom((Class) listResult)) {
472 return Optional.<Class<? extends DataContainer>> of((Class) listResult);
474 return Optional.absent();
478 } catch (Exception e) {
481 * It is safe to log this this exception on debug, since this
482 * method should not fail. Only failures are possible if the
485 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
488 return Optional.absent();
491 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
494 public Optional<QName> load(final Class<?> key) throws Exception {
495 return resolveQNameNoCache(key);
501 * Tries to resolve QName for supplied class.
503 * Looks up for static field with name from constant
504 * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if
507 * If field is not present uses {@link #computeQName(Class)} to compute
508 * QName for missing types.
513 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
515 Field field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
516 Object obj = field.get(null);
517 if (obj instanceof QName) {
518 return Optional.of((QName) obj);
521 } catch (NoSuchFieldException e) {
522 return Optional.of(computeQName(key));
524 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
527 * It is safe to log this this exception on debug, since this method
528 * should not fail. Only failures are possible if the runtime /
531 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
533 return Optional.absent();
537 * Computes QName for supplied class
539 * Namespace and revision are same as {@link YangModuleInfo} associated with
544 * <li>rpc input: local name is "input".
545 * <li>rpc output: local name is "output".
546 * <li>augmentation: local name is "module name".
549 * There is also fallback, if it is not possible to compute QName using
550 * following algorithm returns module QName.
552 * FIXME: Extend this algorithm to also provide QName for YANG modeled
555 * @throws IllegalStateException
556 * If YangModuleInfo could not be resolved
557 * @throws IllegalArgumentException
558 * If supplied class was not derived from YANG model.
561 @SuppressWarnings({ "rawtypes", "unchecked" })
562 private static QName computeQName(final Class key) {
563 if (isBindingClass(key)) {
564 YangModuleInfo moduleInfo;
566 moduleInfo = getModuleInfo(key);
567 } catch (Exception e) {
568 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.", e);
570 final QName module = getModuleQName(moduleInfo);
571 if (Augmentation.class.isAssignableFrom(key)) {
573 } else if (isRpcType(key)) {
574 final String className = key.getSimpleName();
575 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
576 return QName.create(module, "output");
578 return QName.create(module, "input");
582 * Fallback for Binding types which fo not have QNAME field
586 throw new IllegalArgumentException("Supplied class " + key + "is not derived from YANG.");
591 * Given a {@link YangModuleInfo}, create a QName representing it. The QName
592 * is formed by reusing the module's namespace and revision using the
593 * module's name as the QName's local name.
597 * @return QName representing the module
599 public static QName getModuleQName(final YangModuleInfo moduleInfo) {
600 checkArgument(moduleInfo != null, "moduleInfo must not be null.");
601 return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(), moduleInfo.getName());
605 * Extracts augmentation from Binding DTO field using reflection
608 * Instance of DataObject which is augmentable and may contain
610 * @return Map of augmentations if read was successful, otherwise empty map.
612 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
613 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
618 * Determines if two augmentation classes or case classes represents same
621 * Two augmentations or cases could be substituted only if and if:
623 * <li>Both implements same interfaces</li>
624 * <li>Both have same children</li>
625 * <li>If augmentations: Both have same augmentation target class. Target
626 * class was generated for data node in grouping.</li>
627 * <li>If cases: Both are from same choice. Choice class was generated for
628 * data node in grouping.</li>
631 * <b>Explanation:</b> Binding Specification reuses classes generated for
632 * groupings as part of normal data tree, this classes from grouping could
633 * be used at various locations and user may not be aware of it and may use
634 * incorrect case or augmentation in particular subtree (via copy
635 * constructors, etc).
638 * Class which is potential substition
640 * Class which should be used at particular subtree
641 * @return true if and only if classes represents same data.
643 @SuppressWarnings({ "rawtypes", "unchecked" })
644 public static boolean isSubstitutionFor(final Class potential, final Class target) {
645 HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
646 HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
647 if (!subImplemented.equals(targetImplemented)) {
650 if (Augmentation.class.isAssignableFrom(potential)
651 && !BindingReflections.findAugmentationTarget(potential).equals(
652 BindingReflections.findAugmentationTarget(target))) {
655 for (Method potentialMethod : potential.getMethods()) {
657 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
658 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
661 } catch (NoSuchMethodException e) {
662 // Counterpart method is missing, so classes could not be
665 } catch (SecurityException e) {
666 throw new IllegalStateException("Could not compare methods", e);