Remove BindingReflections.isRpcMethod()
[mdsal.git] / binding / mdsal-binding-spec-util / src / main / java / org / opendaylight / mdsal / binding / spec / reflect / 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.mdsal.binding.spec.reflect;
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.annotations.VisibleForTesting;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import java.lang.reflect.Field;
18 import java.lang.reflect.InvocationTargetException;
19 import java.lang.reflect.Method;
20 import java.util.Optional;
21 import java.util.concurrent.TimeUnit;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.yangtools.yang.binding.Action;
24 import org.opendaylight.yangtools.yang.binding.Augmentation;
25 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
26 import org.opendaylight.yangtools.yang.binding.BindingContract;
27 import org.opendaylight.yangtools.yang.binding.ChildOf;
28 import org.opendaylight.yangtools.yang.binding.DataContainer;
29 import org.opendaylight.yangtools.yang.binding.DataObject;
30 import org.opendaylight.yangtools.yang.binding.Notification;
31 import org.opendaylight.yangtools.yang.binding.Rpc;
32 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
33 import org.opendaylight.yangtools.yang.binding.contract.Naming;
34 import org.opendaylight.yangtools.yang.common.QName;
35 import org.opendaylight.yangtools.yang.common.QNameModule;
36 import org.opendaylight.yangtools.yang.common.YangConstants;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public final class BindingReflections {
41     private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
42     private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
43             .weakKeys()
44             .expireAfterAccess(60, TimeUnit.SECONDS)
45             .build(new ClassToQNameLoader());
46
47     private BindingReflections() {
48         // Hidden on purpose
49     }
50
51     /**
52      * Returns a QName associated to supplied type.
53      *
54      * @param dataType Data type class
55      * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
56      *         QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
57      *         have name. May return null if QName is not present.
58      */
59     public static QName findQName(final Class<?> dataType) {
60         return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
61     }
62
63     public static @NonNull QName getQName(final BaseIdentity identity) {
64         return getContractQName(identity);
65     }
66
67     public static @NonNull QName getQName(final Rpc<?, ?> rpc) {
68         return getContractQName(rpc);
69     }
70
71     private static @NonNull QName getContractQName(final BindingContract<?> contract) {
72         return CLASS_TO_QNAME.getUnchecked(contract.implementedInterface())
73             .orElseThrow(() -> new IllegalStateException("Failed to resolve QName of " + contract));
74     }
75
76     public static QNameModule getQNameModule(final Class<?> clz) {
77         if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
78                 || Action.class.isAssignableFrom(clz)) {
79             return findQName(clz).getModule();
80         }
81
82         return getModuleInfo(clz).getName().getModule();
83     }
84
85     /**
86      * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
87      *
88      * @param cls data object class
89      * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
90      */
91     private static @NonNull YangModuleInfo getModuleInfo(final Class<?> cls) {
92         final String potentialClassName = Naming.getModelRootPackageName(cls.getPackage().getName()) + "."
93             + Naming.MODULE_INFO_CLASS_NAME;
94         final Class<?> moduleInfoClass;
95         try {
96             moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
97         } catch (ClassNotFoundException e) {
98             throw new IllegalStateException("Failed to load " + potentialClassName, e);
99         }
100
101         final Object infoInstance;
102         try {
103             infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
104         } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
105             throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
106         }
107
108         checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
109         return (YangModuleInfo) infoInstance;
110     }
111
112     /**
113      * Check if supplied class is derived from YANG model.
114      *
115      * @param cls
116      *            Class to check
117      * @return true if class is derived from YANG model.
118      */
119     public static boolean isBindingClass(final Class<?> cls) {
120         if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
121             return true;
122         }
123         return cls.getName().startsWith(Naming.PACKAGE_PREFIX);
124     }
125
126     /**
127      * Checks if supplied method is callback for notifications.
128      *
129      * @param method method to check
130      * @return true if method is notification callback.
131      */
132     public static boolean isNotificationCallback(final Method method) {
133         checkArgument(method != null);
134         if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
135             Class<?> potentialNotification = method.getParameterTypes()[0];
136             if (isNotification(potentialNotification)
137                     && method.getName().equals("on" + potentialNotification.getSimpleName())) {
138                 return true;
139             }
140         }
141         return false;
142     }
143
144     /**
145      * Checks is supplied class is a {@link Notification}.
146      *
147      * @param potentialNotification class to examine
148      * @return True if the class represents a Notification.
149      */
150     @VisibleForTesting
151     static boolean isNotification(final Class<?> potentialNotification) {
152         checkArgument(potentialNotification != null, "potentialNotification must not be null.");
153         return Notification.class.isAssignableFrom(potentialNotification);
154     }
155
156     /**
157      * Checks if supplied class represents RPC Input / RPC Output.
158      *
159      * @param targetType
160      *            Class to be checked
161      * @return true if class represents RPC Input or RPC Output class.
162      */
163     public static boolean isRpcType(final Class<? extends DataObject> targetType) {
164         return DataContainer.class.isAssignableFrom(targetType)
165                 && !ChildOf.class.isAssignableFrom(targetType)
166                 && !Notification.class.isAssignableFrom(targetType)
167                 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
168     }
169
170     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
171
172         @Override
173         public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
174             return resolveQNameNoCache(key);
175         }
176
177         /**
178          * Tries to resolve QName for supplied class. Looks up for static field with name from constant
179          * {@link Naming#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
180          * {@link #computeQName(Class)} to compute QName for missing types.
181          */
182         private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
183             try {
184                 final Field field;
185                 try {
186                     field = key.getField(Naming.QNAME_STATIC_FIELD_NAME);
187                 } catch (NoSuchFieldException e) {
188                     LOG.debug("{} does not have a {} field, falling back to computation", key,
189                         Naming.QNAME_STATIC_FIELD_NAME, e);
190                     return Optional.of(computeQName(key));
191                 }
192
193                 final Object obj = field.get(null);
194                 if (obj instanceof QName qname) {
195                     return Optional.of(qname);
196                 }
197             } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
198                 /*
199                  * It is safe to log this this exception on debug, since this method should not fail. Only failures are
200                  * possible if the runtime / backing is inconsistent.
201                  */
202                 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
203             }
204             return Optional.empty();
205         }
206
207         /**
208          * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
209          * supplied class.
210          *
211          * <p>
212          * If class is
213          * <ul>
214          * <li>rpc input: local name is "input".
215          * <li>rpc output: local name is "output".
216          * <li>augmentation: local name is "module name".
217          * </ul>
218          *
219          * <p>
220          * There is also fallback, if it is not possible to compute QName using following algorithm returns module
221          * QName.
222          *
223          * @throws IllegalStateException If YangModuleInfo could not be resolved
224          * @throws IllegalArgumentException If supplied class was not derived from YANG model.
225          */
226         // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
227         @SuppressWarnings({ "rawtypes", "unchecked" })
228         private static QName computeQName(final Class key) {
229             checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
230
231             final QName module = getModuleInfo(key).getName();
232             if (Augmentation.class.isAssignableFrom(key)) {
233                 return module;
234             } else if (isRpcType(key)) {
235                 final String className = key.getSimpleName();
236                 if (className.endsWith(Naming.RPC_OUTPUT_SUFFIX)) {
237                     return YangConstants.operationOutputQName(module.getModule()).intern();
238                 }
239
240                 return YangConstants.operationInputQName(module.getModule()).intern();
241             }
242
243             /*
244              * Fallback for Binding types which do not have QNAME field
245              */
246             return module;
247         }
248     }
249 }