Added implementation of getQName for Identity classes
[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 java.lang.reflect.Field;
11 import java.lang.reflect.Method;
12 import java.lang.reflect.Type;
13 import java.util.concurrent.Future;
14 import java.util.concurrent.TimeUnit;
15 import org.opendaylight.yangtools.concepts.util.ClassLoaderUtils;
16 import org.opendaylight.yangtools.yang.binding.Augmentable;
17 import org.opendaylight.yangtools.yang.binding.Augmentation;
18 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
19 import org.opendaylight.yangtools.yang.binding.BindingMapping;
20 import org.opendaylight.yangtools.yang.binding.ChildOf;
21 import org.opendaylight.yangtools.yang.binding.DataContainer;
22 import org.opendaylight.yangtools.yang.binding.DataObject;
23 import org.opendaylight.yangtools.yang.binding.RpcService;
24 import org.opendaylight.yangtools.yang.common.QName;
25
26 import static com.google.common.base.Preconditions.*;
27
28 import com.google.common.base.Optional;
29 import com.google.common.cache.CacheBuilder;
30 import com.google.common.cache.CacheLoader;
31 import com.google.common.cache.LoadingCache;
32
33 public class BindingReflections {
34
35     private static final long EXPIRATION_TIME = 60;
36
37     private static final LoadingCache<Class<?>, Optional<QName>> classToQName = CacheBuilder.newBuilder() //
38             .weakKeys() //
39             .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS) //
40             .build(new ClassToQNameLoader());
41
42     /**
43      * 
44      * @param augmentation
45      *            {@link Augmentation} subclass for which we want to determine
46      *            augmentation target.
47      * @return Augmentation target - class which augmentation provides
48      *         additional extensions.
49      */
50     public static Class<? extends Augmentable<?>> findAugmentationTarget(
51             final Class<? extends Augmentation<?>> augmentation) {
52         return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class);
53     }
54
55     /**
56      * 
57      * @param augmentation
58      *            {@link Augmentation} subclass for which we want to determine
59      *            augmentation target.
60      * @return Augmentation target - class which augmentation provides
61      *         additional extensions.
62      */
63     public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
64         return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class);
65     }
66
67     /**
68      * 
69      * @param augmentation
70      *            {@link Augmentation} subclass for which we want to determine
71      *            augmentation target.
72      * @return Augmentation target - class which augmentation provides
73      *         additional extensions.
74      */
75     public static Class<?> findHierarchicalParent(DataObject childClass) {
76         if (childClass instanceof ChildOf) {
77             return ClassLoaderUtils.findFirstGenericArgument(childClass.getImplementedInterface(), ChildOf.class);
78         }
79         return null;
80     }
81
82     public static final QName findQName(Class<?> dataType) {
83         return classToQName.getUnchecked(dataType).orNull();
84     }
85
86     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
87
88         @Override
89         public Optional<QName> load(Class<?> key) throws Exception {
90             try {
91                 Field field = key.getField(BindingMapping.QNAME_STATIC_FIELD_NAME);
92                 Object obj = field.get(null);
93                 if (obj instanceof QName) {
94                     return Optional.of((QName) obj);
95                 }
96             } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
97                 // NOOP
98             }
99             return Optional.absent();
100         }
101     }
102
103     public static boolean isRpcMethod(Method possibleMethod) {
104         return possibleMethod != null &&
105         RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
106         && Future.class.isAssignableFrom(possibleMethod.getReturnType())
107         && possibleMethod.getParameterTypes().length <= 1;
108     }
109
110     @SuppressWarnings("rawtypes")
111     public static Optional<Class<?>> resolveRpcOutputClass(Method targetMethod) {
112         checkState(isRpcMethod(targetMethod),"Supplied method is not Rpc invocation method");
113         Type futureType = targetMethod.getGenericReturnType();
114         Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType);
115         Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType);
116         if(rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
117             return Optional.<Class<?>>of((Class) rpcResultArgument);
118         }
119         return Optional.absent();
120     }
121
122     @SuppressWarnings("unchecked")
123     public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(Method targetMethod) {
124         @SuppressWarnings("rawtypes")
125         Class[] types = targetMethod.getParameterTypes();
126         if(types.length == 0) {
127             return Optional.absent();
128         }
129         if(types.length == 1) {
130             return Optional.<Class<? extends DataContainer>>of(types[0]);
131         }
132         throw new IllegalArgumentException("Method has 2 or more arguments.");
133     }
134
135     public static QName getQName(Class<? extends BaseIdentity> context) {
136         return findQName(context);
137     }
138 }