BUG-2159: fix wrong javadocs
[yangtools.git] / yang / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / util / BindingReflections.java
index d6c1d7b75138ab6da9ad5290cc83f4714459b7a3..6d6decb8ec74d5bb25fa98e8b727f4306cc9b3dd 100644 (file)
@@ -9,20 +9,29 @@ package org.opendaylight.yangtools.yang.binding.util;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkState;
-
+import com.google.common.base.Optional;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSet.Builder;
+import com.google.common.collect.Sets;
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Map;
 import java.util.ServiceLoader;
 import java.util.concurrent.Callable;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
+import org.opendaylight.yangtools.util.ClassLoaderUtils;
 import org.opendaylight.yangtools.yang.binding.Augmentable;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
@@ -38,13 +47,6 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Optional;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.ImmutableSet.Builder;
-
 public class BindingReflections {
 
     private static final long EXPIRATION_TIME = 60;
@@ -58,12 +60,12 @@ public class BindingReflections {
             .build(new ClassToQNameLoader());
 
 
+
     private BindingReflections() {
         throw new UnsupportedOperationException("Utility class.");
     }
 
     /**
-     *
      * Find augmentation target class from concrete Augmentation class
      *
      * This method uses first generic argument of
@@ -86,11 +88,9 @@ public class BindingReflections {
      * This method uses first generic argument of
      * implemented {@link ChildOf} interface.
      *
-     * @param augmentation
-     *            {@link Augmentation} subclass for which we want to determine
-     *            augmentation target.
-     * @return Augmentation target - class which augmentation provides
-     *         additional extensions.
+     * @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);
@@ -102,11 +102,9 @@ public class BindingReflections {
      * This method is shorthand which gets DataObject class by invoking
      * {@link DataObject#getImplementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
      *
-     * @param childClass
-     *            {@link Augmentation} subclass for which we want to determine
-     *            augmentation target.
-     * @return Augmentation target - class which augmentation provides
-     *         additional extensions.
+     * @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) {
@@ -225,9 +223,9 @@ public class BindingReflections {
     }
 
     /**
-     * Returns root package name for suplied package name.
+     * Returns root package name for supplied package name.
      *
-     * @param pkg Package for which find model root package.
+     * @param name Package for which find model root package.
      * @return Package of model root.
      */
     public static String getModelRootPackageName(final String name) {
@@ -395,6 +393,26 @@ public class BindingReflections {
         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) {
+       checkArgument(type != null, "Target type must not be null");
+       checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
+       Map<Class<?>,Method> ret = new HashMap<>();
+       for (Method method : type.getMethods()) {
+           Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
+           if (entity.isPresent()) {
+               ret.put(entity.get(),method);
+           }
+       }
+       return ret;
+   }
+
     @SuppressWarnings("unchecked")
     private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
         if (method.getName().equals("getClass") || !method.getName().startsWith("get")
@@ -533,11 +551,76 @@ public class BindingReflections {
         }
     }
 
+    /**
+     * Given a {@link YangModuleInfo}, create a QName representing it. The QName
+     * is formed by reusing the module's namespace and revision using the module's
+     * name as the QName's local name.
+     *
+     * @param moduleInfo module information
+     * @return QName representing the module
+     */
     public static QName getModuleQName(final YangModuleInfo moduleInfo) {
         checkArgument(moduleInfo != null, "moduleInfo must not be null.");
         return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(),
                 moduleInfo.getName());
     }
 
+    /**
+     * 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) {
+        return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
+    }
 
+    /**
+     *
+     * 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>
+     * </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).
+     *
+     * @param potential Class which is potential substition
+     * @param target Class which should be used at particular subtree
+     * @return true if and only if classes represents same data.
+     */
+    @SuppressWarnings({"rawtypes","unchecked"})
+    public static boolean isSubstitutionFor(final Class potential, final Class target) {
+        HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
+        HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
+        if(!subImplemented.equals(targetImplemented)) {
+            return false;
+        }
+        if(Augmentation.class.isAssignableFrom(potential)
+                && !BindingReflections.findAugmentationTarget(potential).equals(BindingReflections.findAugmentationTarget(target))) {
+                return false;
+        }
+        for(Method potentialMethod : potential.getMethods()) {
+            try {
+                Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
+                if(!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
+                    return false;
+                }
+            } catch (NoSuchMethodException e) {
+                // Counterpart method is missing, so classes could not be substituted.
+                return false;
+            } catch (SecurityException e) {
+                throw new IllegalStateException("Could not compare methods",e);
+            }
+        }
+        return true;
+    }
 }