Modernize ChoiceNodeCodecContext
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / ChoiceNodeCodecContext.java
index 6100d4db209e08b715689758243ce6da79fef5f3..639e2dc5f760d8d37fb88eca707b106cfbcec2c8 100644 (file)
@@ -9,42 +9,40 @@ package org.opendaylight.mdsal.binding.dom.codec.impl;
 
 import static com.google.common.base.Preconditions.checkArgument;
 
+import com.google.common.collect.ImmutableCollection;
 import com.google.common.collect.ImmutableListMultimap;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableMap.Builder;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.MultimapBuilder.SetMultimapBuilder;
 import com.google.common.collect.Multimaps;
-import com.google.common.collect.SetMultimap;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.util.ArrayList;
 import java.util.Comparator;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
+import java.util.LinkedList;
 import java.util.Optional;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
 import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
+import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
+import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
 import org.opendaylight.mdsal.binding.runtime.api.CaseRuntimeType;
 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
-import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
+import org.opendaylight.yangtools.yang.binding.BindingObject;
+import org.opendaylight.yangtools.yang.binding.DataContainer;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.binding.contract.Naming;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
-import org.opendaylight.yangtools.yang.data.util.NormalizedNodeSchemaUtils;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
 import org.slf4j.Logger;
@@ -97,10 +95,11 @@ import org.slf4j.LoggerFactory;
  * ambiguous reference and issue warn once when they are encountered -- tracking warning information in
  * {@link #ambiguousByCaseChildWarnings}.
  */
-final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D, ChoiceRuntimeType> {
+final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D, ChoiceRuntimeType>
+        implements BindingDataObjectCodecTreeNode<D> {
     private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
 
-    private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChild;
+    private final ImmutableMap<NodeIdentifier, DataContainerCodecPrototype<?>> byYangCaseChild;
     private final ImmutableListMultimap<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseChildClass;
     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClass;
     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byClass;
@@ -108,68 +107,47 @@ final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCo
 
     ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceRuntimeType> prototype) {
         super(prototype);
-        final Map<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChildBuilder =
-            new HashMap<>();
-        final Map<Class<?>, DataContainerCodecPrototype<?>> byClassBuilder = new HashMap<>();
-        final SetMultimap<Class<?>, DataContainerCodecPrototype<?>> childToCase =
-            SetMultimapBuilder.hashKeys().hashSetValues().build();
-        final Set<Class<?>> potentialSubstitutions = new HashSet<>();
-        // Walks all cases for supplied choice in current runtime context
-        // FIXME: 9.0.0: factory short-circuits to prototype, just as getBindingClass() does
-        for (final Class<?> caze : loadCaseClasses()) {
-            // We try to load case using exact match thus name
-            // and original schema must equals
-            final DataContainerCodecPrototype<CaseRuntimeType> cazeDef = loadCase(caze);
-            // If we have case definition, this case is instantiated
-            // at current location and thus is valid in context of parent choice
-            if (cazeDef != null) {
-                byClassBuilder.put(cazeDef.getBindingClass(), cazeDef);
-                // Updates collection of case children
-                @SuppressWarnings("unchecked")
-                final Class<? extends DataObject> cazeCls = (Class<? extends DataObject>) caze;
-                for (final Class<? extends DataObject> cazeChild : BindingReflections.getChildrenClasses(cazeCls)) {
-                    childToCase.put(cazeChild, cazeDef);
-                }
-                // Updates collection of YANG instance identifier to case
-                for (var stmt : cazeDef.getType().statement().effectiveSubstatements()) {
-                    if (stmt instanceof DataSchemaNode) {
-                        final DataSchemaNode cazeChild = (DataSchemaNode) stmt;
-                        if (cazeChild.isAugmenting()) {
-                            final AugmentationSchemaNode augment = NormalizedNodeSchemaUtils.findCorrespondingAugment(
-                                // FIXME: bad cast
-                                (DataSchemaNode) cazeDef.getType().statement(), cazeChild);
-                            if (augment != null) {
-                                byYangCaseChildBuilder.put(DataSchemaContextNode.augmentationIdentifierFrom(augment),
-                                    cazeDef);
-                                continue;
-                            }
-                        }
-                        byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), cazeDef);
-                    }
+        final var byYangCaseChildBuilder = new HashMap<NodeIdentifier, DataContainerCodecPrototype<?>>();
+        final var byClassBuilder = new HashMap<Class<?>, DataContainerCodecPrototype<?>>();
+        final var childToCase = SetMultimapBuilder.hashKeys().hashSetValues()
+            .<Class<?>, DataContainerCodecPrototype<?>>build();
+
+        // Load case statements valid in this choice and keep track of their names
+        final var choiceType = prototype.getType();
+        final var factory = prototype.getFactory();
+        final var localCases = new HashSet<JavaTypeName>();
+        for (var caseType : choiceType.validCaseChildren()) {
+            final var cazeDef = loadCase(factory, caseType);
+            localCases.add(caseType.getIdentifier());
+            byClassBuilder.put(cazeDef.getBindingClass(), cazeDef);
+
+            // Updates collection of case children
+            @SuppressWarnings("unchecked")
+            final var cazeCls = (Class<? extends DataObject>) cazeDef.getBindingClass();
+            for (var cazeChild : getChildrenClasses(cazeCls)) {
+                childToCase.put(cazeChild, cazeDef);
+            }
+            // Updates collection of YANG instance identifier to case
+            for (var stmt : cazeDef.getType().statement().effectiveSubstatements()) {
+                if (stmt instanceof DataSchemaNode cazeChild) {
+                    byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), cazeDef);
                 }
-            } else {
-                /*
-                 * If case definition is not available, we store it for
-                 * later check if it could be used as substitution of existing one.
-                 */
-                potentialSubstitutions.add(caze);
             }
         }
         byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder);
 
         // Move unambiguous child->case mappings to byCaseChildClass, removing them from childToCase
-        final ImmutableListMultimap.Builder<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseBuilder =
-                ImmutableListMultimap.builder();
-        final Builder<Class<?>, DataContainerCodecPrototype<?>> unambiguousByCaseBuilder = ImmutableMap.builder();
-        for (Entry<Class<?>, Set<DataContainerCodecPrototype<?>>> e : Multimaps.asMap(childToCase).entrySet()) {
-            final Set<DataContainerCodecPrototype<?>> cases = e.getValue();
+        final var ambiguousByCaseBuilder = ImmutableListMultimap.<Class<?>, DataContainerCodecPrototype<?>>builder();
+        final var unambiguousByCaseBuilder = ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builder();
+        for (var entry : Multimaps.asMap(childToCase).entrySet()) {
+            final var cases = entry.getValue();
             if (cases.size() != 1) {
                 // Sort all possibilities by their FQCN to retain semi-predictable results
-                final List<DataContainerCodecPrototype<?>> list = new ArrayList<>(e.getValue());
+                final var list = new ArrayList<>(entry.getValue());
                 list.sort(Comparator.comparing(proto -> proto.getBindingClass().getCanonicalName()));
-                ambiguousByCaseBuilder.putAll(e.getKey(), list);
+                ambiguousByCaseBuilder.putAll(entry.getKey(), list);
             } else {
-                unambiguousByCaseBuilder.put(e.getKey(), cases.iterator().next());
+                unambiguousByCaseBuilder.put(entry.getKey(), cases.iterator().next());
             }
         }
         byCaseChildClass = unambiguousByCaseBuilder.build();
@@ -179,40 +157,49 @@ final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCo
         ambiguousByCaseChildWarnings = ambiguousByCaseChildClass.isEmpty() ? ImmutableSet.of()
                 : ConcurrentHashMap.newKeySet();
 
-        final Map<Class<?>, DataContainerCodecPrototype<?>> bySubstitutionBuilder = new HashMap<>();
         /*
-         * Walks all cases which are not directly instantiated and
-         * tries to match them to instantiated cases - represent same data as instantiated case,
-         * only case name or schema path is different. This is required due property of
-         * binding specification, that if choice is in grouping schema path location is lost,
-         * and users may use incorrect case class using copy builders.
+         * Choice/Case mapping across groupings is compile-time unsafe and we therefore need to also track any
+         * CaseRuntimeTypes added to the choice in other contexts. This is necessary to discover when a case represents
+         * equivalent data in a different instantiation context.
+         *
+         * This is required due property of binding specification, that if choice is in grouping schema path location is
+         * lost, and users may use incorrect case class using copy builders.
          */
-        for (final Class<?> substitution : potentialSubstitutions) {
-            search: for (final Entry<Class<?>, DataContainerCodecPrototype<?>> real : byClassBuilder.entrySet()) {
-                if (BindingReflections.isSubstitutionFor(substitution, real.getKey())) {
-                    bySubstitutionBuilder.put(substitution, real.getValue());
-                    break search;
+        final var bySubstitutionBuilder = new HashMap<Class<?>, DataContainerCodecPrototype<?>>();
+        final var context = factory.getRuntimeContext();
+        for (var caseType : context.getTypes().allCaseChildren(choiceType)) {
+            final var caseName = caseType.getIdentifier();
+            if (!localCases.contains(caseName)) {
+                // FIXME: do not rely on class loading here, the check we are performing should be possible on
+                //        GeneratedType only -- or it can be provided by BindingRuntimeTypes -- i.e. rather than
+                //        'allCaseChildren()' it would calculate additional mappings we can use off-the-bat.
+                final var substitution = loadCase(context, caseType);
+
+                search: for (var real : byClassBuilder.entrySet()) {
+                    if (isSubstitutionFor(substitution, real.getKey())) {
+                        bySubstitutionBuilder.put(substitution, real.getValue());
+                        break search;
+                    }
                 }
             }
         }
+
         byClassBuilder.putAll(bySubstitutionBuilder);
         byClass = ImmutableMap.copyOf(byClassBuilder);
     }
 
-    private List<Class<?>> loadCaseClasses() {
-        final var context = factory().getRuntimeContext();
-        final var type = getType();
+    private static DataContainerCodecPrototype<CaseRuntimeType> loadCase(final CodecContextFactory factory,
+            final CaseRuntimeType caseType) {
+        return DataContainerCodecPrototype.from(loadCase(factory.getRuntimeContext(), caseType), caseType, factory);
+    }
 
-        return Stream.concat(type.validCaseChildren().stream(), type.additionalCaseChildren().stream())
-            .map(caseChild -> {
-                final var caseName = caseChild.getIdentifier();
-                try {
-                    return context.loadClass(caseName);
-                } catch (ClassNotFoundException e) {
-                    throw new IllegalStateException("Failed to load class for " + caseName, e);
-                }
-            })
-            .collect(Collectors.toUnmodifiableList());
+    private static Class<?> loadCase(final BindingRuntimeContext context, final CaseRuntimeType caseType) {
+        final var className = caseType.getIdentifier();
+        try {
+            return context.loadClass(className);
+        } catch (ClassNotFoundException e) {
+            throw new LinkageError("Failed to load class for " + className, e);
+        }
     }
 
     @Override
@@ -224,7 +211,7 @@ final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCo
     @SuppressWarnings("unchecked")
     @Override
     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
-        final DataContainerCodecPrototype<?> child = byClass.get(childClass);
+        final var child = byClass.get(childClass);
         return (DataContainerCodecContext<C, ?>) childNonNull(child, childClass,
             "Supplied class %s is not valid case in %s", childClass, bindingArg()).get();
     }
@@ -233,7 +220,7 @@ final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCo
     @Override
     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
             final Class<C> childClass) {
-        final DataContainerCodecPrototype<?> child = byClass.get(childClass);
+        final var child = byClass.get(childClass);
         if (child != null) {
             return Optional.of((DataContainerCodecContext<C, ?>) child.get());
         }
@@ -244,20 +231,10 @@ final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCo
         return Iterables.concat(byCaseChildClass.keySet(), ambiguousByCaseChildClass.keySet());
     }
 
-    protected DataContainerCodecPrototype<CaseRuntimeType> loadCase(final Class<?> childClass) {
-        final var child = getType().bindingCaseChild(JavaTypeName.create(childClass));
-        if (child == null) {
-            LOG.debug("Supplied class {} is not valid case in schema {}", childClass, getSchema());
-            return null;
-        }
-
-        return DataContainerCodecPrototype.from(childClass, child, factory());
-    }
-
     @Override
     public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
         final DataContainerCodecPrototype<?> cazeProto;
-        if (arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
+        if (arg instanceof NodeIdentifierWithPredicates) {
             cazeProto = byYangCaseChild.get(new NodeIdentifier(arg.getNodeType()));
         } else {
             cazeProto = byYangCaseChild.get(arg);
@@ -271,16 +248,20 @@ final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCo
     @SuppressWarnings("unchecked")
     @SuppressFBWarnings(value = "NP_NONNULL_RETURN_VIOLATION", justification = "See FIXME below")
     public D deserialize(final NormalizedNode data) {
-        checkArgument(data instanceof ChoiceNode);
-        final ChoiceNode casted = (ChoiceNode) data;
-        final NormalizedNode first = Iterables.getFirst(casted.body(), null);
+        final var casted = checkDataArgument(ChoiceNode.class, data);
+        final var first = Iterables.getFirst(casted.body(), null);
 
         if (first == null) {
             // FIXME: this needs to be sorted out
             return null;
         }
-        final DataContainerCodecPrototype<?> caze = byYangCaseChild.get(first.getIdentifier());
-        return (D) caze.get().deserialize(data);
+        final var caze = byYangCaseChild.get(first.name());
+        return (D) caze.getDataObject().deserialize(data);
+    }
+
+    @Override
+    public NormalizedNode serialize(final D data) {
+        return serializeImpl(data);
     }
 
     @Override
@@ -300,24 +281,53 @@ final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCo
         return getDomPathArgument();
     }
 
+    @Override
+    public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
+            final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
+        return createCachingCodec(this, cacheSpecifier);
+    }
+
     DataContainerCodecContext<?, ?> getCaseByChildClass(final @NonNull Class<? extends DataObject> type) {
-        DataContainerCodecPrototype<?> result = byCaseChildClass.get(type);
+        var result = byCaseChildClass.get(type);
         if (result == null) {
             // We have not found an unambiguous result, try ambiguous ones
-            final List<DataContainerCodecPrototype<?>> inexact = ambiguousByCaseChildClass.get(type);
+            final var inexact = ambiguousByCaseChildClass.get(type);
             if (!inexact.isEmpty()) {
                 result = inexact.get(0);
                 // Issue a warning, but only once so as not to flood the logs
                 if (ambiguousByCaseChildWarnings.add(type)) {
-                    LOG.warn("Ambiguous reference {} to child of {} resolved to {}, the first case in {} This mapping "
-                            + "is not guaranteed to be stable and is subject to variations based on runtime "
-                            + "circumstances. Please see the stack trace for hints about the source of ambiguity.",
-                            type, bindingArg(), result.getBindingClass(),
-                            Lists.transform(inexact, DataContainerCodecPrototype::getBindingClass), new Throwable());
+                    LOG.warn("""
+                        Ambiguous reference {} to child of {} resolved to {}, the first case in {} This mapping is \
+                        not guaranteed to be stable and is subject to variations based on runtime circumstances. \
+                        Please see the stack trace for hints about the source of ambiguity.""",
+                        type, bindingArg(), result.getBindingClass(),
+                        Lists.transform(inexact, DataContainerCodecPrototype::getBindingClass), new Throwable());
                 }
             }
         }
 
         return childNonNull(result, type, "Class %s is not child of any cases for %s", type, bindingArg()).get();
     }
+
+    /**
+     * 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
+     */
+    // FIXME: MDSAL-780: replace use of this method
+    @SuppressWarnings("unchecked")
+    private 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");
+        final var ret = new LinkedList<Class<? extends DataObject>>();
+        for (var method : type.getMethods()) {
+            final var entity = getYangModeledReturnType(method, Naming.GETTER_PREFIX);
+            if (entity.isPresent()) {
+                ret.add((Class<? extends DataObject>) entity.orElseThrow());
+            }
+        }
+        return ret;
+    }
 }