Deprecate BindingReflections.isNotification()
[mdsal.git] / binding / mdsal-binding-spec-util / src / main / java / org / opendaylight / mdsal / binding / spec / reflect / BindingReflections.java
index f82d8aa401d58f7a39f4c7549d4b0bccfdce1165..e7e467e45b2c88bb3543c149f48e3ad32cebd46b 100644 (file)
@@ -18,14 +18,12 @@ import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.ImmutableSet.Builder;
 import com.google.common.util.concurrent.ListenableFuture;
 import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
 import java.lang.reflect.Type;
 import java.util.Arrays;
-import java.util.HashMap;
 import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
 import java.util.Optional;
 import java.util.ServiceLoader;
 import java.util.Set;
@@ -33,17 +31,19 @@ import java.util.concurrent.TimeUnit;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import org.checkerframework.checker.regex.qual.Regex;
+import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
 import org.opendaylight.yangtools.util.ClassLoaderUtils;
 import org.opendaylight.yangtools.yang.binding.Action;
 import org.opendaylight.yangtools.yang.binding.Augmentable;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
+import org.opendaylight.yangtools.yang.binding.BindingContract;
 import org.opendaylight.yangtools.yang.binding.ChildOf;
 import org.opendaylight.yangtools.yang.binding.DataContainer;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.Notification;
+import org.opendaylight.yangtools.yang.binding.Rpc;
 import org.opendaylight.yangtools.yang.binding.RpcService;
 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
@@ -78,7 +78,7 @@ public final class BindingReflections {
                 });
 
     private BindingReflections() {
-        throw new UnsupportedOperationException("Utility class.");
+        // Hidden on purpose
     }
 
     /**
@@ -97,33 +97,6 @@ public final class BindingReflections {
         return opt.orElse(null);
     }
 
-    /**
-     * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
-     * {@link ChildOf} interface.
-     *
-     * @param childClass
-     *            child class for which we want to find the parent class.
-     * @return Parent class, e.g. class of which the childClass is ChildOf.
-     */
-    public static Class<?> findHierarchicalParent(final Class<? extends ChildOf<?>> childClass) {
-        return ClassLoaderUtils.findFirstGenericArgument(childClass, ChildOf.class).orElse(null);
-    }
-
-    /**
-     * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
-     * invoking {@link DataObject#implementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
-     *
-     * @param child
-     *            Child object for which the parent needs to be located.
-     * @return Parent class, or null if a parent is not found.
-     */
-    public static Class<?> findHierarchicalParent(final DataObject child) {
-        if (child instanceof ChildOf) {
-            return ClassLoaderUtils.findFirstGenericArgument(child.implementedInterface(), ChildOf.class).orElse(null);
-        }
-        return null;
-    }
-
     /**
      * Returns a QName associated to supplied type.
      *
@@ -156,18 +129,19 @@ public final class BindingReflections {
     /**
      * Extracts Output class for RPC method.
      *
-     * @param targetMethod
-     *            method to scan
+     * @param targetMethod method to scan
      * @return Optional.empty() if result type could not be get, or return type is Void.
+     * @deprecated This method is unused and scheduled for removal
      */
+    @Deprecated(since = "10.0.4", forRemoval = true)
     @SuppressWarnings("rawtypes")
     public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
         checkState(isRpcMethod(targetMethod), "Supplied method is not a RPC invocation method");
         Type futureType = targetMethod.getGenericReturnType();
         Type rpcResultType = ClassLoaderUtils.getFirstGenericParameter(futureType).orElse(null);
         Type rpcResultArgument = ClassLoaderUtils.getFirstGenericParameter(rpcResultType).orElse(null);
-        if (rpcResultArgument instanceof Class && !Void.class.equals(rpcResultArgument)) {
-            return Optional.of((Class) rpcResultArgument);
+        if (rpcResultArgument instanceof Class cls && !Void.class.equals(rpcResultArgument)) {
+            return Optional.of(cls);
         }
         return Optional.empty();
     }
