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 * {@link Augmentation} subclass for which we want to determine
93 * augmentation target.
94 * @return Augmentation target - class which augmentation provides
95 * additional extensions.
97 public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
98 return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class);
102 * Find data hierarchy parent from concrete Data class
104 * This method is shorthand which gets DataObject class by invoking
105 * {@link DataObject#getImplementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
108 * {@link Augmentation} subclass for which we want to determine
109 * augmentation target.
110 * @return Augmentation target - class which augmentation provides
111 * additional extensions.
113 public static Class<?> findHierarchicalParent(final DataObject child) {
114 if (child instanceof ChildOf) {
115 return ClassLoaderUtils.findFirstGenericArgument(child.getImplementedInterface(), ChildOf.class);
121 * Returns a QName associated to supplied type
124 * @return QName associated to supplied dataType. If dataType is
125 * Augmentation method does not return canonical QName, but QName
126 * with correct namespace revision, but virtual local name, since
127 * augmentations do not have name.
129 * May return null if QName is not present.
131 public static final QName findQName(final Class<?> dataType) {
132 return classToQName.getUnchecked(dataType).orNull();
136 * Checks if method is RPC invocation
140 * @param possibleMethod Method to check
141 * @return true if method is RPC invocation, false otherwise.
143 public static boolean isRpcMethod(final Method possibleMethod) {
144 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
145 && Future.class.isAssignableFrom(possibleMethod.getReturnType())
146 && possibleMethod.getParameterTypes().length <= 1;
151 * Extracts Output class for RPC method
153 * @param targetMethod method to scan
154 * @return Optional.absent() if result type could not be get,
155 * or return type is Void.
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 method to scan
174 * @return Optional.absent() if rpc has no input, Rpc input type otherwise.
176 @SuppressWarnings("unchecked")
177 public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
178 @SuppressWarnings("rawtypes")
179 Class[] types = targetMethod.getParameterTypes();
180 if (types.length == 0) {
181 return Optional.absent();
183 if (types.length == 1) {
184 return Optional.<Class<? extends DataContainer>> of(types[0]);
186 throw new IllegalArgumentException("Method has 2 or more arguments.");
189 public static QName getQName(final Class<? extends BaseIdentity> context) {
190 return findQName(context);
195 * Checks if class is child of augmentation.
201 public static boolean isAugmentationChild(final Class<?> clazz) {
202 // FIXME: Current resolver could be still confused when
203 // child node was added by grouping
204 checkArgument(clazz != null);
206 @SuppressWarnings({ "rawtypes", "unchecked" })
207 Class<?> parent = findHierarchicalParent((Class) clazz);
208 if (parent == null) {
209 LOG.debug("Did not find a parent for class {}", clazz);
213 String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
214 String parentModelPackage = getModelRootPackageName(parent.getPackage());
216 return !clazzModelPackage.equals(parentModelPackage);
220 * Returns root package name for suplied package.
222 * @param pkg Package for which find model root package.
223 * @return Package of model root.
225 public static String getModelRootPackageName(final Package pkg) {
226 return getModelRootPackageName(pkg.getName());
230 * Returns root package name for supplied package name.
232 * @param pkg 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);
247 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
250 * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
253 public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
254 checkArgument(cls != null);
255 String packageName = getModelRootPackageName(cls.getPackage());
256 final String potentialClassName = getModuleInfoClassName(packageName);
257 return ClassLoaderUtils.withClassLoader(cls.getClassLoader(), new Callable<YangModuleInfo>() {
259 public YangModuleInfo call() throws ClassNotFoundException, IllegalAccessException,
260 IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
261 Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
262 return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
267 public static String getModuleInfoClassName(final String packageName) {
268 return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
273 * Check if supplied class is derived from YANG model.
275 * @param cls Class to check
276 * @return true if class is derived from YANG model.
278 public static boolean isBindingClass(final Class<?> cls) {
279 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
282 return (cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX));
287 * Checks if supplied method is callback for notifications.
290 * @return true if method is notification callback.
292 public static boolean isNotificationCallback(final Method method) {
293 checkArgument(method != null);
294 if (method.getName().startsWith("on") && method.getParameterTypes().length == 1) {
295 Class<?> potentialNotification = method.getParameterTypes()[0];
296 if (isNotification(potentialNotification)
297 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
306 * Checks is supplied class is Notification.
308 * @param potentialNotification
311 public static boolean isNotification(final Class<?> potentialNotification) {
312 checkArgument(potentialNotification != null,"potentialNotification must not be null.");
313 return Notification.class.isAssignableFrom(potentialNotification);
318 * Loads {@link YangModuleInfo} infos available on current classloader.
320 * This method is shorthand for {@link #loadModuleInfos(ClassLoader)} with
321 * {@link Thread#getContextClassLoader()} for current thread.
323 * @return Set of {@link YangModuleInfo} available for current classloader.
325 public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
326 return loadModuleInfos(Thread.currentThread().getContextClassLoader());
331 * Loads {@link YangModuleInfo} infos available on supplied classloader.
333 * {@link YangModuleInfo} are discovered using {@link ServiceLoader}
334 * for {@link YangModelBindingProvider}. {@link YangModelBindingProvider}
335 * are simple classes which holds only pointers to actual instance
336 * {@link YangModuleInfo}.
338 * When {@link YangModuleInfo} is available, all dependencies are recursivelly collected
339 * into returning set by collecting results of {@link YangModuleInfo#getImportedModules()}.
342 * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
343 * @return Set of {@link YangModuleInfo} available for supplied classloader.
345 public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
346 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.<YangModuleInfo> builder();
347 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
349 for (YangModelBindingProvider bindingProvider : serviceLoader) {
350 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
351 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
352 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
354 return moduleInfoSet.build();
357 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
358 final Builder<YangModuleInfo> moduleInfoSet) {
359 moduleInfoSet.add(moduleInfo);
360 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
361 collectYangModuleInfo(dependency, moduleInfoSet);
367 * Checks if supplied class represents RPC Input / RPC Output.
369 * @param targetType Class to be checked
370 * @return true if class represents RPC Input or RPC Output class.
372 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
373 return DataContainer.class.isAssignableFrom(targetType) //
374 && !ChildOf.class.isAssignableFrom(targetType) //
375 && !Notification.class.isAssignableFrom(targetType) //
376 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
381 * Scans supplied class and returns an iterable of all data children classes.
383 * @param type YANG Modeled Entity derived from DataContainer
384 * @return Iterable of all data children, which have YANG modeled entity
386 @SuppressWarnings("unchecked")
387 public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
388 checkArgument(type != null, "Target type must not be null");
389 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
390 List<Class<? extends DataObject>> ret = new LinkedList<>();
391 for (Method method : type.getMethods()) {
392 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
393 if (entity.isPresent()) {
394 ret.add((Class<? extends DataObject>) entity.get());
402 * Scans supplied class and returns an iterable of all data children classes.
404 * @param type YANG Modeled Entity derived from DataContainer
405 * @return Iterable of all data children, which have YANG modeled entity
407 public static Map<Class<?>,Method> getChildrenClassToMethod(final Class<?> type) {
408 checkArgument(type != null, "Target type must not be null");
409 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
410 Map<Class<?>,Method> ret = new HashMap<>();
411 for (Method method : type.getMethods()) {
412 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
413 if (entity.isPresent()) {
414 ret.put(entity.get(),method);
420 @SuppressWarnings("unchecked")
421 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
422 if (method.getName().equals("getClass") || !method.getName().startsWith("get")
423 || method.getParameterTypes().length > 0) {
424 return Optional.absent();
427 @SuppressWarnings("rawtypes")
428 Class returnType = method.getReturnType();
429 if (DataContainer.class.isAssignableFrom(returnType)) {
430 return Optional.<Class<? extends DataContainer>> of(returnType);
431 } else if (List.class.isAssignableFrom(returnType)) {
433 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
434 new Callable<Optional<Class<? extends DataContainer>>>() {
435 @SuppressWarnings("rawtypes")
437 public Optional<Class<? extends DataContainer>> call() {
438 Type listResult = ClassLoaderUtils.getFirstGenericParameter(method
439 .getGenericReturnType());
440 if (listResult instanceof Class
441 && DataContainer.class.isAssignableFrom((Class) listResult)) {
442 return Optional.<Class<? extends DataContainer>> of((Class) listResult);
444 return Optional.absent();
448 } catch (Exception e) {
451 * It is safe to log this this exception on debug, since
452 * this method should not fail. Only failures are possible if
453 * the runtime / backing.
456 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
459 return Optional.absent();
462 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
465 public Optional<QName> load(final Class<?> key) throws Exception {
466 return resolveQNameNoCache(key);
472 * Tries to resolve QName for supplied class.
474 * Looks up for static field with name from constant {@link BindingMapping#QNAME_STATIC_FIELD_NAME}
475 * and returns value if present.
477 * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types.
482 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
484 Field field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
485 Object obj = field.get(null);
486 if (obj instanceof QName) {
487 return Optional.of((QName) obj);
490 } catch (NoSuchFieldException e) {
491 return Optional.of(computeQName(key));
493 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
496 * It is safe to log this this exception on debug, since
497 * this method should not fail. Only failures are possible if
498 * the runtime / backing.
501 LOG.debug("Unexpected exception during extracting QName for {}",key,e);
503 return Optional.absent();
507 * Computes QName for supplied class
509 * Namespace and revision are same as {@link YangModuleInfo}
510 * associated with supplied class.
514 * <li>rpc input: local name is "input".
515 * <li>rpc output: local name is "output".
516 * <li>augmentation: local name is "module name".
519 * There is also fallback, if it is not possible to compute QName
520 * using following algorithm returns module QName.
522 * FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
524 * @throws IllegalStateException If YangModuleInfo could not be resolved
525 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
528 @SuppressWarnings({ "rawtypes", "unchecked" })
529 private static QName computeQName(final Class key) {
530 if(isBindingClass(key)) {
531 YangModuleInfo moduleInfo;
533 moduleInfo = getModuleInfo(key);
534 } catch (Exception e) {
535 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",e);
537 final QName module = getModuleQName(moduleInfo);
538 if (Augmentation.class.isAssignableFrom(key)) {
540 } else if(isRpcType(key)) {
541 final String className = key.getSimpleName();
542 if(className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
543 return QName.create(module,"output");
545 return QName.create(module,"input");
549 * Fallback for Binding types which fo not have QNAME
554 throw new IllegalArgumentException("Supplied class "+key+"is not derived from YANG.");
559 * Given a {@link YangModuleInfo}, create a QName representing it. The QName
560 * is formed by reusing the module's namespace and revision using the module's
561 * name as the QName's local name.
563 * @param moduleInfo module information
564 * @return QName representing the module
566 public static QName getModuleQName(final YangModuleInfo moduleInfo) {
567 checkArgument(moduleInfo != null, "moduleInfo must not be null.");
568 return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(),
569 moduleInfo.getName());
573 * Extracts augmentation from Binding DTO field using reflection
575 * @param input Instance of DataObject which is augmentable and
576 * may contain augmentation
577 * @return Map of augmentations if read was successful, otherwise
580 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
581 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
586 * Determines if two augmentation classes or case classes represents same data.
588 * Two augmentations or cases could be substituted only if and if:
590 * <li>Both implements same interfaces</li>
591 * <li>Both have same children</li>
592 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in grouping.</li>
593 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
596 * <b>Explanation:</b> Binding Specification reuses classes generated for groupings as part of normal data tree,
597 * this classes from grouping could be used at various locations and user may not be aware of it
598 * and may use incorrect case or augmentation in particular subtree (via copy constructors, etc).
600 * @param potential Class which is potential substition
601 * @param target Class which should be used at particular subtree
602 * @return true if and only if classes represents same data.
604 @SuppressWarnings({"rawtypes","unchecked"})
605 public static boolean isSubstitutionFor(final Class potential, final Class target) {
606 HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
607 HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
608 if(!subImplemented.equals(targetImplemented)) {
611 if(Augmentation.class.isAssignableFrom(potential)
612 && !BindingReflections.findAugmentationTarget(potential).equals(BindingReflections.findAugmentationTarget(target))) {
615 for(Method potentialMethod : potential.getMethods()) {
617 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
618 if(!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
621 } catch (NoSuchMethodException e) {
622 // Counterpart method is missing, so classes could not be substituted.
624 } catch (SecurityException e) {
625 throw new IllegalStateException("Could not compare methods",e);