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;
12 import com.google.common.base.Optional;
13 import com.google.common.cache.CacheBuilder;
14 import com.google.common.cache.CacheLoader;
15 import com.google.common.cache.LoadingCache;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.ImmutableSet.Builder;
18 import com.google.common.collect.Sets;
19 import java.lang.reflect.Field;
20 import java.lang.reflect.InvocationTargetException;
21 import java.lang.reflect.Method;
22 import java.lang.reflect.Type;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.LinkedList;
26 import java.util.List;
28 import java.util.ServiceLoader;
29 import java.util.concurrent.Callable;
30 import java.util.concurrent.Future;
31 import java.util.concurrent.TimeUnit;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import org.opendaylight.yangtools.util.ClassLoaderUtils;
35 import org.opendaylight.yangtools.yang.binding.Augmentable;
36 import org.opendaylight.yangtools.yang.binding.Augmentation;
37 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
38 import org.opendaylight.yangtools.yang.binding.BindingMapping;
39 import org.opendaylight.yangtools.yang.binding.ChildOf;
40 import org.opendaylight.yangtools.yang.binding.DataContainer;
41 import org.opendaylight.yangtools.yang.binding.DataObject;
42 import org.opendaylight.yangtools.yang.binding.Notification;
43 import org.opendaylight.yangtools.yang.binding.RpcService;
44 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
45 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
50 public class BindingReflections {
52 private static final long EXPIRATION_TIME = 60;
53 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])";
54 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
55 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
57 private static final LoadingCache<Class<?>, Optional<QName>> classToQName = CacheBuilder.newBuilder() //
59 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS) //
60 .build(new ClassToQNameLoader());
64 private BindingReflections() {
65 throw new UnsupportedOperationException("Utility class.");
69 * Find augmentation target class from concrete Augmentation class
71 * This method uses first generic argument of
72 * implemented {@link Augmentation} interface.
75 * {@link Augmentation} subclass for which we want to determine
76 * augmentation target.
77 * @return Augmentation target - class which augmentation provides
78 * additional extensions.
80 public static Class<? extends Augmentable<?>> findAugmentationTarget(
81 final Class<? extends Augmentation<?>> augmentation) {
82 return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class);
86 * Find data hierarchy parent from concrete Data class
88 * This method uses first generic argument of
89 * implemented {@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
102 * This method is shorthand which gets DataObject class by invoking
103 * {@link DataObject#getImplementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
106 * Child object for which the parent needs to be located.
107 * @return Parent class, or null if a parent is not found.
109 public static Class<?> findHierarchicalParent(final DataObject child) {
110 if (child instanceof ChildOf) {
111 return ClassLoaderUtils.findFirstGenericArgument(child.getImplementedInterface(), ChildOf.class);
117 * Returns a QName associated to supplied type
120 * @return QName associated to supplied dataType. If dataType is
121 * Augmentation method does not return canonical QName, but QName
122 * with correct namespace revision, but virtual local name, since
123 * augmentations do not have name.
125 * May return null if QName is not present.
127 public static final QName findQName(final Class<?> dataType) {
128 return classToQName.getUnchecked(dataType).orNull();
132 * Checks if method is RPC invocation
136 * @param possibleMethod Method to check
137 * @return true if method is RPC invocation, false otherwise.
139 public static boolean isRpcMethod(final Method possibleMethod) {
140 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
141 && Future.class.isAssignableFrom(possibleMethod.getReturnType())
142 && possibleMethod.getParameterTypes().length <= 1;
147 * Extracts Output class for RPC method
149 * @param targetMethod method to scan
150 * @return Optional.absent() if result type could not be get,
151 * or return type is Void.
153 @SuppressWarnings("rawtypes")
154 public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
155 checkState(isRpcMethod(targetMethod), "Supplied method is not Rpc invocation method");
156 Type futureType = targetMethod.getGenericReturnType();
157 Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType);
158 Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType);
159 if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
160 return Optional.<Class<?>> of((Class) rpcResultArgument);
162 return Optional.absent();
167 * Extracts input class for RPC method
169 * @param targetMethod method to scan
170 * @return Optional.absent() if rpc has no input, Rpc input type otherwise.
172 @SuppressWarnings("unchecked")
173 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
174 @SuppressWarnings("rawtypes")
175 Class[] types = targetMethod.getParameterTypes();
176 if (types.length == 0) {
177 return Optional.absent();
179 if (types.length == 1) {
180 return Optional.<Class<? extends DataContainer>> of(types[0]);
182 throw new IllegalArgumentException("Method has 2 or more arguments.");
185 public static QName getQName(final Class<? extends BaseIdentity> context) {
186 return findQName(context);
191 * Checks if class is child of augmentation.
197 public static boolean isAugmentationChild(final Class<?> clazz) {
198 // FIXME: Current resolver could be still confused when
199 // child node was added by grouping
200 checkArgument(clazz != null);
202 @SuppressWarnings({ "rawtypes", "unchecked" })
203 Class<?> parent = findHierarchicalParent((Class) clazz);
204 if (parent == null) {
205 LOG.debug("Did not find a parent for class {}", clazz);
209 String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
210 String parentModelPackage = getModelRootPackageName(parent.getPackage());
212 return !clazzModelPackage.equals(parentModelPackage);
216 * Returns root package name for suplied package.
218 * @param pkg 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.
228 * @param name Package for which find model root package.
229 * @return Package of model root.
231 public static String getModelRootPackageName(final String name) {
232 checkArgument(name != null, "Package name should not be null.");
233 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
234 BindingMapping.PACKAGE_PREFIX, name);
235 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
236 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
237 ROOT_PACKAGE_PATTERN_STRING);
238 return match.group(0);
243 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
246 * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
249 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
250 checkArgument(cls != null);
251 String packageName = getModelRootPackageName(cls.getPackage());
252 final String potentialClassName = getModuleInfoClassName(packageName);
253 return ClassLoaderUtils.withClassLoader(cls.getClassLoader(), new Callable<YangModuleInfo>() {
255 public YangModuleInfo call() throws ClassNotFoundException, IllegalAccessException,
256 IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
257 Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
258 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
263 public static String getModuleInfoClassName(final String packageName) {
264 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
269 * Check if supplied class is derived from YANG model.
271 * @param cls Class to check
272 * @return true if class is derived from YANG model.
274 public static boolean isBindingClass(final Class<?> cls) {
275 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
278 return (cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX));
283 * Checks if supplied method is callback for notifications.
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())) {
302 * Checks is supplied class is Notification.
304 * @param potentialNotification
307 public static boolean isNotification(final Class<?> potentialNotification) {
308 checkArgument(potentialNotification != null,"potentialNotification must not be null.");
309 return Notification.class.isAssignableFrom(potentialNotification);
314 * Loads {@link YangModuleInfo} infos available on current classloader.
316 * This method is shorthand for {@link #loadModuleInfos(ClassLoader)} with
317 * {@link Thread#getContextClassLoader()} for current thread.
319 * @return Set of {@link YangModuleInfo} available for current classloader.
321 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
322 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
327 * Loads {@link YangModuleInfo} infos available on supplied classloader.
329 * {@link YangModuleInfo} are discovered using {@link ServiceLoader}
330 * for {@link YangModelBindingProvider}. {@link YangModelBindingProvider}
331 * are simple classes which holds only pointers to actual instance
332 * {@link YangModuleInfo}.
334 * When {@link YangModuleInfo} is available, all dependencies are recursivelly collected
335 * into returning set by collecting results of {@link YangModuleInfo#getImportedModules()}.
338 * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
339 * @return Set of {@link YangModuleInfo} available for supplied classloader.
341 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
342 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.<YangModuleInfo> builder();
343 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
345 for (YangModelBindingProvider bindingProvider : serviceLoader) {
346 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
347 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
348 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
350 return moduleInfoSet.build();
353 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
354 final Builder<YangModuleInfo> moduleInfoSet) {
355 moduleInfoSet.add(moduleInfo);
356 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
357 collectYangModuleInfo(dependency, moduleInfoSet);
363 * Checks if supplied class represents RPC Input / RPC Output.
365 * @param targetType Class to be checked
366 * @return true if class represents RPC Input or RPC Output class.
368 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
369 return DataContainer.class.isAssignableFrom(targetType) //
370 && !ChildOf.class.isAssignableFrom(targetType) //
371 && !Notification.class.isAssignableFrom(targetType) //
372 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
377 * Scans supplied class and returns an iterable of all data children classes.
379 * @param type YANG Modeled Entity derived from DataContainer
380 * @return Iterable of all data children, which have YANG modeled entity
382 @SuppressWarnings("unchecked")
383 public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
384 checkArgument(type != null, "Target type must not be null");
385 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
386 List<Class<? extends DataObject>> ret = new LinkedList<>();
387 for (Method method : type.getMethods()) {
388 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
389 if (entity.isPresent()) {
390 ret.add((Class<? extends DataObject>) entity.get());
398 * Scans supplied class and returns an iterable of all data children classes.
400 * @param type YANG Modeled Entity derived from DataContainer
401 * @return Iterable of all data children, which have YANG modeled entity
403 public static Map<Class<?>,Method> getChildrenClassToMethod(final Class<?> type) {
404 checkArgument(type != null, "Target type must not be null");
405 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type 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);
409 if (entity.isPresent()) {
410 ret.put(entity.get(),method);
416 @SuppressWarnings("unchecked")
417 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
418 if (method.getName().equals("getClass") || !method.getName().startsWith("get")
419 || method.getParameterTypes().length > 0) {
420 return Optional.absent();
423 @SuppressWarnings("rawtypes")
424 Class returnType = method.getReturnType();
425 if (DataContainer.class.isAssignableFrom(returnType)) {
426 return Optional.<Class<? extends DataContainer>> of(returnType);
427 } else if (List.class.isAssignableFrom(returnType)) {
429 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
430 new Callable<Optional<Class<? extends DataContainer>>>() {
431 @SuppressWarnings("rawtypes")
433 public Optional<Class<? extends DataContainer>> call() {
434 Type listResult = ClassLoaderUtils.getFirstGenericParameter(method
435 .getGenericReturnType());
436 if (listResult instanceof Class
437 && DataContainer.class.isAssignableFrom((Class) listResult)) {
438 return Optional.<Class<? extends DataContainer>> of((Class) listResult);
440 return Optional.absent();
444 } catch (Exception e) {
447 * It is safe to log this this exception on debug, since
448 * this method should not fail. Only failures are possible if
449 * the runtime / backing.
452 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
455 return Optional.absent();
458 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
461 public Optional<QName> load(final Class<?> key) throws Exception {
462 return resolveQNameNoCache(key);
468 * Tries to resolve QName for supplied class.
470 * Looks up for static field with name from constant {@link BindingMapping#QNAME_STATIC_FIELD_NAME}
471 * and returns value if present.
473 * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types.
478 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
480 Field field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
481 Object obj = field.get(null);
482 if (obj instanceof QName) {
483 return Optional.of((QName) obj);
486 } catch (NoSuchFieldException e) {
487 return Optional.of(computeQName(key));
489 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
492 * It is safe to log this this exception on debug, since
493 * this method should not fail. Only failures are possible if
494 * the runtime / backing.
497 LOG.debug("Unexpected exception during extracting QName for {}",key,e);
499 return Optional.absent();
503 * Computes QName for supplied class
505 * Namespace and revision are same as {@link YangModuleInfo}
506 * associated with supplied class.
510 * <li>rpc input: local name is "input".
511 * <li>rpc output: local name is "output".
512 * <li>augmentation: local name is "module name".
515 * There is also fallback, if it is not possible to compute QName
516 * using following algorithm returns module QName.
518 * FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
520 * @throws IllegalStateException If YangModuleInfo could not be resolved
521 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
524 @SuppressWarnings({ "rawtypes", "unchecked" })
525 private static QName computeQName(final Class key) {
526 if(isBindingClass(key)) {
527 YangModuleInfo moduleInfo;
529 moduleInfo = getModuleInfo(key);
530 } catch (Exception e) {
531 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",e);
533 final QName module = getModuleQName(moduleInfo);
534 if (Augmentation.class.isAssignableFrom(key)) {
536 } else if(isRpcType(key)) {
537 final String className = key.getSimpleName();
538 if(className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
539 return QName.create(module,"output");
541 return QName.create(module,"input");
545 * Fallback for Binding types which fo not have QNAME
550 throw new IllegalArgumentException("Supplied class "+key+"is not derived from YANG.");
555 * Given a {@link YangModuleInfo}, create a QName representing it. The QName
556 * is formed by reusing the module's namespace and revision using the module's
557 * name as the QName's local name.
559 * @param moduleInfo module information
560 * @return QName representing the module
562 public static QName getModuleQName(final YangModuleInfo moduleInfo) {
563 checkArgument(moduleInfo != null, "moduleInfo must not be null.");
564 return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(),
565 moduleInfo.getName());
569 * Extracts augmentation from Binding DTO field using reflection
571 * @param input Instance of DataObject which is augmentable and
572 * may contain augmentation
573 * @return Map of augmentations if read was successful, otherwise
576 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
577 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
582 * Determines if two augmentation classes or case classes represents same data.
584 * Two augmentations or cases could be substituted only if and if:
586 * <li>Both implements same interfaces</li>
587 * <li>Both have same children</li>
588 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in grouping.</li>
589 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
592 * <b>Explanation:</b> Binding Specification reuses classes generated for groupings as part of normal data tree,
593 * this classes from grouping could be used at various locations and user may not be aware of it
594 * and may use incorrect case or augmentation in particular subtree (via copy constructors, etc).
596 * @param potential Class which is potential substition
597 * @param target Class which should be used at particular subtree
598 * @return true if and only if classes represents same data.
600 @SuppressWarnings({"rawtypes","unchecked"})
601 public static boolean isSubstitutionFor(final Class potential, final Class target) {
602 HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
603 HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
604 if(!subImplemented.equals(targetImplemented)) {
607 if(Augmentation.class.isAssignableFrom(potential)
608 && !BindingReflections.findAugmentationTarget(potential).equals(BindingReflections.findAugmentationTarget(target))) {
611 for(Method potentialMethod : potential.getMethods()) {
613 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
614 if(!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
617 } catch (NoSuchMethodException e) {
618 // Counterpart method is missing, so classes could not be substituted.
620 } catch (SecurityException e) {
621 throw new IllegalStateException("Could not compare methods",e);