Modernize dom-codec-api a bit
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / BindingCodecContext.java
index dde78fa3d4dab5cd55196b92518cd4e557d981d6..dd108c2c818d5d33ac99510d1352706575341df9 100644 (file)
@@ -16,6 +16,7 @@ import com.google.common.base.Strings;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.io.File;
@@ -29,7 +30,6 @@ import java.time.Instant;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
@@ -39,11 +39,13 @@ import java.util.concurrent.ExecutionException;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
 import org.kohsuke.MetaInfServices;
+import org.opendaylight.mdsal.binding.dom.codec.api.BindingAugmentationCodecTreeNode;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeNode;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingInstanceIdentifierCodec;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeWriterFactory;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingStreamEventWriter;
+import org.opendaylight.mdsal.binding.dom.codec.api.CommonDataObjectCodecTreeNode;
 import org.opendaylight.mdsal.binding.dom.codec.impl.NodeCodecContext.CodecContextFactory;
 import org.opendaylight.mdsal.binding.dom.codec.spi.AbstractBindingNormalizedNodeSerializer;
 import org.opendaylight.mdsal.binding.dom.codec.spi.BindingDOMCodecServices;
@@ -56,6 +58,7 @@ import org.opendaylight.yangtools.concepts.Delegator;
 import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.util.ClassLoaderUtils;
 import org.opendaylight.yangtools.yang.binding.Action;
+import org.opendaylight.yangtools.yang.binding.Augmentation;
 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
 import org.opendaylight.yangtools.yang.binding.BaseNotification;
 import org.opendaylight.yangtools.yang.binding.DataContainer;
@@ -70,6 +73,7 @@ import org.opendaylight.yangtools.yang.binding.RpcInput;
 import org.opendaylight.yangtools.yang.binding.RpcOutput;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
@@ -79,7 +83,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.data.api.schema.ValueNode;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
-import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
+import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -120,6 +124,7 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
     }
 
     private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
