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