@@ -175,10 +149,11 @@ public final class BindingReflections {
     /**
      * Extracts input class for RPC method.
      *
-     * @param targetMethod
-     *            method to scan
+     * @param targetMethod method to scan
      * @return Optional.empty() if RPC has no input, RPC input type otherwise.
+     * @deprecated This method is unused and scheduled for removal
      */
+    @Deprecated(since = "10.0.4", forRemoval = true)
     @SuppressWarnings("rawtypes")
     public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
         for (Class clazz : targetMethod.getParameterTypes()) {
@@ -189,29 +164,17 @@ public final class BindingReflections {
         return Optional.empty();
     }
 
-    // FIXME: 4.0.0: check that the QName is actually resolved, i.e. guarantee @NonNull here
-    public static QName getQName(final Class<? extends BaseIdentity> context) {
-        return findQName(context);
+    public static @NonNull QName getQName(final BaseIdentity identity) {
+        return getContractQName(identity);
     }
 
-    /**
-     * Checks if class is child of augmentation.
-     */
-    public static boolean isAugmentationChild(final Class<?> clazz) {
-        // FIXME: Current resolver could be still confused when child node was added by grouping
-        checkArgument(clazz != null);
-
-        @SuppressWarnings({ "rawtypes", "unchecked" })
-        Class<?> parent = findHierarchicalParent((Class) clazz);
-        if (parent == null) {
-            LOG.debug("Did not find a parent for class {}", clazz);
-            return false;
-        }
-
-        String clazzModelPackage = getModelRootPackageName(clazz.getPackage());
-        String parentModelPackage = getModelRootPackageName(parent.getPackage());
+    public static @NonNull QName getQName(final Rpc<?, ?> rpc) {
+        return getContractQName(rpc);
+    }
 
-        return !clazzModelPackage.equals(parentModelPackage);
+    private static @NonNull QName getContractQName(final BindingContract<?> contract) {
+        return CLASS_TO_QNAME.getUnchecked(contract.implementedInterface())
+            .orElseThrow(() -> new IllegalStateException("Failed to resolve QName of " + contract));
     }
 
     /**
@@ -242,37 +205,43 @@ public final class BindingReflections {
         return match.group(0);
     }
 
-    @SuppressWarnings("checkstyle:illegalCatch")
     public static QNameModule getQNameModule(final Class<?> clz) {
         if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)
                 || Action.class.isAssignableFrom(clz)) {
             return findQName(clz).getModule();
         }
-        try {
-            return BindingReflections.getModuleInfo(clz).getName().getModule();
-        } catch (Exception e) {
-            throw new IllegalStateException("Unable to get QName of defining model.", e);
-        }
+
+        return getModuleInfo(clz).getName().getModule();
     }
 
     /**
      * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
      *
      * @param cls data object class
-     * @return Instance of {@link YangModuleInfo} associated with model, from
-     *         which this class was derived.
+     * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
      */
-    public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
-        checkArgument(cls != null);
-        String packageName = getModelRootPackageName(cls.getPackage());
+    public static @NonNull YangModuleInfo getModuleInfo(final Class<?> cls) {
+        final String packageName = getModelRootPackageName(cls.getPackage());
         final String potentialClassName = getModuleInfoClassName(packageName);
-        return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> {
-            Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
-            return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
-        });
+        final Class<?> moduleInfoClass;
+        try {
+            moduleInfoClass = cls.getClassLoader().loadClass(potentialClassName);
+        } catch (ClassNotFoundException e) {
+            throw new IllegalStateException("Failed to load " + potentialClassName, e);
+        }
+
+        final Object infoInstance;
+        try {
+            infoInstance = moduleInfoClass.getMethod("getInstance").invoke(null);
+        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
+            throw new IllegalStateException("Failed to get instance of " + moduleInfoClass, e);
+        }
+
+        checkState(infoInstance instanceof YangModuleInfo, "Unexpected instance %s", infoInstance);
+        return (YangModuleInfo) infoInstance;
     }
 
-    public static String getModuleInfoClassName(final String packageName) {
+    public static @NonNull String getModuleInfoClassName(final String packageName) {
         return packageName + "." + BindingMapping.MODULE_INFO_CLASS_NAME;
     }
 
@@ -313,7 +282,9 @@ public final class BindingReflections {
      *
      * @param potentialNotification class to examine
      * @return True if the class represents a Notification.
+     * @deprecated This method is only used internally and is schedule for removal
      */
+    @Deprecated(since = "10.0.4", forRemoval = true)
     public static boolean isNotification(final Class<?> potentialNotification) {
         checkArgument(potentialNotification != null, "potentialNotification must not be null.");
         return Notification.class.isAssignableFrom(potentialNotification);
@@ -325,7 +296,7 @@ public final class BindingReflections {
      *
      * @return Set of {@link YangModuleInfo} available for current classloader.
      */
-    public static ImmutableSet<YangModuleInfo> loadModuleInfos() {
+    public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos() {
         return loadModuleInfos(Thread.currentThread().getContextClassLoader());
     }
 
@@ -347,7 +318,7 @@ public final class BindingReflections {
      * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
      * @return Set of {@link YangModuleInfo} available for supplied classloader.
      */
-    public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
+    public static @NonNull ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.builder();
         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
                 loader);
@@ -376,7 +347,7 @@ public final class BindingReflections {
      * @return Set of {@link YangModuleInfo} available for supplied classloader.
      */
     @Beta
-    public static ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
+    public static @NonNull ImmutableSet<YangModuleInfo> cacheModuleInfos(final ClassLoader loader) {
         return MODULE_INFO_CACHE.getUnchecked(loader);
     }
 
@@ -402,89 +373,6 @@ public final class BindingReflections {
                 && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output"));
     }
 
-    /**
-     * Scans supplied class and returns an iterable of all data children classes.
-     *
-     * @param type
-     *            YANG Modeled Entity derived from DataContainer
-     * @return Iterable of all data children, which have YANG modeled entity
-     */
-    @SuppressWarnings("unchecked")
-    public static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
-        checkArgument(type != null, "Target type must not be null");
-        checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
-        List<Class<? extends DataObject>> ret = new LinkedList<>();
-        for (Method method : type.getMethods()) {
-            Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method,
-                BindingMapping.GETTER_PREFIX);
-            if (entity.isPresent()) {
-                ret.add((Class<? extends DataObject>) entity.get());
-            }
-        }
-        return ret;
-    }
-
-    /**
-     * Scans supplied class and returns an iterable of all data children classes.
-     *
-     * @param type
-     *            YANG Modeled Entity derived from DataContainer
-     * @return Iterable of all data children, which have YANG modeled entity
-     */
-    public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
-        return getChildrenClassToMethod(type, BindingMapping.GETTER_PREFIX);
-    }
-
-    private static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type, final String prefix) {
-        checkArgument(type != null, "Target type must not be null");
-        checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
-            type);
-        Map<Class<?>, Method> ret = new HashMap<>();
-        for (Method method : type.getMethods()) {
-            Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method, prefix);
-            if (entity.isPresent()) {
-                ret.put(entity.get(), method);
-            }
-        }
-        return ret;
-    }
-
-    @Beta
-    public static Map<Class<?>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
-        return getChildrenClassToMethod(type, BindingMapping.NONNULL_PREFIX);
-    }
-
-    @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" })
-    private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
-            final String prefix) {
-        final String methodName = method.getName();
-        if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
-            return Optional.empty();
-        }
-
-        Class returnType = method.getReturnType();
-        if (DataContainer.class.isAssignableFrom(returnType)) {
-            return Optional.of(returnType);
-        }
-        if (List.class.isAssignableFrom(returnType)) {
-            try {
-                return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(), () -> {
-                    return ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType()).flatMap(
-                        result -> result instanceof Class && DataContainer.class.isAssignableFrom((Class) result)
-                            ? Optional.of((Class<? extends DataContainer>) result) : Optional.empty());
-                });
-            } catch (Exception e) {
-                /*
-                 * It is safe to log this this exception on debug, since this
-                 * method should not fail. Only failures are possible if the
-                 * runtime / backing.
-                 */
-                LOG.debug("Unable to find YANG modeled return type for {}", method, e);
-            }
-        }
-        return Optional.empty();
-    }
-
     private static class ClassToQNameLoader extends CacheLoader<Class<?>, Optional<QName>> {
 
         @Override
@@ -509,8 +397,8 @@ public final class BindingReflections {
                 }
 
                 final Object obj = field.get(null);
-                if (obj instanceof QName) {
-                    return Optional.of((QName) obj);
+                if (obj instanceof QName qname) {
+                    return Optional.of(qname);
                 }
             } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
                 /*
@@ -542,18 +430,11 @@ public final class BindingReflections {
          * @throws IllegalArgumentException If supplied class was not derived from YANG model.
          */
         // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
-        @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
+        @SuppressWarnings({ "rawtypes", "unchecked" })
         private static QName computeQName(final Class key) {
             checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
 
-            YangModuleInfo moduleInfo;
-            try {
-                moduleInfo = getModuleInfo(key);
-            } catch (Exception e) {
-                throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
-                    e);
-            }
-            final QName module = moduleInfo.getName();
+            final QName module = getModuleInfo(key).getName();
             if (Augmentation.class.isAssignableFrom(key)) {
                 return module;
             } else if (isRpcType(key)) {
@@ -573,48 +454,34 @@ public final class BindingReflections {
     }
 
     /**
-     * Extracts augmentation from Binding DTO field using reflection.
-     *
-     * @param input
-     *            Instance of DataObject which is augmentable and may contain
-     *            augmentation
-     * @return Map of augmentations if read was successful, otherwise empty map.
-     */
-    public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
-        if (input instanceof AugmentationHolder) {
-            return ((AugmentationHolder) input).augmentations();
-        }
-        return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
-    }
-
-    /**
-     * Determines if two augmentation classes or case classes represents same
-     * data.
+     * Determines if two augmentation classes or case classes represents same data.
      *
      * <p>
      * Two augmentations or cases could be substituted only if and if:
      * <ul>
-     * <li>Both implements same interfaces</li>
-     * <li>Both have same children</li>
-     * <li>If augmentations: Both have same augmentation target class. Target
-     * class was generated for data node in grouping.</li>
-     * <li>If cases: Both are from same choice. Choice class was generated for
-     * data node in grouping.</li>
+     *   <li>Both implements same interfaces</li>
+     *   <li>Both have same children</li>
+     *   <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
+     *       grouping.</li>
+     *   <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
      * </ul>
      *
      * <p>
-     * <b>Explanation:</b> Binding Specification reuses classes generated for
-     * groupings as part of normal data tree, this classes from grouping could
-     * be used at various locations and user may not be aware of it and may use
-     * incorrect case or augmentation in particular subtree (via copy
-     * constructors, etc).
+     * <b>Explanation:</b>
+     * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
+     * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
+     * augmentation in particular subtree (via copy constructors, etc).
      *
-     * @param potential
-     *            Class which is potential substitution
-     * @param target
-     *            Class which should be used at particular subtree
+     * @param potential Class which is potential substitution
+     * @param target Class which should be used at particular subtree
      * @return true if and only if classes represents same data.
+     * @throws NullPointerException if any argument is {@code null}
      */
+    // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
+    //                   user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
+    //                   a particular world this boils down to a matrix, which can be calculated either on-demand or
+    //                   when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
+    //                   to have a pre-compiled Binding Runtime.
     @SuppressWarnings({ "rawtypes", "unchecked" })
     public static boolean isSubstitutionFor(final Class potential, final Class target) {
         Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
@@ -628,6 +495,11 @@ public final class BindingReflections {
             return false;
         }
         for (Method potentialMethod : potential.getMethods()) {
+            if (Modifier.isStatic(potentialMethod.getModifiers())) {
+                // Skip any static methods, as we are not interested in those
+                continue;
+            }
+
             try {
                 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
                 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {