Move grouping/instantiation lookup code
[mdsal.git] / binding / mdsal-binding-runtime-api / src / main / java / org / opendaylight / mdsal / binding / runtime / api / AbstractBindingRuntimeContext.java
index 6b7b625b5a948122b9bf7878620096fe0a575ab5..0eb80331245e9a6ea0084c2ea8ff4f6c75f15f3a 100644 (file)
@@ -27,7 +27,6 @@ import java.util.Optional;
 import java.util.Set;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
-import org.opendaylight.mdsal.binding.model.api.DefaultType;
 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
@@ -36,6 +35,7 @@ import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilde
 import org.opendaylight.yangtools.yang.binding.Action;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
 import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
@@ -44,11 +44,11 @@ import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
-import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -71,65 +71,87 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
                 final Optional<Type> identityType = getTypes().findIdentity(key);
                 checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
                 try {
-                    return getStrategy().loadClass(identityType.get());
+                    return loadClass(identityType.get());
                 } catch (final ClassNotFoundException e) {
                     throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
                 }
             }
         });
 
-    /**
-     * Returns schema of augmentation.
-     *
-     * <p>Returned schema is schema definition from which augmentation class was generated.
-     * This schema is isolated from other augmentations. This means it contains
-     * augmentation definition as was present in original YANG module.
-     *
-     * <p>Children of returned schema does not contain any additional augmentations,
-     * which may be present in runtime for them, thus returned schema is unsuitable
-     * for use for validation of data.
-     *
-     * <p>For retrieving {@link AugmentationSchemaNode}, which will contains
-     * full model for child nodes, you should use method
-     * {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
-     * which will return augmentation schema derived from supplied augmentation target
-     * schema.
-     *
-     * @param augClass Augmentation class
-     * @return Schema of augmentation or null if augmentaiton is not known in this context
-     * @throws IllegalArgumentException If supplied class is not an augmentation
-     */
     @Override
-    public final @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
-        checkArgument(Augmentation.class.isAssignableFrom(augClass),
-            "Class %s does not represent augmentation", augClass);
-        return getTypes().findAugmentation(DefaultType.of(augClass)).orElse(null);
+    public final <T extends Augmentation<?>> AugmentationSchemaNode getAugmentationDefinition(final Class<T> augClass) {
+        return getTypes().findAugmentation(Type.of(augClass)).orElse(null);
     }
 
-    /**
-     * Returns defining {@link DataSchemaNode} for supplied class.
-     *
-     * <p>Returned schema is schema definition from which class was generated.
-     * This schema may be isolated from augmentations, if supplied class
-     * represent node, which was child of grouping or augmentation.
-     *
-     * <p>For getting augmentation schema from augmentation class use
-     * {@link #getAugmentationDefinition(Class)} instead.
-     *
-     * @param cls Class which represents list, container, choice or case.
-     * @return Schema node, from which class was generated.
-     */
     @Override
     public final DataSchemaNode getSchemaDefinition(final Class<?> cls) {
         checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
             cls);
         checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
-        return (DataSchemaNode) getTypes().findSchema(DefaultType.of(cls)).orElse(null);
+        return (DataSchemaNode) getTypes().findSchema(Type.of(cls)).orElse(null);
+    }
+
+    @Override
+    public final DataSchemaNode findChildSchemaDefinition(final DataNodeContainer parentSchema,
+            final QNameModule parentNamespace, final Class<?> childClass) {
+        final DataSchemaNode origDef = getSchemaDefinition(childClass);
+        // Direct instantiation or use in same module in which grouping was defined.
+        DataSchemaNode sameName;
+        try {
+            sameName = parentSchema.dataChildByName(origDef.getQName());
+        } catch (final IllegalArgumentException e) {
+            LOG.trace("Failed to find schema for {}", origDef, e);
+            sameName = null;
+        }
+
+        final DataSchemaNode childSchema;
+        if (sameName != null) {
+            // Check if it is:
+            // - exactly same schema node, or
+            // - instantiated node was added via uses statement and is instantiation of same grouping
+            if (origDef.equals(sameName) || origDef.equals(getRootOriginalIfPossible(sameName))) {
+                childSchema = sameName;
+            } else {
+                // Node has same name, but clearly is different
+                childSchema = null;
+            }
+        } else {
+            // We are looking for instantiation via uses in other module
+            final QName instantiedName = origDef.getQName().bindTo(parentNamespace);
+            final DataSchemaNode potential = parentSchema.dataChildByName(instantiedName);
+            // We check if it is really instantiated from same definition as class was derived
+            if (potential != null && origDef.equals(getRootOriginalIfPossible(potential))) {
+                childSchema = potential;
+            } else {
+                childSchema = null;
+            }
+        }
+
+        return childSchema;
+    }
+
+    private static @Nullable SchemaNode getRootOriginalIfPossible(final SchemaNode data) {
+        SchemaNode previous = null;
+        SchemaNode next = getOriginalIfPossible(data);
+        while (next != null) {
+            previous = next;
+            next = getOriginalIfPossible(next);
+        }
+        return previous;
+    }
+
+    private static @Nullable SchemaNode getOriginalIfPossible(final SchemaNode node) {
+        return node instanceof DerivableSchemaNode ? ((DerivableSchemaNode) node).getOriginal().orElse(null) : null;
     }
 
     @Override
     public final ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
