Added tests for yang.model.util
[yangtools.git] / yang / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / util / BindingReflections.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.binding.util;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12
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
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;
27 import java.util.Map;
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
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;
49
50 public class BindingReflections {
51
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);
56
57     private static final LoadingCache<Class<?>, Optional<QName>> classToQName = CacheBuilder.newBuilder() //
58             .weakKeys() //
59             .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS) //
60             .build(new ClassToQNameLoader());
61
62
63
64     private BindingReflections() {
65         throw new UnsupportedOperationException("Utility class.");
66     }
67
68     /**
69      * Find augmentation target class from concrete Augmentation class
70      *
71      * This method uses first generic argument of
72      * implemented {@link Augmentation} interface.
73      *
74      * @param augmentation
75      *            {@link Augmentation} subclass for which we want to determine
76      *            augmentation target.
77      * @return Augmentation target - class which augmentation provides
78      *         additional extensions.
79      */
80     public static Class<? extends Augmentable<?>> findAugmentationTarget(
81             final Class<? extends Augmentation<?>> augmentation) {
82         return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class);
83     }
84
85     /**
86      * Find data hierarchy parent from concrete Data class
87      *
88      * This method uses first generic argument of
89      * implemented {@link ChildOf} interface.
90      *
91      * @param augmentation
92      *            {@link Augmentation} subclass for which we want to determine
93      *            augmentation target.
94      * @return Augmentation target - class which augmentation provides
95      *         additional extensions.
96      */
97     public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
98         return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class);
99     }
100
101     /**
102      * Find data hierarchy parent from concrete Data class
103      *
104      * This method is shorthand which gets DataObject class by invoking
105      * {@link DataObject#getImplementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
106      *
107      * @param childClass
108      *            {@link Augmentation} subclass for which we want to determine
109      *            augmentation target.
110      * @return Augmentation target - class which augmentation provides
111      *         additional extensions.
112      */
113     public static Class<?> findHierarchicalParent(final DataObject child) {
114         if (child instanceof ChildOf) {
115             return ClassLoaderUtils.findFirstGenericArgument(child.getImplementedInterface(), ChildOf.class);
116         }
117         return null;
118     }
119
120     /**
121      * Returns a QName associated to supplied type
122      *
123      * @param dataType
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.
128      *
129      *         May return null if QName is not present.
130      */
131     public static final QName findQName(final Class<?> dataType) {
132         return classToQName.getUnchecked(dataType).orNull();
133     }
134
135     /**
136      * Checks if method is RPC invocation
137      *
138      *
139      *
140      * @param possibleMethod Method to check
141      * @return true if method is RPC invocation, false otherwise.
142      */
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;
147     }
148
149     /**
150      *
151      * Extracts Output class for RPC method
152      *
153      * @param targetMethod method to scan
154      * @return Optional.absent() if result type could not be get,
155      *         or return type is Void.
156      */
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);
165         }
166         return Optional.absent();
167     }
168
169     /**
170      *
171      * Extracts input class for RPC method
172      *
173      * @param targetMethod method to scan
174      * @return Optional.absent() if rpc has no input, Rpc input type otherwise.
175      */
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();
182         }
183         if (types.length == 1) {
184             return Optional.<Class<? extends DataContainer>> of(types[0]);
185         }
186         throw new IllegalArgumentException("Method has 2 or more arguments.");
187     }
188
189     public static QName getQName(final Class<? extends BaseIdentity> context) {
190         return findQName(context);
191     }
192
193     /**
194      *
195      * Checks if class is child of augmentation.
196      *
197      *
198      * @param clazz
199      * @return
200      */
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);
205
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);
210             return false;
211         }
212
213         String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
214         String parentModelPackage = getModelRootPackageName(parent.getPackage());
215
216         return !clazzModelPackage.equals(parentModelPackage);
217     }
218
219     /**
220      * Returns root package name for suplied package.
221      *
222      * @param pkg Package for which find model root package.
223      * @return Package of model root.
224      */
225     public static String getModelRootPackageName(final Package pkg) {
226         return getModelRootPackageName(pkg.getName());
227     }
228
229     /**
230      * Returns root package name for suplied package name.
231      *
232      * @param pkg Package for which find model root package.
233      * @return Package of model root.
234      */
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);
243     }
244
245     /**
246      *
247      * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
248      *
249      * @param cls
250      * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
251      * @throws Exception
252      */
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>() {
258             @Override
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);
263             }
264         });
265     }
266
267     public static String getModuleInfoClassName(final String packageName) {
268         return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
269     }
270
271     /**
272      *
273      * Check if supplied class is derived from YANG model.
274      *
275      * @param cls Class to check
276      * @return true if class is derived from YANG model.
277      */
278     public static boolean isBindingClass(final Class<?> cls) {
279         if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
280             return true;
281         }
282         return (cls.getName().startsWith(BindingMapping.PACKAGE_PREFIX));
283     }
284
285     /**
286      *
287      * Checks if supplied method is callback for notifications.
288      *
289      * @param method
290      * @return true if method is notification callback.
291      */
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())) {
298                 return true;
299             }
300         }
301         return false;
302     }
303
304     /**
305      *
306      * Checks is supplied class is Notification.
307      *
308      * @param potentialNotification
309      * @return
310      */
311     public static boolean isNotification(final Class<?> potentialNotification) {
312         checkArgument(potentialNotification != null,"potentialNotification must not be null.");
313         return Notification.class.isAssignableFrom(potentialNotification);
314     }
315
316     /**
317      *
318      * Loads {@link YangModuleInfo} infos available on current classloader.
319      *
320      * This method is shorthand for {@link #loadModuleInfos(ClassLoader)} with
321      * {@link Thread#getContextClassLoader()} for current thread.
322      *
323      * @return Set of {@link YangModuleInfo} available for current classloader.
324      */
325     public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
326         return loadModuleInfos(Thread.currentThread().getContextClassLoader());
327     }
328
329     /**
330     *
331     * Loads {@link YangModuleInfo} infos available on supplied classloader.
332     *
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}.
337     *
338     * When {@link YangModuleInfo} is available, all dependencies are recursivelly collected
339     * into returning set by collecting results of {@link YangModuleInfo#getImportedModules()}.
340     *
341     *
342     * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
343     * @return Set of {@link YangModuleInfo} available for supplied classloader.
344     */
345     public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
346         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.<YangModuleInfo> builder();
347         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
348                 loader);
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);
353         }
354         return moduleInfoSet.build();
355     }
356
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);
362         }
363     }
364
365     /**
366      *
367      * Checks if supplied class represents RPC Input / RPC Output.
368      *
369      * @param targetType Class to be checked
370      * @return true if class represents RPC Input or RPC Output class.
371      */
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"));
377     }
378
379     /**
380      *
381      * Scans supplied class and returns an iterable of all data children classes.
382      *
383      * @param type YANG Modeled Entity derived from DataContainer
384      * @return Iterable of all data children, which have YANG modeled entity
385      */
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());
395             }
396         }
397         return ret;
398     }
399
400     /**
401     *
402     * Scans supplied class and returns an iterable of all data children classes.
403     *
404     * @param type YANG Modeled Entity derived from DataContainer
405     * @return Iterable of all data children, which have YANG modeled entity
406     */
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);
416            }
417        }
418        return ret;
419    }
420
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();
426         }
427
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)) {
433             try {
434                 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
435                         new Callable<Optional<Class<? extends DataContainer>>>() {
436                             @SuppressWarnings("rawtypes")
437                             @Override
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);
444                                 }
445                                 return Optional.absent();
446                             }
447
448                         });
449             } catch (Exception e) {
450                 /*
451                  *
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.
455                  *
456                  */
457                 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
458             }
459         }
460         return Optional.absent();
461     }
462
463     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
464
465         @Override
466         public Optional<QName> load(final Class<?> key) throws Exception {
467             return resolveQNameNoCache(key);
468         }
469     }
470
471     /**
472      *
473      * Tries to resolve QName for supplied class.
474      *
475      * Looks up for static field with name from constant {@link BindingMapping#QNAME_STATIC_FIELD_NAME}
476      * and returns value if present.
477      *
478      * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types.
479      *
480      * @param key
481      * @return
482      */
483     private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
484         try {
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);
489             }
490
491         } catch (NoSuchFieldException e) {
492             return Optional.of(computeQName(key));
493
494         } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
495             /*
496              *
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.
500              *
501              */
502             LOG.debug("Unexpected exception during extracting QName for {}",key,e);
503         }
504         return Optional.absent();
505     }
506
507     /**
508      * Computes QName for supplied class
509      *
510      * Namespace and revision are same as {@link YangModuleInfo}
511      * associated with supplied class.
512      * <p>
513      * If class is
514      * <ul>
515      *  <li>rpc input: local name is "input".
516      *  <li>rpc output: local name is "output".
517      *  <li>augmentation: local name is "module name".
518      * </ul>
519      *
520      * There is also fallback, if it is not possible to compute QName
521      * using following algorithm returns module QName.
522      *
523      * FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
524      *
525      * @throws IllegalStateException If YangModuleInfo could not be resolved
526      * @throws IllegalArgumentException If supplied class was not derived from YANG model.
527      *
528      */
529     @SuppressWarnings({ "rawtypes", "unchecked" })
530     private static QName computeQName(final Class key) {
531         if(isBindingClass(key)) {
532             YangModuleInfo moduleInfo;
533             try {
534                 moduleInfo = getModuleInfo(key);
535             } catch (Exception e) {
536                 throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",e);
537             }
538             final QName module = getModuleQName(moduleInfo);
539             if (Augmentation.class.isAssignableFrom(key)) {
540                 return module;
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");
545                 } else {
546                     return QName.create(module,"input");
547                 }
548             }
549             /*
550              *  Fallback for Binding types which fo not have QNAME
551              *  field
552              */
553             return module;
554         } else {
555             throw new IllegalArgumentException("Supplied class "+key+"is not derived from YANG.");
556         }
557     }
558
559     /**
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.
563      *
564      * @param moduleInfo module information
565      * @return QName representing the module
566      */
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());
571     }
572
573     /**
574      * Extracts augmentation from Binding DTO field using reflection
575      *
576      * @param input Instance of DataObject which is augmentable and
577      *      may contain augmentation
578      * @return Map of augmentations if read was successful, otherwise
579      *      empty map.
580      */
581     public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
582         return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
583     }
584 }