+    private static final @NonNull NodeIdentifier FAKE_NODEID = new NodeIdentifier(QName.create("fake", "fake"));
     private static final File BYTECODE_DIRECTORY;
 
     static {
@@ -150,7 +155,7 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
     private final @NonNull InstanceIdentifierCodec instanceIdentifierCodec;
     private final @NonNull IdentityCodec identityCodec;
     private final @NonNull BindingRuntimeContext context;
-    private final SchemaRootCodecContext<?> root;
+    private final @NonNull SchemaRootCodecContext<?> root;
 
     public BindingCodecContext() {
         this(ServiceLoader.load(BindingRuntimeContext.class).findFirst()
@@ -159,7 +164,7 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
 
     public BindingCodecContext(final BindingRuntimeContext context) {
         this.context = requireNonNull(context, "Binding Runtime Context is required.");
-        root = SchemaRootCodecContext.create(this);
+        root = new SchemaRootCodecContext<>(this);
         identityCodec = new IdentityCodec(context);
         instanceIdentifierCodec = new InstanceIdentifierCodec(this);
     }
@@ -202,9 +207,9 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
     @Override
     public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriterAndIdentifier(
             final InstanceIdentifier<?> path, final NormalizedNodeStreamWriter domWriter) {
-        final List<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
-        final DataContainerCodecContext<?,?> codecContext = getCodecContextNode(path, yangArgs);
-        return Map.entry(YangInstanceIdentifier.create(yangArgs),
+        final var yangArgs = new ArrayList<YangInstanceIdentifier.PathArgument>();
+        final var codecContext = getCodecContextNode(path, yangArgs);
+        return Map.entry(YangInstanceIdentifier.of(yangArgs),
             new BindingToNormalizedStreamWriter(codecContext, domWriter));
     }
 
@@ -238,14 +243,18 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
         return new BindingToNormalizedStreamWriter(getActionCodec(action).output(), domWriter);
     }
 
-    DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
+    @NonNull DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
             final List<YangInstanceIdentifier.PathArgument> builder) {
-        DataContainerCodecContext<?,?> currentNode = root;
-        for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
-            currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
-            checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.", binding);
+        DataContainerCodecContext<?, ?> current = root;
+        for (var bindingArg : binding.getPathArguments()) {
+            final var next = current.bindingPathArgumentChild(bindingArg, builder);
+            if (next == null) {
+                throw new IllegalArgumentException("%s is not valid: parent %s does not have a child %s".formatted(
+                    binding, current.bindingArg(), bindingArg));
+            }
+            current = next;
         }
-        return currentNode;
+        return current;
     }
 
     /**
@@ -265,11 +274,23 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
         NodeCodecContext currentNode = root;
         ListNodeCodecContext<?> currentList = null;
 
-        for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
+        for (var domArg : dom.getPathArguments()) {
             checkArgument(currentNode instanceof DataContainerCodecContext,
                 "Unexpected child of non-container node %s", currentNode);
-            final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?, ?>) currentNode;
-            final NodeCodecContext nextNode = previous.yangPathArgumentChild(domArg);
+            final var previous = (DataContainerCodecContext<?, ?>) currentNode;
+            var nextNode = previous.yangPathArgumentChild(domArg);
+
+            /**
+             * Compatibility case: if it's determined the node belongs to augmentation
+             * then insert augmentation path argument in between.
+             */
+            if (nextNode instanceof AugmentationNodeContext<?> augmContext) {
+                if (bindingArguments != null) {
+                    bindingArguments.add(augmContext.bindingArg());
+                }
+                currentNode = nextNode;
+                nextNode = augmContext.yangPathArgumentChild(domArg);
+            }
 
             /*
              * List representation in YANG Instance Identifier consists of two
@@ -290,17 +311,17 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
                 }
                 currentList = null;
                 currentNode = nextNode;
-            } else if (nextNode instanceof ListNodeCodecContext) {
+            } else if (nextNode instanceof ListNodeCodecContext<?> listNode) {
                 // We enter list, we do not update current Node yet,
                 // since we need to verify
-                currentList = (ListNodeCodecContext<?>) nextNode;
+                currentList = listNode;
             } else if (nextNode instanceof ChoiceNodeCodecContext) {
                 // We do not add path argument for choice, since
                 // it is not supported by binding instance identifier.
                 currentNode = nextNode;
-            } else if (nextNode instanceof DataContainerCodecContext) {
+            } else if (nextNode instanceof DataContainerCodecContext<?, ?> containerNode) {
                 if (bindingArguments != null) {
-                    bindingArguments.add(((DataContainerCodecContext<?, ?>) nextNode).getBindingPathArgument(domArg));
+                    bindingArguments.add(containerNode.getBindingPathArgument(domArg));
                 }
                 currentNode = nextNode;
             } else if (nextNode instanceof ValueNodeCodecContext) {
@@ -349,14 +370,14 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
     @Override
     public ImmutableMap<Method, ValueNodeCodecContext> getLeafNodes(final Class<?> type,
             final EffectiveStatement<?, ?> schema) {
-        final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
+        final var getterToLeafSchema = new HashMap<String, DataSchemaNode>();
         for (var stmt : schema.effectiveSubstatements()) {
-            if (stmt instanceof TypedDataSchemaNode) {
-                putLeaf(getterToLeafSchema, (TypedDataSchemaNode) stmt);
-            } else if (stmt instanceof AnydataSchemaNode) {
-                putLeaf(getterToLeafSchema, (AnydataSchemaNode) stmt);
-            } else if (stmt instanceof AnyxmlSchemaNode) {
-                putLeaf(getterToLeafSchema, (AnyxmlSchemaNode) stmt);
+            if (stmt instanceof TypedDataSchemaNode typedSchema) {
+                putLeaf(getterToLeafSchema, typedSchema);
+            } else if (stmt instanceof AnydataSchemaNode anydataSchema) {
+                putLeaf(getterToLeafSchema, anydataSchema);
+            } else if (stmt instanceof AnyxmlSchemaNode anyxmlSchema) {
+                putLeaf(getterToLeafSchema, anyxmlSchema);
             }
         }
         return getLeafNodesUsingReflection(type, getterToLeafSchema);
@@ -368,8 +389,8 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
 
     private ImmutableMap<Method, ValueNodeCodecContext> getLeafNodesUsingReflection(
             final Class<?> parentClass, final Map<String, DataSchemaNode> getterToLeafSchema) {
-        final Map<Method, ValueNodeCodecContext> leaves = new HashMap<>();
-        for (final Method method : parentClass.getMethods()) {
+        final var leaves = new HashMap<Method, ValueNodeCodecContext>();
+        for (var method : parentClass.getMethods()) {
             // Only consider non-bridge methods with no arguments
             if (method.getParameterCount() == 0 && !method.isBridge()) {
                 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
@@ -382,7 +403,7 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
                     final ValueCodec<Object, Object> codec = getCodec(valueType, leafSchema.getType());
                     valueNode = LeafNodeCodecContext.of(leafSchema, codec, method.getName(), valueType,
                         context.getEffectiveModelContext());
-                } else if (schema instanceof LeafListSchemaNode) {
+                } else if (schema instanceof LeafListSchemaNode leafListSchema) {
                     final Optional<Type> optType = ClassLoaderUtils.getFirstGenericParameter(
                         method.getGenericReturnType());
                     checkState(optType.isPresent(), "Failed to find return type for %s", method);
@@ -400,14 +421,13 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
                         throw new IllegalStateException("Unexpected return type " + genericType);
                     }
 
-                    final LeafListSchemaNode leafListSchema = (LeafListSchemaNode) schema;
                     final ValueCodec<Object, Object> codec = getCodec(valueType, leafListSchema.getType());
                     valueNode = new LeafSetNodeCodecContext(leafListSchema, codec, method.getName());
-                } else if (schema instanceof AnyxmlSchemaNode) {
-                    valueNode = new OpaqueNodeCodecContext.Anyxml<>((AnyxmlSchemaNode) schema, method.getName(),
+                } else if (schema instanceof AnyxmlSchemaNode anyxmlSchema) {
+                    valueNode = new OpaqueNodeCodecContext.Anyxml<>(anyxmlSchema, method.getName(),
                             opaqueReturnType(method), loader);
-                } else if (schema instanceof AnydataSchemaNode) {
-                    valueNode = new OpaqueNodeCodecContext.Anydata<>((AnydataSchemaNode) schema, method.getName(),
+                } else if (schema instanceof AnydataSchemaNode anydataSchema) {
+                    valueNode = new OpaqueNodeCodecContext.Anydata<>(anydataSchema, method.getName(),
                             opaqueReturnType(method), loader);
                 } else {
                     verify(schema == null, "Unhandled schema %s for method %s", schema, method);
@@ -447,9 +467,9 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
             return new CompositeValueCodec.OfIdentity(valueType, identityCodec);
         } else if (typeDef instanceof InstanceIdentifierTypeDefinition) {
             return new CompositeValueCodec.OfInstanceIdentifier(valueType, instanceIdentifierCodec);
-        } else if (typeDef instanceof UnionTypeDefinition) {
+        } else if (typeDef instanceof UnionTypeDefinition unionType) {
             try {
-                return UnionTypeCodec.of(valueType, (UnionTypeDefinition) typeDef, this);
+                return UnionTypeCodec.of(valueType, unionType, this);
             } catch (Exception e) {
                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
             }
@@ -457,10 +477,10 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
             final var typeWithSchema = context.getTypeWithSchema(valueType);
             final var schema = typeWithSchema.statement();
             final TypeDefinition<?> def;
-            if (schema instanceof TypeDefinitionAware) {
-                def = ((TypeDefinitionAware) schema).getTypeDefinition();
-            } else if (schema instanceof TypeAware) {
-                def = ((TypeAware) schema).getType();
+            if (schema instanceof TypeDefinitionAware typeDefAware) {
+                def = typeDefAware.getTypeDefinition();
+            } else if (schema instanceof TypeAware typeAware) {
+                def = typeAware.getType();
             } else {
                 throw new IllegalStateException("Unexpected schema " + schema);
             }
@@ -485,15 +505,48 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
     }
 
     @Override
-    public <E extends DataObject> BindingDataObjectCodecTreeNode<E> streamChild(final Class<E> childClass) {
+    public <E extends DataObject> CommonDataObjectCodecTreeNode<E> streamChild(final Class<E> childClass) {
         return root.streamChild(childClass);
     }
 
     @Override
     @SuppressWarnings("unchecked")
-    public <T extends DataObject> BindingDataObjectCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
+    public <A extends Augmentation<?>> BindingAugmentationCodecTreeNode<A> getAugmentationCodec(
+            final InstanceIdentifier<A> path) {
+        final var codecContext = getCodecContextNode(path, null);
+        if (codecContext instanceof BindingAugmentationCodecTreeNode) {
+            return (BindingAugmentationCodecTreeNode<A>) codecContext;
+        }
+        throw new IllegalArgumentException(path + " does not refer to an Augmentation");
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public <T extends DataObject> BindingDataObjectCodecTreeNode<T> getDataObjectCodec(
+            final InstanceIdentifier<T> path) {
+        final var codecContext = getCodecContextNode(path, null);
+        if (codecContext instanceof BindingDataObjectCodecTreeNode) {
+            return (BindingDataObjectCodecTreeNode<T>) codecContext;
+        }
+        throw new IllegalArgumentException(path + " does not refer to a plain DataObject");
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public <T extends DataObject> CodecWithPath<T> getSubtreeCodecWithPath(final InstanceIdentifier<T> path) {
+        final var yangArgs = new ArrayList<YangInstanceIdentifier.PathArgument>();
+        final var codecContext = getCodecContextNode(path, yangArgs);
+
         // TODO Do we need defensive check here?
-        return (BindingDataObjectCodecTreeNode<T>) getCodecContextNode(path, null);
+        return new CodecWithPath<>((CommonDataObjectCodecTreeNode<T>) codecContext,
+            YangInstanceIdentifier.of(yangArgs));
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public <T extends DataObject> CommonDataObjectCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
+        // TODO Do we need defensive check here?
+        return (CommonDataObjectCodecTreeNode<T>) getCodecContextNode(path, null);
     }
 
     @Override
@@ -517,24 +570,62 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
     }
 
     @Override
-    public <T extends DataObject> Entry<YangInstanceIdentifier, NormalizedNode> toNormalizedNode(
-            final InstanceIdentifier<T> path, final T data) {
-        final NormalizedNodeResult result = new NormalizedNodeResult();
-        // We create DOM stream writer which produces normalized nodes
-        final NormalizedNodeStreamWriter domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
+    public <A extends Augmentation<?>> AugmentationResult toNormalizedAugmentation(final InstanceIdentifier<A> path,
+            final A data) {
+        final var result = toNormalizedNode(path, data);
+        if (result instanceof AugmentationResult augment) {
+            return augment;
+        }
+        throw new IllegalArgumentException(path + " does not identify an Augmentation");
+    }
+
+    @Override
+    public <T extends DataObject> NodeResult toNormalizedDataObject(final InstanceIdentifier<T> path, final T data) {
+        final var result = toNormalizedNode(path, data);
+        if (result instanceof NodeResult node) {
+            return node;
+        }
+        throw new IllegalArgumentException(path + " does not identify a plain DataObject");
+    }
 
+    @Override
+    public <T extends DataObject> NormalizedResult toNormalizedNode(final InstanceIdentifier<T> path, final T data) {
         // We create Binding Stream Writer which translates from Binding to Normalized Nodes
-        final Entry<YangInstanceIdentifier, BindingStreamEventWriter> writeCtx = newWriterAndIdentifier(path,
-            domWriter);
+        final var yangArgs = new ArrayList<YangInstanceIdentifier.PathArgument>();
+        final var codecContext = getCodecContextNode(path, yangArgs);
+        final var yangPath = YangInstanceIdentifier.of(yangArgs);
+
+        // We create DOM stream writer which produces normalized nodes
+        final var result = new NormalizationResultHolder();
+        final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
+        final var bindingWriter = new BindingToNormalizedStreamWriter(codecContext, domWriter);
+        final var augment = codecContext instanceof BindingAugmentationCodecTreeNode<?> augmentNode ? augmentNode
+            : null;
 
-        // We get serializer which reads binding data and uses Binding To Normalized Node writer to write result
         try {
-            getSerializer(path.getTargetType()).serialize(data, writeCtx.getValue());
+            // Augmentations do not have a representation, so we are faking a ContainerNode as the parent and we will be
+            // extracting the resulting children.
+            if (augment != null) {
+                domWriter.startContainerNode(FAKE_NODEID, NormalizedNodeStreamWriter.UNKNOWN_SIZE);
+            }
+
+            // We get serializer which reads binding data and uses Binding To Normalized Node writer to write result
+            getSerializer(path.getTargetType()).serialize(data, bindingWriter);
+
+            if (augment != null) {
+                domWriter.endNode();
+            }
         } catch (final IOException e) {
             LOG.error("Unexpected failure while serializing path {} data {}", path, data, e);
             throw new IllegalStateException("Failed to create normalized node", e);
         }
-        return Map.entry(writeCtx.getKey(), result.getResult());
+
+        // Terminate the fake container and extract it to the result
+        if (augment != null) {
+            return new AugmentationResult(yangPath, augment.childPathArguments(),
+                ImmutableList.copyOf(((ContainerNode) result.getResult().data()).body()));
+        }
+        return new NodeResult(yangPath, result.getResult().data());
     }
 
     @Override
@@ -629,9 +720,9 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
 
     private <T extends DataContainer> @NonNull ContainerNode serializeDataObject(final DataObject data,
             final WriterFactoryMethod<T> newWriter) {
-        final NormalizedNodeResult result = new NormalizedNodeResult();
+        final var result = new NormalizationResultHolder();
         // We create DOM stream writer which produces normalized nodes
-        final NormalizedNodeStreamWriter domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
+        final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
         final Class<? extends DataObject> type = data.implementedInterface();
         @SuppressWarnings("unchecked")
         final BindingStreamEventWriter writer = newWriter.createWriter(this, (Class<T>) type, domWriter);
@@ -641,16 +732,16 @@ public final class BindingCodecContext extends AbstractBindingNormalizedNodeSeri
             LOG.error("Unexpected failure while serializing data {}", data, e);
             throw new IllegalStateException("Failed to create normalized node", e);
         }
-        return (ContainerNode) result.getResult();
+        return (ContainerNode) result.getResult().data();
     }
 
 
     private static boolean notBindingRepresentable(final NormalizedNode data) {
         // ValueNode covers LeafNode and LeafSetEntryNode
         return data instanceof ValueNode
-                || data instanceof MapNode || data instanceof UnkeyedListNode
-                || data instanceof ChoiceNode
-                || data instanceof LeafSetNode;
+            || data instanceof MapNode || data instanceof UnkeyedListNode
+            || data instanceof ChoiceNode
+            || data instanceof LeafSetNode;
     }
 
     @SuppressWarnings("rawtypes")