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.mdsal.binding.spec.reflect;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
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;
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()
46 .expireAfterAccess(60, TimeUnit.SECONDS)
47 .build(new ClassToQNameLoader());
49 private BindingReflections() {
54 * Returns a QName associated to supplied type.
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.
61 public static QName findQName(final Class<?> dataType) {
62 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
66 * Checks if method is RPC invocation.
68 * @param possibleMethod
70 * @return true if method is RPC invocation, false otherwise.
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;
82 public static @NonNull QName getQName(final BaseIdentity identity) {
83 return getContractQName(identity);
86 public static @NonNull QName getQName(final Rpc<?, ?> rpc) {
87 return getContractQName(rpc);
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));
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();
101 return getModuleInfo(clz).getName().getModule();
105 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
107 * @param cls data object class
108 * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
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;
115 moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
116 } catch (ClassNotFoundException e) {
117 throw new IllegalStateException("Failed to load " + potentialClassName, e);
120 final Object infoInstance;
122 infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
123 } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
124 throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
127 checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
128 return (YangModuleInfo) infoInstance;
132 * Check if supplied class is derived from YANG model.
136 * @return true if class is derived from YANG model.
138 public static boolean isBindingClass(final Class<?> cls) {
139 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
142 return cls.getName().startsWith(Naming.PACKAGE_PREFIX);
146 * Checks if supplied method is callback for notifications.
148 * @param method method to check
149 * @return true if method is notification callback.
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())) {
164 * Checks is supplied class is a {@link Notification}.
166 * @param potentialNotification class to examine
167 * @return True if the class represents a Notification.
170 static boolean isNotification(final Class<?> potentialNotification) {
171 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
172 return Notification.class.isAssignableFrom(potentialNotification);
176 * Checks if supplied class represents RPC Input / RPC Output.
179 * Class to be checked
180 * @return true if class represents RPC Input or RPC Output class.
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"));
189 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
192 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
193 return resolveQNameNoCache(key);
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.
201 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
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));
212 final Object obj = field.get(null);
213 if (obj instanceof QName qname) {
214 return Optional.of(qname);
216 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
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.
221 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
223 return Optional.empty();
227 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
233 * <li>rpc input: local name is "input".
234 * <li>rpc output: local name is "output".
235 * <li>augmentation: local name is "module name".
239 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
242 * @throws IllegalStateException If YangModuleInfo could not be resolved
243 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
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);
250 final QName module = getModuleInfo(key).getName();
251 if (Augmentation.class.isAssignableFrom(key)) {
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();
259 return YangConstants.operationInputQName(module.getModule()).intern();
263 * Fallback for Binding types which do not have QNAME field