Mark DataContainerCodecPrototype.isChoice() for removal
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / DataObjectCodecContext.java
index 73fa12e6ed816d7cd6fbe4f5c8a67b74f9d57f20..fd1c2eea8bd9ee66a94922fbd777e740d8f4c5d6 100644 (file)
@@ -17,6 +17,7 @@ import com.google.common.collect.ImmutableMap.Builder;
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
 import java.lang.invoke.MethodType;
+import java.lang.invoke.VarHandle;
 import java.lang.reflect.Method;
 import java.util.HashMap;
 import java.util.List;
@@ -26,30 +27,28 @@ import java.util.Optional;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
-import org.opendaylight.mdsal.binding.model.api.DefaultType;
 import org.opendaylight.mdsal.binding.model.api.Type;
 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
 import org.opendaylight.yangtools.yang.binding.Augmentable;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
+import org.opendaylight.yangtools.yang.binding.DataContainer;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
 import org.opendaylight.yangtools.yang.binding.OpaqueObject;
-import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 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.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
+import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
-import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -61,9 +60,19 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
         extends DataContainerCodecContext<D, T> {
     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
-        DataObjectCodecContext.class, NormalizedNodeContainer.class);
+        DataObjectCodecContext.class, DistinctNodeContainer.class);
     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
-        DataObjectCodecContext.class, NormalizedNodeContainer.class);
+        DataObjectCodecContext.class, DistinctNodeContainer.class);
+    private static final VarHandle MISMATCHED_AUGMENTED;
+
+    static {
+        try {
+            MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
+                "mismatchedAugmented", ImmutableMap.class);
+        } catch (NoSuchFieldException | IllegalAccessException e) {
+            throw new ExceptionInInitializerError(e);
+        }
+    }
 
     private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
@@ -75,7 +84,8 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
     private final MethodHandle proxyConstructor;
 
     // Note this the content of this field depends only of invariants expressed as this class's fields or
-    // BindingRuntimeContext.
+    // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
+    @SuppressWarnings("unused")
     private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
 
     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
@@ -88,7 +98,8 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
         final Class<D> bindingClass = getBindingClass();
 
         final ImmutableMap<Method, ValueNodeCodecContext> tmpLeaves = factory().getLeafNodes(bindingClass, getSchema());
-        final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
+        final Map<Class<? extends DataContainer>, Method> clsToMethod =
+            BindingReflections.getChildrenClassToMethod(bindingClass);
 
         final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
         final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
@@ -97,28 +108,31 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
         // Adds leaves to mapping
         final Builder<String, ValueNodeCodecContext> leafChildBuilder =
                 ImmutableMap.builderWithExpectedSize(tmpLeaves.size());
-        for (final Entry<Method, ValueNodeCodecContext> entry : tmpLeaves.entrySet()) {
-            final ValueNodeCodecContext leaf = entry.getValue();
+        for (final ValueNodeCodecContext leaf : tmpLeaves.values()) {
             leafChildBuilder.put(leaf.getSchema().getQName().getLocalName(), leaf);
             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
         }
         this.leafChild = leafChildBuilder.build();
 
         final Map<Method, Class<?>> tmpDataObjects = new HashMap<>();
-        for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
+        for (final Entry<Class<? extends DataContainer>, Method> childDataObj : clsToMethod.entrySet()) {
             final Method method = childDataObj.getValue();
             verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
 
-            final Class<?> retClass = childDataObj.getKey();
+            final Class<? extends DataContainer> retClass = childDataObj.getKey();
             if (OpaqueObject.class.isAssignableFrom(retClass)) {
                 // Filter OpaqueObjects, they are not containers
                 continue;
             }
 
             final DataContainerCodecPrototype<?> childProto = loadChildPrototype(retClass);
-            tmpDataObjects.put(method, childProto.getBindingClass());
-            byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
+            final Class<?> childClass = childProto.getBindingClass();
+            tmpDataObjects.put(method, childClass);
+            byStreamClassBuilder.put(childClass, childProto);
             byYangBuilder.put(childProto.getYangArg(), childProto);
+
+            // FIXME: It really feels like we should be specializing DataContainerCodecPrototype so as to ditch
+            //        createInstance() and then we could do an instanceof check instead.
             if (childProto.isChoice()) {
                 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
                 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
@@ -259,46 +273,19 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
         return value;
     }
 
-    private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
-        final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
-        // Direct instantiation or use in same module in which grouping
-        // was defined.
-        DataSchemaNode sameName;
-        try {
-            sameName = getSchema().getDataChildByName(origDef.getQName());
-        } catch (final IllegalArgumentException e) {
-            sameName = null;
-        }
-        final DataSchemaNode childSchema;
-        if (sameName != null) {
-            // Exactly same schema node
-            if (origDef.equals(sameName)) {
-                childSchema = sameName;
-                // We check if instantiated node was added via uses
-                // statement and is instantiation of same grouping
-            } else if (origDef.equals(SchemaNodeUtils.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(namespace());
-            final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
-            // We check if it is really instantiated from same
-            // definition as class was derived
-            if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
-                childSchema = potential;
-            } else {
-                childSchema = null;
-            }
-        }
-        final DataSchemaNode nonNullChild =
-                childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
-        return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
+    private DataContainerCodecPrototype<?> loadChildPrototype(final Class<? extends DataContainer> childClass) {
+        final DataSchemaNode childSchema = childNonNull(
+            factory().getRuntimeContext().findChildSchemaDefinition(getSchema(), namespace(), childClass), childClass,
+            "Node %s does not have child named %s", getSchema(), childClass);
+        return DataContainerCodecPrototype.from(createBindingArg(childClass, childSchema), childSchema, factory());
     }
 
+    // FIXME: MDSAL-697: move this method into BindingRuntimeContext
+    //                   This method is only called from loadChildPrototype() and exists only to be overridden by
+    //                   CaseNodeCodecContext. Since we are providing childClass and our schema to BindingRuntimeContext
+    //                   and receiving childSchema from it via findChildSchemaDefinition, we should be able to receive
+    //                   the equivalent of Map.Entry<Item, DataSchemaNode>, along with the override we create here. One
+    //                   more input we may need to provide is our bindingClass().
     @SuppressWarnings("unchecked")
     Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
         return Item.of((Class<? extends DataObject>) childClass);
@@ -306,20 +293,25 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
 
     private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
         final DataContainerCodecPrototype<?> childProto = augmentationByStream.get(childClass);
-        if (childProto != null) {
-            return childProto;
-        }
+        return childProto != null ? childProto : mismatchedAugmentationByClass(childClass);
+    }
 
+    private @Nullable DataContainerCodecPrototype<?> mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
         /*
          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
          * we'll cache it so we do not need to perform reflection operations again.
          */
-        final DataContainerCodecPrototype<?> mismatched = mismatchedAugmented.get(childClass);
-        if (mismatched != null) {
-            return mismatched;
-        }
+        final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local =
+                (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) MISMATCHED_AUGMENTED.getAcquire(this);
+        final DataContainerCodecPrototype<?> mismatched = local.get(childClass);
+        return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
+
+    }
 
+    private @Nullable DataContainerCodecPrototype<?> loadMismatchedAugmentation(
+            final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
+            final @NonNull Class<?> childClass) {
         @SuppressWarnings("rawtypes")
         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
         // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
@@ -328,7 +320,7 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
             for (final DataContainerCodecPrototype<?> realChild : augmentationByStream.values()) {
                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
-                    return cacheMismatched(childClass, realChild);
+                    return cacheMismatched(oldMismatched, childClass, realChild);
                 }
             }
         }
