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;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.lang.reflect.Type;
24 import java.util.HashMap;
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;
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 suplied 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 @SuppressWarnings("unchecked")
408 public static Map<Class<?>,Method> getChildrenClassToMethod(final Class<?> 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 Map<Class<?>,Method> ret = new HashMap<>();
412 for (Method method : type.getMethods()) {
413 Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
414 if (entity.isPresent()) {
415 ret.put(entity.get(),method);
421 @SuppressWarnings("unchecked")
422 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
423 if (method.getName().equals("getClass") || !method.getName().startsWith("get")
424 || method.getParameterTypes().length > 0) {
425 return Optional.absent();
428 @SuppressWarnings("rawtypes")
429 Class returnType = method.getReturnType();
430 if (DataContainer.class.isAssignableFrom(returnType)) {
431 return Optional.<Class<? extends DataContainer>> of(returnType);
432 } else if (List.class.isAssignableFrom(returnType)) {
434 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
435 new Callable<Optional<Class<? extends DataContainer>>>() {
436 @SuppressWarnings("rawtypes")
438 public Optional<Class<? extends DataContainer>> call() {
439 Type listResult = ClassLoaderUtils.getFirstGenericParameter(method
440 .getGenericReturnType());
441 if (listResult instanceof Class
442 && DataContainer.class.isAssignableFrom((Class) listResult)) {
443 return Optional.<Class<? extends DataContainer>> of((Class) listResult);
445 return Optional.absent();
449 } catch (Exception e) {
452 * It is safe to log this this exception on debug, since
453 * this method should not fail. Only failures are possible if
454 * the runtime / backing.
457 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
460 return Optional.absent();
463 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
466 public Optional<QName> load(final Class<?> key) throws Exception {
467 return resolveQNameNoCache(key);
473 * Tries to resolve QName for supplied class.
475 * Looks up for static field with name from constant {@link BindingMapping#QNAME_STATIC_FIELD_NAME}
476 * and returns value if present.
478 * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types.
483 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
485 Field field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
486 Object obj = field.get(null);
487 if (obj instanceof QName) {
488 return Optional.of((QName) obj);
491 } catch (NoSuchFieldException e) {
492 return Optional.of(computeQName(key));
494 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
497 * It is safe to log this this exception on debug, since
498 * this method should not fail. Only failures are possible if
499 * the runtime / backing.
502 LOG.debug("Unexpected exception during extracting QName for {}",key,e);
504 return Optional.absent();
508 * Computes QName for supplied class
510 * Namespace and revision are same as {@link YangModuleInfo}
511 * associated with supplied class.
515 * <li>rpc input: local name is "input".
516 * <li>rpc output: local name is "output".
517 * <li>augmentation: local name is "module name".
520 * There is also fallback, if it is not possible to compute QName
521 * using following algorithm returns module QName.
523 * FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
525 * @throws IllegalStateException If YangModuleInfo could not be resolved
526 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
529 @SuppressWarnings({ "rawtypes", "unchecked" })
530 private static QName computeQName(final Class key) {
531 if(isBindingClass(key)) {
532 YangModuleInfo moduleInfo;
534 moduleInfo = getModuleInfo(key);
535 } catch (Exception e) {
536 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",e);
538 final QName module = getModuleQName(moduleInfo);
539 if (Augmentation.class.isAssignableFrom(key)) {
541 } else if(isRpcType(key)) {
542 final String className = key.getSimpleName();
543 if(className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
544 return QName.create(module,"output");
546 return QName.create(module,"input");
550 * Fallback for Binding types which fo not have QNAME
555 throw new IllegalArgumentException("Supplied class "+key+"is not derived from YANG.");
560 * Given a {@link YangModuleInfo}, create a QName representing it. The QName
561 * is formed by reusing the module's namespace and revision using the module's
562 * name as the QName's local name.
564 * @param moduleInfo module information
565 * @return QName representing the module
567 public static QName getModuleQName(final YangModuleInfo moduleInfo) {
568 checkArgument(moduleInfo != null, "moduleInfo must not be null.");
569 return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(),
570 moduleInfo.getName());
574 * Extracts augmentation from Binding DTO field using reflection
576 * @param input Instance of DataObject which is augmentable and
577 * may contain augmentation
578 * @return Map of augmentations if read was successful, otherwise
581 public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
582 return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);