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.collect.ImmutableSet;
18 import com.google.common.collect.ImmutableSet.Builder;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.util.Optional;
24 import java.util.ServiceLoader;
25 import java.util.concurrent.TimeUnit;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.yangtools.yang.binding.Action;
28 import org.opendaylight.yangtools.yang.binding.Augmentation;
29 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
30 import org.opendaylight.yangtools.yang.binding.BindingContract;
31 import org.opendaylight.yangtools.yang.binding.ChildOf;
32 import org.opendaylight.yangtools.yang.binding.DataContainer;
33 import org.opendaylight.yangtools.yang.binding.DataObject;
34 import org.opendaylight.yangtools.yang.binding.Notification;
35 import org.opendaylight.yangtools.yang.binding.Rpc;
36 import org.opendaylight.yangtools.yang.binding.RpcService;
37 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
38 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
39 import org.opendaylight.yangtools.yang.binding.contract.Naming;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.common.QNameModule;
42 import org.opendaylight.yangtools.yang.common.YangConstants;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 public final class BindingReflections {
47 private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
48 private static final LoadingCache<Class<?>, Optional<QName>> CLASS_TO_QNAME = CacheBuilder.newBuilder()
50 .expireAfterAccess(60, TimeUnit.SECONDS)
51 .build(new ClassToQNameLoader());
53 private BindingReflections() {
58 * Returns a QName associated to supplied type.
60 * @param dataType Data type class
61 * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
62 * QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
63 * have name. May return null if QName is not present.
65 public static QName findQName(final Class<?> dataType) {
66 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
70 * Checks if method is RPC invocation.
72 * @param possibleMethod
74 * @return true if method is RPC invocation, false otherwise.
76 public static boolean isRpcMethod(final Method possibleMethod) {
77 return possibleMethod != null && RpcService.class.isAssignableFrom(possibleMethod.getDeclaringClass())
78 && ListenableFuture.class.isAssignableFrom(possibleMethod.getReturnType())
79 // length <= 2: it seemed to be impossible to get correct RpcMethodInvoker because of
80 // resolveRpcInputClass() check.While RpcMethodInvoker counts with one argument for
81 // non input type and two arguments for input type, resolveRpcInputClass() counting
82 // with zero for non input and one for input type
83 && possibleMethod.getParameterCount() <= 2;
86 public static @NonNull QName getQName(final BaseIdentity identity) {
87 return getContractQName(identity);
90 public static @NonNull QName getQName(final Rpc<?, ?> rpc) {
91 return getContractQName(rpc);
94 private static @NonNull QName getContractQName(final BindingContract<?> contract) {
95 return CLASS_TO_QNAME.getUnchecked(contract.implementedInterface())
96 .orElseThrow(() -> new IllegalStateException("Failed to resolve QName of " + contract));
99 public static QNameModule getQNameModule(final Class<?> clz) {
100 if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
101 || Action.class.isAssignableFrom(clz)) {
102 return findQName(clz).getModule();
105 return getModuleInfo(clz).getName().getModule();
109 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
111 * @param cls data object class
112 * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
114 private static @NonNull YangModuleInfo getModuleInfo(final Class<?> cls) {
115 final String packageName = Naming.getModelRootPackageName(cls.getPackage().getName());
116 final String potentialClassName = getModuleInfoClassName(packageName);
117 final Class<?> moduleInfoClass;
119 moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
120 } catch (ClassNotFoundException e) {
121 throw new IllegalStateException("Failed to load " + potentialClassName, e);
124 final Object infoInstance;
126 infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
127 } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
128 throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
131 checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
132 return (YangModuleInfo) infoInstance;
135 public static @NonNull String getModuleInfoClassName(final String packageName) {
136 return packageName + "." + Naming.MODULE_INFO_CLASS_NAME;
140 * Check if supplied class is derived from YANG model.
144 * @return true if class is derived from YANG model.
146 public static boolean isBindingClass(final Class<?> cls) {
147 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
150 return cls.getName().startsWith(Naming.PACKAGE_PREFIX);
154 * Checks if supplied method is callback for notifications.
156 * @param method method to check
157 * @return true if method is notification callback.
159 public static boolean isNotificationCallback(final Method method) {
160 checkArgument(method != null);
161 if (method.getName().startsWith("on") && method.getParameterCount() == 1) {
162 Class<?> potentialNotification = method.getParameterTypes()[0];
163 if (isNotification(potentialNotification)
164 && method.getName().equals("on" + potentialNotification.getSimpleName())) {
172 * Checks is supplied class is a {@link Notification}.
174 * @param potentialNotification class to examine
175 * @return True if the class represents a Notification.
178 static boolean isNotification(final Class<?> potentialNotification) {
179 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
180 return Notification.class.isAssignableFrom(potentialNotification);
184 * Loads {@link YangModuleInfo} infos available on supplied classloader.
187 * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
188 * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
189 * {@link YangModuleInfo}.
192 * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
193 * collecting results of {@link YangModuleInfo#getImportedModules()}.
195 * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
196 * @return Set of {@link YangModuleInfo} available for supplied classloader.
198 public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
199 Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
200 ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
202 for (YangModelBindingProvider bindingProvider : serviceLoader) {
203 YangModuleInfo moduleInfo = bindingProvider.getModuleInfo();
204 checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass());
205 collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet);
207 return moduleInfoSet.build();
210 private static void collectYangModuleInfo(final YangModuleInfo moduleInfo,
211 final Builder<YangModuleInfo> moduleInfoSet) {
212 moduleInfoSet.add(moduleInfo);
213 for (YangModuleInfo dependency : moduleInfo.getImportedModules()) {
214 collectYangModuleInfo(dependency, moduleInfoSet);
219 * Checks if supplied class represents RPC Input / RPC Output.
222 * Class to be checked
223 * @return true if class represents RPC Input or RPC Output class.
225 public static boolean isRpcType(final Class<? extends DataObject> targetType) {
226 return DataContainer.class.isAssignableFrom(targetType)
227 && !ChildOf.class.isAssignableFrom(targetType)
228 && !Notification.class.isAssignableFrom(targetType)
229 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
232 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
235 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
236 return resolveQNameNoCache(key);
240 * Tries to resolve QName for supplied class. Looks up for static field with name from constant
241 * {@link Naming#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
242 * {@link #computeQName(Class)} to compute QName for missing types.
244 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
248 field = key.getField(Naming.QNAME_STATIC_FIELD_NAME);
249 } catch (NoSuchFieldException e) {
250 LOG.debug("{} does not have a {} field, falling back to computation", key,
251 Naming.QNAME_STATIC_FIELD_NAME, e);
252 return Optional.of(computeQName(key));
255 final Object obj = field.get(null);
256 if (obj instanceof QName qname) {
257 return Optional.of(qname);
259 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
261 * It is safe to log this this exception on debug, since this method should not fail. Only failures are
262 * possible if the runtime / backing is inconsistent.
264 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
266 return Optional.empty();
270 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
276 * <li>rpc input: local name is "input".
277 * <li>rpc output: local name is "output".
278 * <li>augmentation: local name is "module name".
282 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
285 * @throws IllegalStateException If YangModuleInfo could not be resolved
286 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
288 // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
289 @SuppressWarnings({ "rawtypes", "unchecked" })
290 private static QName computeQName(final Class key) {
291 checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
293 final QName module = getModuleInfo(key).getName();
294 if (Augmentation.class.isAssignableFrom(key)) {
296 } else if (isRpcType(key)) {
297 final String className = key.getSimpleName();
298 if (className.endsWith(Naming.RPC_OUTPUT_SUFFIX)) {
299 return YangConstants.operationOutputQName(module.getModule()).intern();
302 return YangConstants.operationInputQName(module.getModule()).intern();
306 * Fallback for Binding types which do not have QNAME field