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.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 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.impl.loader.CodecClassLoader;
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.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;
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;
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;
}
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 LoadingCache<Class<?>, DataObjectStreamer<?>> streamers = CacheBuilder.newBuilder().build(
new CacheLoader<Class<?>, DataObjectStreamer<?>>() {
}
});
- private final @NonNull CodecClassLoader loader = CodecClassLoader.create();
+ 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 SchemaRootCodecContext<?> root;
+ private final @NonNull SchemaRootCodecContext<?> root;
public BindingCodecContext() {
this(ServiceLoader.load(BindingRuntimeContext.class).findFirst()
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);
}
}
@Override
- public CodecClassLoader getLoader() {
+ public BindingClassLoader getLoader() {
return loader;
}
@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), codecContext.createWriter(domWriter));
+ final var yangArgs = new ArrayList<YangInstanceIdentifier.PathArgument>();
+ 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 getCodecContextNode(path, null).createWriter(domWriter);
+ return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter);
}
@Override
public BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
final NormalizedNodeStreamWriter domWriter) {
- return root.getRpc(rpcInputOrOutput).createWriter(domWriter);
+ return new BindingToNormalizedStreamWriter(root.getRpc(rpcInputOrOutput), domWriter);
}
@Override
public BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification<?>> notification,
final NormalizedNodeStreamWriter domWriter) {
- return root.getNotification(notification).createWriter(domWriter);
+ return new BindingToNormalizedStreamWriter(root.getNotification(notification), domWriter);
}
@Override
public BindingStreamEventWriter newActionInputWriter(final Class<? extends Action<?, ?, ?>> action,
final NormalizedNodeStreamWriter domWriter) {
- return getActionCodec(action).input().createWriter(domWriter);
+ return new BindingToNormalizedStreamWriter(getActionCodec(action).input(), domWriter);
}
@Override
public BindingStreamEventWriter newActionOutputWriter(final Class<? extends Action<?, ?, ?>> action,
final NormalizedNodeStreamWriter domWriter) {
- return getActionCodec(action).output().createWriter(domWriter);
+ 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;
}
/**
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
}
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) {
@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);
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());
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);
final Class<?> valueType;
- final Type genericType = optType.get();
- if (genericType instanceof Class<?>) {
- valueType = (Class<?>) genericType;
- } else if (genericType instanceof ParameterizedType) {
- valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
+ 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;
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);
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);
}
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);
}
Identifiable.class);
checkState(optIdentifier.isPresent(), "Failed to find identifier for %s", listClz);
- final Class<Identifier<?>> identifier = optIdentifier.get();
+ final Class<Identifier<?>> identifier = optIdentifier.orElseThrow();
final Map<QName, ValueContext> valueCtx = new HashMap<>();
for (final ValueNodeCodecContext leaf : getLeafNodes(identifier, type.statement()).values()) {
final QName name = leaf.getDomPathArgument().getNodeType();
}
@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
}
@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 <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
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);
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")