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 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;
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()
44 .expireAfterAccess(60, TimeUnit.SECONDS)
45 .build(new ClassToQNameLoader());
47 private BindingReflections() {
52 * Returns a QName associated to supplied type.
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.
59 public static QName findQName(final Class<?> dataType) {
60 return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null);
63 public static @NonNull QName getQName(final BaseIdentity identity) {
64 return getContractQName(identity);
67 public static @NonNull QName getQName(final Rpc<?, ?> rpc) {
68 return getContractQName(rpc);
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));
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();
82 return getModuleInfo(clz).getName().getModule();
86 * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
88 * @param cls data object class
89 * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
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;
96 moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
97 } catch (ClassNotFoundException e) {
98 throw new IllegalStateException("Failed to load " + potentialClassName, e);
101 final Object infoInstance;
103 infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
104 } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
105 throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
108 checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
109 return (YangModuleInfo) infoInstance;
113 * Check if supplied class is derived from YANG model.
117 * @return true if class is derived from YANG model.
119 public static boolean isBindingClass(final Class<?> cls) {
120 if (DataContainer.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls)) {
123 return cls.getName().startsWith(Naming.PACKAGE_PREFIX);
127 * Checks if supplied method is callback for notifications.
129 * @param method method to check
130 * @return true if method is notification callback.
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())) {
145 * Checks is supplied class is a {@link Notification}.
147 * @param potentialNotification class to examine
148 * @return True if the class represents a Notification.
151 static boolean isNotification(final Class<?> potentialNotification) {
152 checkArgument(potentialNotification != null, "potentialNotification must not be null.");
153 return Notification.class.isAssignableFrom(potentialNotification);
157 * Checks if supplied class represents RPC Input / RPC Output.
160 * Class to be checked
161 * @return true if class represents RPC Input or RPC Output class.
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"));
170 private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
173 public Optional<QName> load(@SuppressWarnings("NullableProblems") final Class<?> key) throws Exception {
174 return resolveQNameNoCache(key);
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.
182 private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
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));
193 final Object obj = field.get(null);
194 if (obj instanceof QName qname) {
195 return Optional.of(qname);
197 } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
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.
202 LOG.debug("Unexpected exception during extracting QName for {}", key, e);
204 return Optional.empty();
208 * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
214 * <li>rpc input: local name is "input".
215 * <li>rpc output: local name is "output".
216 * <li>augmentation: local name is "module name".
220 * There is also fallback, if it is not possible to compute QName using following algorithm returns module
223 * @throws IllegalStateException If YangModuleInfo could not be resolved
224 * @throws IllegalArgumentException If supplied class was not derived from YANG model.
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);
231 final QName module = getModuleInfo(key).getName();
232 if (Augmentation.class.isAssignableFrom(key)) {
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();
240 return YangConstants.operationInputQName(module.getModule()).intern();
244 * Fallback for Binding types which do not have QNAME field