-        return (ActionDefinition) getTypes().findSchema(DefaultType.of(cls)).orElse(null);
+        return (ActionDefinition) getTypes().findSchema(Type.of(cls)).orElse(null);
+    }
+
+    @Override
+    public final Absolute getActionIdentifier(final Class<? extends Action<?, ?, ?>> cls) {
+        return getTypes().findSchemaNodeIdentifier(Type.of(cls)).orElse(null);
     }
 
     @Override
@@ -152,7 +174,7 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
         final Set<QName> childNames = new HashSet<>();
         final Set<DataSchemaNode> realChilds = new HashSet<>();
         for (final DataSchemaNode child : origSchema.getChildNodes()) {
-            final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
+            final DataSchemaNode dataChildQNname = target.dataChildByName(child.getQName());
             final String childLocalName = child.getQName().getLocalName();
             if (dataChildQNname == null) {
                 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
@@ -172,15 +194,6 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
         return new SimpleEntry<>(identifier, proxy);
     }
 
-    /**
-     * Returns resolved case schema for supplied class.
-     *
-     * @param schema Resolved parent choice schema
-     * @param childClass Class representing case.
-     * @return Optionally a resolved case schema,.empty if the choice is not legal in
-     *         the given context.
-     * @throws IllegalArgumentException If supplied class does not represent case.
-     */
     @Override
     public final Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema,
             final Class<?> childClass) {
@@ -196,20 +209,9 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
         return findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
     }
 
-    /**
-     * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
-     * from which supplied class was generated. Returned schema may be augmented with
-     * additional information, which was not available at compile type
-     * (e.g. third party augmentations).
-     *
-     * @param type Binding Class for which schema should be retrieved.
-     * @return Instance of generated type (definition of Java API), along with
-     *     {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
-     *     which was used to generate supplied class.
-     */
     @Override
     public final Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
-        return getTypeWithSchema(getTypes(), DefaultType.of(type));
+        return getTypeWithSchema(getTypes(), Type.of(type));
     }
 
     private static @NonNull Entry<GeneratedType, WithStatus> getTypeWithSchema(final BindingRuntimeTypes types,
@@ -258,11 +260,11 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
 
     @Override
     public final Set<Class<?>> getCases(final Class<?> choice) {
-        final Collection<Type> cazes = getTypes().findCases(DefaultType.of(choice));
+        final Collection<Type> cazes = getTypes().findCases(Type.of(choice));
         final Set<Class<?>> ret = new HashSet<>(cazes.size());
         for (final Type caze : cazes) {
             try {
-                ret.add(getStrategy().loadClass(caze));
+                ret.add(loadClass(caze));
             } catch (final ClassNotFoundException e) {
                 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
             }
@@ -278,7 +280,7 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
             childSchema, origSchema);
 
         try {
-            return getStrategy().loadClass(clazzType.get());
+            return loadClass(clazzType.get());
         } catch (final ClassNotFoundException e) {
             throw new IllegalStateException(e);
         }
@@ -287,8 +289,8 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
     @Override
     public final ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(
             final DataNodeContainer container) {
-        final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
         if (container instanceof AugmentationTarget) {
+            final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
             final BindingRuntimeTypes types = getTypes();
             for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) {
                 // Augmentation must have child nodes if is to be used with Binding classes
@@ -304,9 +306,10 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
                     }
                 }
             }
+            return ImmutableMap.copyOf(identifierToType);
         }
 
-        return ImmutableMap.copyOf(identifierToType);
+        return ImmutableMap.of();
     }
 
     @Override
@@ -340,7 +343,7 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
 
     private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
         @SuppressWarnings("unchecked")
-        final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
+        final T original = (T) originalNodeOf(choice);
         if (original != null) {
             return original;
         }
@@ -354,7 +357,7 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
             return Optional.of(potential);
         }
         if (potential != null) {
-            SchemaNode potentialRoot = SchemaNodeUtils.getRootOriginalIfPossible(potential);
+            SchemaNode potentialRoot = originalNodeOf(potential);
             if (originalDefinition.equals(potentialRoot)) {
                 return Optional.of(potential);
             }
@@ -370,10 +373,14 @@ public abstract class AbstractBindingRuntimeContext implements BindingRuntimeCon
         // sufficient to uniquelly determine equality of cases
         //
         for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
-            if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(caze))) {
+            if (originalDefinition.equals(originalNodeOf(caze))) {
                 return Optional.of(caze);
             }
         }
         return Optional.empty();
     }
+
+    private static @Nullable SchemaNode originalNodeOf(final SchemaNode node) {
+        return node instanceof DerivableSchemaNode ? ((DerivableSchemaNode) node).getOriginal().orElse(null) : null;
+    }
 }