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.Method;
21 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.opendaylight.yangtools.yang.common.QNameModule;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 public class BindingReflections {
53 private static final long EXPIRATION_TIME = 60;
54 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])";
55 private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
56 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
58 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder() //
60 .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS) //
61 .build(new ClassToQNameLoader());
63 private BindingReflections() {
64 throw new UnsupportedOperationException("Utility class.");
68 * Find augmentation target class from concrete Augmentation class
70 * This method uses first generic argument of implemented
71 * {@link Augmentation} interface.
74 * {@link Augmentation} subclass for which we want to determine
75 * augmentation target.
76 * @return Augmentation target - class which augmentation provides
77 * additional extensions.
79 public static Class<? extends Augmentable<?>> findAugmentationTarget(
80 final Class<? extends Augmentation<?>> augmentation) {
81 return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class);
85 * Find data hierarchy parent from concrete Data class
87 * This method uses first generic argument of implemented {@link ChildOf}
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
101 * This method is shorthand which gets DataObject class by invoking
102 * {@link DataObject#getImplementedInterface()} and uses
103 * {@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 CLASS_TO_QNAME.getUnchecked(dataType).orNull();
132 * Checks if method is RPC invocation
134 * @param possibleMethod
136 * @return true if method is RPC invocation, false otherwise.
138 public static boolean isRpcMethod(final Method possibleMethod) {
139 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
140 && Future.class.isAssignableFrom(possibleMethod.getReturnType())
141 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
142 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
143 // non input type and two arguments for input type, resolveRpcInputClass() counting
144 // with zero for non input and one for input type
145 && possibleMethod.getParameterTypes().length <= 2;
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 a 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.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("rawtypes")
178 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
179 for (Class clazz : targetMethod.getParameterTypes()) {
180 if (DataContainer.class.isAssignableFrom(clazz)) {
181 return Optional.of(clazz);
184 return Optional.absent();
187 public static QName getQName(final Class<? extends BaseIdentity> context) {
188 return findQName(context);
193 * Checks if class is child of augmentation.
199 public static boolean isAugmentationChild(final Class<?> clazz) {
200 // FIXME: Current resolver could be still confused when
201 // child node was added by grouping
202 checkArgument(clazz != null);
204 @SuppressWarnings({ "rawtypes", "unchecked" })
205 Class<?> parent = findHierarchicalParent((Class) clazz);
206 if (parent == null) {
207 LOG.debug("Did not find a parent for class {}", clazz);
211 String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
212 String parentModelPackage = getModelRootPackageName(parent.getPackage());
214 return !clazzModelPackage.equals(parentModelPackage);
218 * Returns root package name for suplied package.
221 * Package for which find model root package.
222 * @return Package of model root.
224 public static String getModelRootPackageName(final Package pkg) {
225 return getModelRootPackageName(pkg.getName());
229 * Returns root package name for supplied package name.
232 * Package for which find model root package.
233 * @return Package of model root.
235 public static String getModelRootPackageName(final String name) {
236 checkArgument(name != null, "Package name should not be null.");
237 checkArgument(name.startsWith(BindingMapping.PACKAGE_PREFIX), "Package name not starting with %s, is: %s",
238 BindingMapping.PACKAGE_PREFIX, name);
239 Matcher match = ROOT_PACKAGE_PATTERN.matcher(name);
240 checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name,
241 ROOT_PACKAGE_PATTERN_STRING);
242 return match.group(0);
245 public static final QNameModule getQNameModule(final Class<?> clz) {
246 if(DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)) {
247 return findQName(clz).getModule();
250 YangModuleInfo modInfo = BindingReflections.getModuleInfo(clz);
251 return getQNameModule(modInfo);
252 } catch (Exception e) {
253 throw new IllegalStateException("Unable to get QName of defining model.", e);
257 public static final QNameModule getQNameModule(final YangModuleInfo modInfo) {
258 return QNameModule.create(URI.create(modInfo.getNamespace()), QName.parseRevision(modInfo.getRevision()));
263 * Returns instance of {@link YangModuleInfo} of declaring model for
267 * @return Instance of {@link YangModuleInfo} associated with model, from
268 * which this class was derived.
271 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
272 checkArgument(cls != null);
273 String packageName = getModelRootPackageName(cls.getPackage());
274 final String potentialClassName = getModuleInfoClassName(packageName);
275 return ClassLoaderUtils.withClassLoader(cls.getClassLoader(), (Callable<YangModuleInfo>) () -> {
276 Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
277 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
281 public static String getModuleInfoClassName(final String packageName) {
282 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
287 * Check if supplied class is derived from YANG model.
291 * @return true if class is derived from YANG model.
293 public static boolean isBindingClass(final Class<?> cls) {
294 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
297 return cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX);
302 * Checks if supplied method is callback for notifications.
305 * @return true if method is notification callback.
307 public static boolean isNotificationCallback(final Method method) {
308 checkArgument(method != null);
309 if (method.getName().startsWith("on") && method.getParameterTypes().length == 1) {
310 Class<?> potentialNotification = method.getParameterTypes()[0];
311 if (isNotification(potentialNotification)
312 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
321 * Checks is supplied class is Notification.
323 * @param potentialNotification
326 public static boolean isNotification(final Class<?> potentialNotification) {
327 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
328 return Notification.class.isAssignableFrom(potentialNotification);
333 * Loads {@link YangModuleInfo} infos available on current classloader.
335 * This method is shorthand for {@link #loadModuleInfos(ClassLoader)} with
336 * {@link Thread#getContextClassLoader()} for current thread.
338 * @return Set of {@link YangModuleInfo} available for current classloader.
340 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
341 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
346 * Loads {@link YangModuleInfo} infos available on supplied classloader.
348 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for
349 * {@link YangModelBindingProvider}. {@link YangModelBindingProvider} are
350 * simple classes which holds only pointers to actual instance
351 * {@link YangModuleInfo}.
353 * When {@link YangModuleInfo} is available, all dependencies are
354 * recursivelly collected into returning set by collecting results of
355 * {@link YangModuleInfo#getImportedModules()}.
359 * Classloader for which {@link YangModuleInfo} should be
361 * @return Set of {@link YangModuleInfo} available for supplied classloader.
363 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
364 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
365 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
367 for (YangModelBindingProvider bindingProvider : serviceLoader) {
368 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
369 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
370 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
372 return moduleInfoSet.build();
375 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
376 final Builder<YangModuleInfo> moduleInfoSet) {
377 moduleInfoSet.add(moduleInfo);
378 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
379 collectYangModuleInfo(dependency, moduleInfoSet);
385 * Checks if supplied class represents RPC Input / RPC Output.
388 * Class to be checked
389 * @return true if class represents RPC Input or RPC Output class.
391 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
392 return DataContainer.class.isAssignableFrom(targetType) //
393 && !ChildOf.class.isAssignableFrom(targetType) //
394 && !Notification.class.isAssignableFrom(targetType) //
395 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
400 * Scans supplied class and returns an iterable of all data children
404 * YANG Modeled Entity derived from DataContainer
405 * @return Iterable of all data children, which have YANG modeled entity
407 @SuppressWarnings("unchecked")
408 public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
409 checkArgument(type != null, "Target type must not be null");
410 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
411 List<Class<? extends DataObject>> ret = new LinkedList<>();
412 for (Method method : type.getMethods()) {
413 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
414 if (entity.isPresent()) {
415 ret.add((Class<? extends DataObject>) entity.get());
423 * Scans supplied class and returns an iterable of all data children
427 * YANG Modeled Entity derived from DataContainer
428 * @return Iterable of all data children, which have YANG modeled entity
430 public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
431 checkArgument(type != null, "Target type must not be null");
432 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
433 Map<Class<?>, Method> ret = new HashMap<>();
434 for (Method method : type.getMethods()) {
435 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
436 if (entity.isPresent()) {
437 ret.put(entity.get(), method);
443 @SuppressWarnings({ "unchecked", "rawtypes" })
444 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
445 if ("getClass".equals(method.getName()) || !method.getName().startsWith("get")
446 || method.getParameterTypes().length > 0) {
447 return Optional.absent();
450 @SuppressWarnings("rawtypes")
451 Class returnType = method.getReturnType();
452 if (DataContainer.class.isAssignableFrom(returnType)) {
453 return Optional.of(returnType);
454 } else if (List.class.isAssignableFrom(returnType)) {
456 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
457 (Callable<Optional<Class<? extends DataContainer>>>) () -> {
458 Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
459 if (listResult instanceof Class
460 && DataContainer.class.isAssignableFrom((Class) listResult)) {
461 return Optional.of((Class) listResult);
463 return Optional.absent();
465 } catch (Exception e) {
468 * It is safe to log this this exception on debug, since this
469 * method should not fail. Only failures are possible if the
472 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
475 return Optional.absent();
478 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
481 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
482 return resolveQNameNoCache(key);
487 * Tries to resolve QName for supplied class.
489 * Looks up for static field with name from constant {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns
492 * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types.
497 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
499 Field field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
500 Object obj = field.get(null);
501 if (obj instanceof QName) {
502 return Optional.of((QName) obj);
505 } catch (NoSuchFieldException e) {
506 return Optional.of(computeQName(key));
508 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
511 * It is safe to log this this exception on debug, since this method
512 * should not fail. Only failures are possible if the runtime /
515 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
517 return Optional.absent();
521 * Computes QName for supplied class
523 * Namespace and revision are same as {@link YangModuleInfo} associated with supplied class.
527 * <li>rpc input: local name is "input".
528 * <li>rpc output: local name is "output".
529 * <li>augmentation: local name is "module name".
532 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
535 * FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
537 * @throws IllegalStateException If YangModuleInfo could not be resolved
538 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
541 @SuppressWarnings({ "rawtypes", "unchecked" })
542 private static QName computeQName(final Class key) {
543 if (isBindingClass(key)) {
544 YangModuleInfo moduleInfo;
546 moduleInfo = getModuleInfo(key);
547 } catch (Exception e) {
548 throw new IllegalStateException("Unable to get QName for " + key
549 + ". YangModuleInfo was not found.", e);
551 final QName module = getModuleQName(moduleInfo).intern();
552 if (Augmentation.class.isAssignableFrom(key)) {
554 } else if (isRpcType(key)) {
555 final String className = key.getSimpleName();
556 if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
557 return QName.create(module, "output").intern();
559 return QName.create(module, "input").intern();
563 * Fallback for Binding types which do not have QNAME field
567 throw new IllegalArgumentException("Supplied class " + key + "is not derived from YANG.");
574 * Given a {@link YangModuleInfo}, create a QName representing it. The QName
575 * is formed by reusing the module's namespace and revision using the
576 * module's name as the QName's local name.
580 * @return QName representing the module
582 public static QName getModuleQName(final YangModuleInfo moduleInfo) {
583 checkArgument(moduleInfo != null, "moduleInfo must not be null.");
584 return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(), moduleInfo.getName());
588 * Extracts augmentation from Binding DTO field using reflection
591 * Instance of DataObject which is augmentable and may contain
593 * @return Map of augmentations if read was successful, otherwise empty map.
595 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
596 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
601 * Determines if two augmentation classes or case classes represents same
604 * Two augmentations or cases could be substituted only if and if:
606 * <li>Both implements same interfaces</li>
607 * <li>Both have same children</li>
608 * <li>If augmentations: Both have same augmentation target class. Target
609 * class was generated for data node in grouping.</li>
610 * <li>If cases: Both are from same choice. Choice class was generated for
611 * data node in grouping.</li>
614 * <b>Explanation:</b> Binding Specification reuses classes generated for
615 * groupings as part of normal data tree, this classes from grouping could
616 * be used at various locations and user may not be aware of it and may use
617 * incorrect case or augmentation in particular subtree (via copy
618 * constructors, etc).
621 * Class which is potential substition
623 * Class which should be used at particular subtree
624 * @return true if and only if classes represents same data.
626 @SuppressWarnings({ "rawtypes", "unchecked" })
627 public static boolean isSubstitutionFor(final Class potential, final Class target) {
628 HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
629 HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
630 if (!subImplemented.equals(targetImplemented)) {
633 if (Augmentation.class.isAssignableFrom(potential)
634 && !BindingReflections.findAugmentationTarget(potential).equals(
635 BindingReflections.findAugmentationTarget(target))) {
638 for (Method potentialMethod : potential.getMethods()) {
640 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
641 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
644 } catch (NoSuchMethodException e) {
645 // Counterpart method is missing, so classes could not be
648 } catch (SecurityException e) {
649 throw new IllegalStateException("Could not compare methods", e);