X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=blobdiff_plain;f=binding%2Fmdsal-binding-dom-codec%2Fsrc%2Fmain%2Fjava%2Forg%2Fopendaylight%2Fmdsal%2Fbinding%2Fdom%2Fcodec%2Fimpl%2FBindingCodecContext.java;h=9842c0f0dde47c106fe2939cb7e6f9e0cff797ac;hb=578068bf0c41c9902638695d3b48ccc0e06d4c9c;hp=967e45b5db700e99b5b63f6fb85009220d493504;hpb=c241dcfa5322ac10810a1068ccd2eb57f6f2dbb2;p=mdsal.git diff --git a/binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/BindingCodecContext.java b/binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/BindingCodecContext.java index 967e45b5db..9842c0f0dd 100644 --- a/binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/BindingCodecContext.java +++ b/binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/BindingCodecContext.java @@ -7,57 +7,94 @@ */ package org.opendaylight.mdsal.binding.dom.codec.impl; -import com.google.common.base.Preconditions; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; +import static com.google.common.base.Verify.verify; +import static java.util.Objects.requireNonNull; + +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; +import java.io.IOException; +import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.AbstractMap.SimpleEntry; +import java.lang.reflect.WildcardType; +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; -import java.util.concurrent.Callable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree; +import java.util.Optional; +import java.util.ServiceLoader; +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.generator.util.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.spec.naming.BindingMapping; +import org.opendaylight.mdsal.binding.dom.codec.spi.AbstractBindingNormalizedNodeSerializer; +import org.opendaylight.mdsal.binding.dom.codec.spi.BindingDOMCodecServices; +import org.opendaylight.mdsal.binding.dom.codec.spi.BindingSchemaMapping; +import org.opendaylight.mdsal.binding.loader.BindingClassLoader; +import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext; +import org.opendaylight.mdsal.binding.runtime.api.ListRuntimeType; import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections; -import org.opendaylight.yangtools.concepts.Codec; +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.BindingStreamEventWriter; +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; import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.binding.DataObjectSerializer; import org.opendaylight.yangtools.yang.binding.Identifiable; import org.opendaylight.yangtools.yang.binding.Identifier; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.binding.Notification; +import org.opendaylight.yangtools.yang.binding.OpaqueObject; +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.NodeIdentifierWithPredicates; +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; +import org.opendaylight.yangtools.yang.data.api.schema.MapNode; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +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.model.api.DataNodeContainer; +import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter; +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; -import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus; import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; -import org.opendaylight.yangtools.yang.model.api.SchemaNode; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; +import org.opendaylight.yangtools.yang.model.api.TypeAware; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition; +import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement; +import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute; +import org.opendaylight.yangtools.yang.model.api.stmt.TypeDefinitionAware; import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition; @@ -65,21 +102,71 @@ import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, Immutable { +@MetaInfServices(value = BindingDOMCodecServices.class) +public final class BindingCodecContext extends AbstractBindingNormalizedNodeSerializer + implements BindingDOMCodecServices, Immutable, CodecContextFactory, DataObjectSerializerRegistry { + private final class DataObjectSerializerProxy implements DataObjectSerializer, Delegator> { + private final @NonNull DataObjectStreamer delegate; + + DataObjectSerializerProxy(final DataObjectStreamer delegate) { + this.delegate = requireNonNull(delegate); + } + + @Override + public DataObjectStreamer getDelegate() { + return delegate; + } + + @Override + public void serialize(final DataObject obj, final BindingStreamEventWriter stream) throws IOException { + delegate.serialize(BindingCodecContext.this, obj, stream); + } + } + 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 { + final String dir = System.getProperty("org.opendaylight.mdsal.binding.dom.codec.loader.bytecodeDumpDirectory"); + BYTECODE_DIRECTORY = Strings.isNullOrEmpty(dir) ? null : new File(dir); + } - private final Codec> instanceIdentifierCodec; - private final Codec> identityCodec; - private final BindingNormalizedNodeCodecRegistry registry; - private final BindingRuntimeContext context; - private final SchemaRootCodecContext root; + private final LoadingCache, DataObjectStreamer> streamers = CacheBuilder.newBuilder().build( + new CacheLoader, DataObjectStreamer>() { + @Override + public DataObjectStreamer load(final Class key) throws ReflectiveOperationException { + final Class streamer = DataObjectStreamerGenerator.generateStreamer(loader, BindingCodecContext.this, + key); + final Field instance = streamer.getDeclaredField(DataObjectStreamerGenerator.INSTANCE_FIELD); + return (DataObjectStreamer) instance.get(null); + } + }); + private final LoadingCache, DataObjectSerializer> serializers = CacheBuilder.newBuilder().build( + new CacheLoader, DataObjectSerializer>() { + @Override + public DataObjectSerializer load(final Class key) throws ExecutionException { + return new DataObjectSerializerProxy(streamers.get(key)); + } + }); + + private final @NonNull BindingClassLoader loader = + BindingClassLoader.create(BindingCodecContext.class, BYTECODE_DIRECTORY); + private final @NonNull InstanceIdentifierCodec instanceIdentifierCodec; + private final @NonNull IdentityCodec identityCodec; + private final @NonNull BindingRuntimeContext context; + private final @NonNull SchemaRootCodecContext root; + + public BindingCodecContext() { + this(ServiceLoader.load(BindingRuntimeContext.class).findFirst() + .orElseThrow(() -> new IllegalStateException("Failed to load BindingRuntimeContext"))); + } - BindingCodecContext(final BindingRuntimeContext context, final BindingNormalizedNodeCodecRegistry registry) { - this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required."); - this.root = SchemaRootCodecContext.create(this); - this.identityCodec = new IdentityCodec(context); - this.instanceIdentifierCodec = new InstanceIdentifierCodec(this); - this.registry = Preconditions.checkNotNull(registry); + public BindingCodecContext(final BindingRuntimeContext context) { + this.context = requireNonNull(context, "Binding Runtime Context is required."); + root = new SchemaRootCodecContext<>(this); + identityCodec = new IdentityCodec(context); + instanceIdentifierCodec = new InstanceIdentifierCodec(this); } @Override @@ -87,50 +174,87 @@ final class BindingCodecContext implements CodecContextFactory, BindingCodecTree return context; } - Codec> getInstanceIdentifierCodec() { - return instanceIdentifierCodec; + @Override + public BindingClassLoader getLoader() { + return loader; } - public Codec> getIdentityCodec() { + @Override + public IdentityCodec getIdentityCodec() { return identityCodec; } - @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public BindingInstanceIdentifierCodec getInstanceIdentifierCodec() { + return instanceIdentifierCodec; + } + @Override public DataObjectSerializer getEventStreamSerializer(final Class type) { - return registry.getSerializer((Class) type); + return serializers.getUnchecked(type); + } + + @Override + public DataObjectStreamer getDataObjectSerializer(final Class type) { + return streamers.getUnchecked(type); } - public Entry newWriter(final InstanceIdentifier path, + @Override + public DataObjectSerializer getSerializer(final Class type) { + return serializers.getUnchecked(type); + } + + @Override + public Entry newWriterAndIdentifier( + final InstanceIdentifier path, final NormalizedNodeStreamWriter domWriter) { + final var yangArgs = new ArrayList(); + final var codecContext = getCodecContextNode(path, yangArgs); + return Map.entry(YangInstanceIdentifier.of(yangArgs), + new BindingToNormalizedStreamWriter(codecContext, domWriter)); + } + + @Override + public BindingStreamEventWriter newWriter(final InstanceIdentifier path, + final NormalizedNodeStreamWriter domWriter) { + return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter); + } + + @Override + public BindingStreamEventWriter newRpcWriter(final Class rpcInputOrOutput, final NormalizedNodeStreamWriter domWriter) { - final List yangArgs = new LinkedList<>(); - final DataContainerCodecContext codecContext = getCodecContextNode(path, yangArgs); - return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter)); + return new BindingToNormalizedStreamWriter(root.getRpc(rpcInputOrOutput), domWriter); } - public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier path, + @Override + public BindingStreamEventWriter newNotificationWriter(final Class> notification, final NormalizedNodeStreamWriter domWriter) { - return getCodecContextNode(path, null).createWriter(domWriter); + return new BindingToNormalizedStreamWriter(root.getNotification(notification), domWriter); } - BindingStreamEventWriter newRpcWriter(final Class rpcInputOrOutput, + @Override + public BindingStreamEventWriter newActionInputWriter(final Class> action, final NormalizedNodeStreamWriter domWriter) { - return root.getRpc(rpcInputOrOutput).createWriter(domWriter); + return new BindingToNormalizedStreamWriter(getActionCodec(action).input(), domWriter); } - BindingStreamEventWriter newNotificationWriter(final Class notification, + @Override + public BindingStreamEventWriter newActionOutputWriter(final Class> action, final NormalizedNodeStreamWriter domWriter) { - return root.getNotification(notification).createWriter(domWriter); + return new BindingToNormalizedStreamWriter(getActionCodec(action).output(), domWriter); } - public DataContainerCodecContext getCodecContextNode(final InstanceIdentifier binding, + @NonNull DataContainerCodecContext getCodecContextNode(final InstanceIdentifier binding, final List builder) { - DataContainerCodecContext currentNode = root; - for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) { - currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder); - Preconditions.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; } /** @@ -145,16 +269,28 @@ final class BindingCodecContext implements CodecContextFactory, BindingCodecTree * binding representation (choice, case, leaf). * */ - @Nullable NodeCodecContext getCodecContextNode(final @Nonnull YangInstanceIdentifier dom, + @Nullable BindingDataObjectCodecTreeNode getCodecContextNode(final @NonNull YangInstanceIdentifier dom, final @Nullable Collection bindingArguments) { - NodeCodecContext currentNode = root; + NodeCodecContext currentNode = root; ListNodeCodecContext currentList = null; - for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) { - Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext, + 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 @@ -165,7 +301,7 @@ final class BindingCodecContext implements CodecContextFactory, BindingCodecTree * Identifier as Item or IdentifiableItem */ if (currentList != null) { - Preconditions.checkArgument(currentList == nextNode, + checkArgument(currentList == nextNode, "List should be referenced two times in YANG Instance Identifier %s", dom); // We entered list, so now we have all information to emit @@ -175,21 +311,21 @@ final class BindingCodecContext implements CodecContextFactory, BindingCodecTree } 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 LeafNodeCodecContext) { - LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom); + } else if (nextNode instanceof ValueNodeCodecContext) { + LOG.debug("Instance identifier referencing a leaf is not representable ({})", dom); return null; } } @@ -197,11 +333,11 @@ final class BindingCodecContext implements CodecContextFactory, BindingCodecTree // Algorithm ended in list as whole representation // we sill need to emit identifier for list if (currentNode instanceof ChoiceNodeCodecContext) { - LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom); + LOG.debug("Instance identifier targeting a choice is not representable ({})", dom); return null; } if (currentNode instanceof CaseNodeCodecContext) { - LOG.debug("Instance identifier targeting a case is not representable (%s)", dom); + LOG.debug("Instance identifier targeting a case is not representable ({})", dom); return null; } @@ -211,15 +347,20 @@ final class BindingCodecContext implements CodecContextFactory, BindingCodecTree } return currentList; } - return currentNode; + if (currentNode != null) { + verify(currentNode instanceof BindingDataObjectCodecTreeNode, "Illegal return node %s for identifier %s", + currentNode, dom); + return (BindingDataObjectCodecTreeNode) currentNode; + } + return null; } - NotificationCodecContext getNotificationContext(final SchemaPath notification) { + NotificationCodecContext getNotificationContext(final Absolute notification) { return root.getNotification(notification); } - RpcInputCodec getRpcInputCodec(final SchemaPath path) { - return root.getRpc(path); + RpcInputCodec getRpcInputCodec(final Absolute containerPath) { + return root.getRpc(containerPath); } ActionCodecContext getActionCodec(final Class> action) { @@ -227,135 +368,373 @@ final class BindingCodecContext implements CodecContextFactory, BindingCodecTree } @Override - public ImmutableMap> getLeafNodes(final Class parentClass, - final DataNodeContainer childSchema) { - final Map getterToLeafSchema = new HashMap<>(); - for (final DataSchemaNode leaf : childSchema.getChildNodes()) { - if (leaf instanceof TypedDataSchemaNode) { - getterToLeafSchema.put(getGetterName(leaf, ((TypedDataSchemaNode) leaf).getType()), leaf); + public ImmutableMap getLeafNodes(final Class type, + final EffectiveStatement schema) { + final var getterToLeafSchema = new HashMap(); + for (var stmt : schema.effectiveSubstatements()) { + 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(parentClass, getterToLeafSchema); + return getLeafNodesUsingReflection(type, getterToLeafSchema); } - private static String getGetterName(final SchemaNode node, final TypeDefinition typeDef) { - final String suffix = BindingMapping.getGetterSuffix(node.getQName()); - // Bug 8903: If it is a derived type of boolean or empty, not an inner type, then the return type - // of method would be the generated type of typedef not build-in types, so here it should be 'get'. - if ((typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition) - && (typeDef.getPath().equals(node.getPath()) || typeDef.getBaseType() == null)) { - return "is" + suffix; - } - return "get" + suffix; + private static void putLeaf(final Map map, final DataSchemaNode leaf) { + map.put(BindingSchemaMapping.getGetterMethodName(leaf), leaf); } - private ImmutableMap> getLeafNodesUsingReflection(final Class parentClass, - final Map getterToLeafSchema) { - final Map> leaves = new HashMap<>(); - for (final Method method : parentClass.getMethods()) { - if (method.getParameterTypes().length == 0) { + private ImmutableMap getLeafNodesUsingReflection( + final Class parentClass, final Map getterToLeafSchema) { + final var leaves = new HashMap(); + 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()); - final Class valueType; - if (schema instanceof LeafSchemaNode) { - valueType = method.getReturnType(); - } else if (schema instanceof LeafListSchemaNode) { - final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType()); - - if (genericType instanceof Class) { - valueType = (Class) genericType; - } else if (genericType instanceof ParameterizedType) { - valueType = (Class) ((ParameterizedType) genericType).getRawType(); + + final ValueNodeCodecContext valueNode; + if (schema instanceof LeafSchemaNode leafSchema) { + // FIXME: MDSAL-670: this is not right as we need to find a concrete type, but this may return + // Object.class + final Class valueType = method.getReturnType(); + final ValueCodec codec = getCodec(valueType, leafSchema.getType()); + valueNode = LeafNodeCodecContext.of(leafSchema, codec, method.getName(), valueType, + context.getEffectiveModelContext()); + } else if (schema instanceof LeafListSchemaNode leafListSchema) { + final Optional optType = ClassLoaderUtils.getFirstGenericParameter( + method.getGenericReturnType()); + checkState(optType.isPresent(), "Failed to find return type for %s", method); + + final Class valueType; + final Type genericType = optType.orElseThrow(); + if (genericType instanceof Class clazz) { + valueType = clazz; + } else if (genericType instanceof ParameterizedType parameterized) { + valueType = (Class) parameterized.getRawType(); + } else if (genericType instanceof WildcardType) { + // FIXME: MDSAL-670: this is not right as we need to find a concrete type + valueType = Object.class; } else { throw new IllegalStateException("Unexpected return type " + genericType); } + + final ValueCodec codec = getCodec(valueType, leafListSchema.getType()); + valueNode = new LeafSetNodeCodecContext(leafListSchema, codec, method.getName()); + } else if (schema instanceof AnyxmlSchemaNode anyxmlSchema) { + valueNode = new OpaqueNodeCodecContext.Anyxml<>(anyxmlSchema, method.getName(), + opaqueReturnType(method), loader); + } else if (schema instanceof AnydataSchemaNode anydataSchema) { + valueNode = new OpaqueNodeCodecContext.Anydata<>(anydataSchema, method.getName(), + opaqueReturnType(method), loader); } else { - // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface). + verify(schema == null, "Unhandled schema %s for method %s", schema, method); + // We do not have schema for leaf, so we will ignore it (e.g. getClass). continue; } - final Codec codec = getCodec(valueType, schema); - final LeafNodeCodecContext leafNode = new LeafNodeCodecContext<>(schema, codec, method, - context.getSchemaContext()); - leaves.put(schema.getQName().getLocalName(), leafNode); + + leaves.put(method, valueNode); } } return ImmutableMap.copyOf(leaves); } - private Codec getCodec(final Class valueType, final DataSchemaNode schema) { - Preconditions.checkArgument(schema instanceof TypedDataSchemaNode, "Unsupported leaf node type %s", schema); - - return getCodec(valueType, ((TypedDataSchemaNode)schema).getType()); - } - - Codec getCodec(final Class valueType, final TypeDefinition instantiatedType) { - if (Class.class.equals(valueType)) { + // FIXME: this is probably not right w.r.t. nulls + ValueCodec getCodec(final Class valueType, final TypeDefinition instantiatedType) { + if (BaseIdentity.class.isAssignableFrom(valueType)) { @SuppressWarnings({ "unchecked", "rawtypes" }) - final Codec casted = (Codec) identityCodec; + final ValueCodec casted = (ValueCodec) identityCodec; return casted; } else if (InstanceIdentifier.class.equals(valueType)) { @SuppressWarnings({ "unchecked", "rawtypes" }) - final Codec casted = (Codec) instanceIdentifierCodec; + final ValueCodec casted = (ValueCodec) instanceIdentifierCodec; return casted; - } else if (Boolean.class.equals(valueType)) { - if (instantiatedType instanceof EmptyTypeDefinition) { - return ValueTypeCodec.EMPTY_CODEC; - } } else if (BindingReflections.isBindingClass(valueType)) { return getCodecForBindingClass(valueType, instantiatedType); } - return ValueTypeCodec.NOOP_CODEC; + // FIXME: MDSAL-670: this is right for most situations, but we must never return NOOP_CODEC for + // valueType=Object.class + return SchemaUnawareCodec.NOOP_CODEC; } @SuppressWarnings("checkstyle:illegalCatch") - private Codec getCodecForBindingClass(final Class valueType, final TypeDefinition typeDef) { + // FIXME: this is probably not right w.r.t. nulls + private ValueCodec getCodecForBindingClass(final Class valueType, + final TypeDefinition typeDef) { if (typeDef instanceof IdentityrefTypeDefinition) { - return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, identityCodec); + return new CompositeValueCodec.OfIdentity(valueType, identityCodec); } else if (typeDef instanceof InstanceIdentifierTypeDefinition) { - return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, instanceIdentifierCodec); - } else if (typeDef instanceof UnionTypeDefinition) { - final Callable loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef, - this); + return new CompositeValueCodec.OfInstanceIdentifier(valueType, instanceIdentifierCodec); + } else if (typeDef instanceof UnionTypeDefinition unionType) { try { - return loader.call(); - } catch (final Exception e) { + return UnionTypeCodec.of(valueType, unionType, this); + } catch (Exception e) { throw new IllegalStateException("Unable to load codec for " + valueType, e); } } else if (typeDef instanceof LeafrefTypeDefinition) { - final Entry typeWithSchema = context.getTypeWithSchema(valueType); - final WithStatus schema = typeWithSchema.getValue(); - Preconditions.checkState(schema instanceof TypeDefinition); - return getCodec(valueType, (TypeDefinition) schema); + final var typeWithSchema = context.getTypeWithSchema(valueType); + final var schema = typeWithSchema.statement(); + final TypeDefinition def; + if (schema instanceof TypeDefinitionAware typeDefAware) { + def = typeDefAware.getTypeDefinition(); + } else if (schema instanceof TypeAware typeAware) { + def = typeAware.getType(); + } else { + throw new IllegalStateException("Unexpected schema " + schema); + } + return getCodec(valueType, def); } - return ValueTypeCodec.getCodecFor(valueType, typeDef); + return SchemaUnawareCodec.of(valueType, typeDef); } @Override - public Codec> getPathArgumentCodec(final Class listClz, - final ListSchemaNode schema) { - final Class> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz, + public IdentifiableItemCodec getPathArgumentCodec(final Class listClz, final ListRuntimeType type) { + final Optional>> optIdentifier = ClassLoaderUtils.findFirstGenericArgument(listClz, Identifiable.class); + checkState(optIdentifier.isPresent(), "Failed to find identifier for %s", listClz); + + final Class> identifier = optIdentifier.orElseThrow(); final Map valueCtx = new HashMap<>(); - for (final LeafNodeCodecContext leaf : getLeafNodes(identifier, schema).values()) { + for (final ValueNodeCodecContext leaf : getLeafNodes(identifier, type.statement()).values()) { final QName name = leaf.getDomPathArgument().getNodeType(); valueCtx.put(name, new ValueContext(identifier, leaf)); } - return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx); + return IdentifiableItemCodec.of(type.statement(), identifier, listClz, valueCtx); + } + + @Override + public CommonDataObjectCodecTreeNode streamChild(final Class childClass) { + return root.streamChild(childClass); } + @Override @SuppressWarnings("unchecked") + public > BindingAugmentationCodecTreeNode getAugmentationCodec( + final InstanceIdentifier path) { + final var codecContext = getCodecContextNode(path, null); + if (codecContext instanceof BindingAugmentationCodecTreeNode) { + return (BindingAugmentationCodecTreeNode) codecContext; + } + throw new IllegalArgumentException(path + " does not refer to an Augmentation"); + } + + @Override + @SuppressWarnings("unchecked") + public BindingDataObjectCodecTreeNode getDataObjectCodec( + final InstanceIdentifier path) { + final var codecContext = getCodecContextNode(path, null); + if (codecContext instanceof BindingDataObjectCodecTreeNode) { + return (BindingDataObjectCodecTreeNode) codecContext; + } + throw new IllegalArgumentException(path + " does not refer to a plain DataObject"); + } + + @Override + @SuppressWarnings("unchecked") + public CodecWithPath getSubtreeCodecWithPath(final InstanceIdentifier path) { + final var yangArgs = new ArrayList(); + final var codecContext = getCodecContextNode(path, yangArgs); + + // TODO Do we need defensive check here? + return new CodecWithPath<>((CommonDataObjectCodecTreeNode) codecContext, + YangInstanceIdentifier.of(yangArgs)); + } + @Override - public BindingCodecTreeNode getSubtreeCodec(final InstanceIdentifier path) { + @SuppressWarnings("unchecked") + public CommonDataObjectCodecTreeNode getSubtreeCodec(final InstanceIdentifier path) { // TODO Do we need defensive check here? - return (BindingCodecTreeNode) getCodecContextNode(path, null); + return (CommonDataObjectCodecTreeNode) getCodecContextNode(path, null); } @Override - public BindingCodecTreeNode getSubtreeCodec(final YangInstanceIdentifier path) { + public BindingCodecTreeNode getSubtreeCodec(final YangInstanceIdentifier path) { return getCodecContextNode(path, null); } @Override - public BindingCodecTreeNode getSubtreeCodec(final SchemaPath path) { + public BindingCodecTreeNode getSubtreeCodec(final Absolute path) { throw new UnsupportedOperationException("Not implemented yet."); } + + @Override + public YangInstanceIdentifier toYangInstanceIdentifier(final InstanceIdentifier binding) { + return instanceIdentifierCodec.fromBinding(binding); + } + + @Override + public InstanceIdentifier fromYangInstanceIdentifier(final YangInstanceIdentifier dom) { + return instanceIdentifierCodec.toBinding(dom); + } + + @Override + public NormalizedResult toNormalizedNode(final InstanceIdentifier path, final T data) { + // We create Binding Stream Writer which translates from Binding to Normalized Nodes + final var yangArgs = new ArrayList(); + 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; + + try { + // 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); + } + + // 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 + public Entry, DataObject> fromNormalizedNode(final YangInstanceIdentifier path, + final NormalizedNode data) { + if (notBindingRepresentable(data)) { + return null; + } + + final List builder = new ArrayList<>(); + final BindingDataObjectCodecTreeNode codec = getCodecContextNode(path, builder); + if (codec == null) { + if (data != null) { + LOG.warn("Path {} does not have a binding equivalent, should have been caught earlier ({})", path, + data.getClass()); + } + return null; + } + + final DataObject lazyObj = codec.deserialize(data); + final InstanceIdentifier bindingPath = InstanceIdentifier.unsafeOf(builder); + return Map.entry(bindingPath, lazyObj); + } + + @Override + public BaseNotification fromNormalizedNodeNotification(final Absolute path, final ContainerNode data) { + return getNotificationContext(path).deserialize(data); + } + + @Override + public BaseNotification fromNormalizedNodeNotification(final Absolute path, final ContainerNode data, + final Instant eventInstant) { + return eventInstant == null ? fromNormalizedNodeNotification(path, data) + : getNotificationContext(path).deserialize(data, eventInstant); + } + + @Override + public DataObject fromNormalizedNodeRpcData(final Absolute containerPath, final ContainerNode data) { + return getRpcInputCodec(containerPath).deserialize(data); + } + + @Override + public T fromNormalizedNodeActionInput(final Class> action, + final ContainerNode input) { + return (T) requireNonNull(getActionCodec(action).input().deserialize(requireNonNull(input))); + } + + @Override + public T fromNormalizedNodeActionOutput(final Class> action, + final ContainerNode output) { + return (T) requireNonNull(getActionCodec(action).output().deserialize(requireNonNull(output))); + } + + @Override + @SuppressFBWarnings("BC_UNCONFIRMED_CAST") + public ContainerNode toNormalizedNodeNotification(final Notification data) { + // FIXME: Should the cast to DataObject be necessary? + return serializeDataObject((DataObject) data, + (ctx, iface, domWriter) -> ctx.newNotificationWriter( + (Class>) iface.asSubclass(Notification.class), domWriter)); + } + + @Override + public ContainerNode toNormalizedNodeNotification(final Absolute path, final BaseNotification data) { + checkArgument(data instanceof DataObject, "Unexpected data %s", data); + @SuppressWarnings("rawtypes") + final NotificationCodecContext notifContext = getNotificationContext(path); + @SuppressWarnings("unchecked") + final var result = notifContext.serialize((DataObject) data); + verify(result instanceof ContainerNode, "Unexpected result %s from %s", result, data); + return (ContainerNode) result; + } + + @Override + @SuppressFBWarnings("BC_UNCONFIRMED_CAST") + public ContainerNode toNormalizedNodeRpcData(final DataContainer data) { + // FIXME: Should the cast to DataObject be necessary? + return serializeDataObject((DataObject) data, BindingNormalizedNodeWriterFactory::newRpcWriter); + } + + @Override + public ContainerNode toNormalizedNodeActionInput(final Class> action, + final RpcInput input) { + return serializeDataObject(input,(ctx, iface, domWriter) -> ctx.newActionInputWriter(action, domWriter)); + } + + @Override + public ContainerNode toNormalizedNodeActionOutput(final Class> action, + final RpcOutput output) { + return serializeDataObject(output, (ctx, iface, domWriter) -> ctx.newActionOutputWriter(action, domWriter)); + } + + private @NonNull ContainerNode serializeDataObject(final DataObject data, + final WriterFactoryMethod newWriter) { + final var result = new NormalizationResultHolder(); + // We create DOM stream writer which produces normalized nodes + final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result); + final Class type = data.implementedInterface(); + @SuppressWarnings("unchecked") + final BindingStreamEventWriter writer = newWriter.createWriter(this, (Class) type, domWriter); + try { + getSerializer(type).serialize(data, writer); + } catch (final IOException e) { + LOG.error("Unexpected failure while serializing data {}", data, e); + throw new IllegalStateException("Failed to create normalized node", e); + } + 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; + } + + @SuppressWarnings("rawtypes") + private static Class opaqueReturnType(final Method method) { + final Class valueType = method.getReturnType(); + verify(OpaqueObject.class.isAssignableFrom(valueType), "Illegal value type %s", valueType); + return valueType.asSubclass(OpaqueObject.class); + } + + @FunctionalInterface + private interface WriterFactoryMethod { + BindingStreamEventWriter createWriter(@NonNull BindingNormalizedNodeWriterFactory factory, + @NonNull Class bindingClass, @NonNull NormalizedNodeStreamWriter domWriter); + } }