@@ -336,33 +328,40 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
         return null;
     }
 
-    // TODO: can we ditch this synchronized block?
-    private synchronized DataContainerCodecPrototype<?> cacheMismatched(final Class<?> childClass,
-            final DataContainerCodecPrototype<?> prototype) {
-        // Original access was unsynchronized, we need to perform additional checking
-        final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local = mismatchedAugmented;
-        final DataContainerCodecPrototype<?> existing = local.get(childClass);
-        if (existing != null) {
-            return existing;
-        }
-
-        final Builder<Class<?>, DataContainerCodecPrototype<?>> builder = ImmutableMap.builderWithExpectedSize(
-            local.size() + 1);
-        builder.putAll(local);
-        builder.put(childClass, prototype);
+    private @NonNull DataContainerCodecPrototype<?> cacheMismatched(
+            final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
+            final @NonNull Class<?> childClass, final @NonNull DataContainerCodecPrototype<?> prototype) {
+
+        ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> expected = oldMismatched;
+        while (true) {
+            final Map<Class<?>, DataContainerCodecPrototype<?>> newMismatched =
+                    ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
+                        .putAll(expected)
+                        .put(childClass, prototype)
+                        .build();
+
+            final Object witness = MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
+            if (witness == expected) {
+                LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
+                return prototype;
+            }
 
-        mismatchedAugmented = builder.build();
-        LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
-        return prototype;
+            expected = (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) witness;
+            final DataContainerCodecPrototype<?> existing = expected.get(childClass);
+            if (existing != null) {
+                LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
+                return existing;
+            }
+        }
     }
 
     private boolean belongsToRuntimeContext(final Class<?> cls) {
         final BindingRuntimeContext ctx = factory().getRuntimeContext();
         final Class<?> loaded;
         try {
-            loaded = ctx.loadClass(DefaultType.of(cls));
+            loaded = ctx.loadClass(Type.of(cls));
         } catch (ClassNotFoundException e) {
-            LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx);
+            LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
             return false;
         }
         return cls.equals(loaded);
@@ -384,7 +383,7 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
     }
 
     @SuppressWarnings("checkstyle:illegalCatch")
-    protected final @NonNull D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
+    protected final @NonNull D createBindingProxy(final DistinctNodeContainer<?, ?> node) {
         try {
             return (D) proxyConstructor.invokeExact(this, node);
         } catch (final Throwable e) {
@@ -395,12 +394,12 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
 
     @SuppressWarnings("unchecked")
     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
-            final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
+            final DistinctNodeContainer<PathArgument, NormalizedNode> data) {
 
         @SuppressWarnings("rawtypes")
         final Map map = new HashMap<>();
 
-        for (final NormalizedNode<?, ?> childValue : data.getValue()) {
+        for (final NormalizedNode childValue : data.body()) {
             if (childValue instanceof AugmentationNode) {
                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
                 final DataContainerCodecPrototype<?> codecProto = augmentationByYang.get(augDomNode.getIdentifier());
@@ -411,9 +410,9 @@ public abstract class DataObjectCodecContext<D extends DataObject, T extends Dat
             }
         }
         for (final DataContainerCodecPrototype<?> value : augmentationByStream.values()) {
-            final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
-            if (augData.isPresent()) {
-                map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
+            final NormalizedNode augData = data.childByArg(value.getYangArg());
+            if (augData != null) {
+                map.put(value.getBindingClass(), value.get().deserializeObject(augData));
             }
         }
         return map;