import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.AbstractMap.SimpleEntry;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
-import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTree;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeNode;
import org.opendaylight.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
import org.opendaylight.yangtools.util.ClassLoaderUtils;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
import org.opendaylight.yangtools.yang.binding.BindingMapping;
import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
-final class BindingCodecContext implements CodecContextFactory, Immutable {
+final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, Immutable {
private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
- private static final String GETTER_PREFIX = "get";
+ static final String GETTER_PREFIX = "get";
- private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec =
- new InstanceIdentifierCodec();
+ private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
private final Codec<QName, Class<?>> identityCodec;
+ private final BindingNormalizedNodeCodecRegistry registry;
private final BindingRuntimeContext context;
- private final SchemaRootCodecContext root;
+ private final SchemaRootCodecContext<?> root;
- public BindingCodecContext(final BindingRuntimeContext context) {
+ 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);
}
@Override
return identityCodec;
}
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ @Override
+ public DataObjectSerializer getEventStreamSerializer(final Class<?> type) {
+ return registry.getSerializer((Class) type);
+ }
+
public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
final NormalizedNodeStreamWriter domWriter) {
final LinkedList<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
- final DataContainerCodecContext<?> codecContext = getCodecContextNode(path, yangArgs);
- final BindingStreamEventWriter writer = new BindingToNormalizedStreamWriter(codecContext, domWriter);
- return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), writer);
+ final DataContainerCodecContext<?,?> codecContext = getCodecContextNode(path, yangArgs);
+ return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter));
}
public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
final NormalizedNodeStreamWriter domWriter) {
- return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter);
+ return getCodecContextNode(path, null).createWriter(domWriter);
}
BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
final NormalizedNodeStreamWriter domWriter) {
- final NodeCodecContext schema = root.getRpc(rpcInputOrOutput);
- return new BindingToNormalizedStreamWriter(schema, domWriter);
+ return root.getRpc(rpcInputOrOutput).createWriter(domWriter);
}
BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
final NormalizedNodeStreamWriter domWriter) {
- final NodeCodecContext schema = root.getNotification(notification);
- return new BindingToNormalizedStreamWriter(schema, domWriter);
+ return root.getNotification(notification).createWriter(domWriter);
}
- public DataContainerCodecContext<?> getCodecContextNode(final InstanceIdentifier<?> binding,
+ public DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
final List<YangInstanceIdentifier.PathArgument> builder) {
- DataContainerCodecContext<?> currentNode = root;
+ DataContainerCodecContext<?,?> currentNode = root;
for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
- currentNode = currentNode.getIdentifierChild(bindingArg, builder);
+ currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
+ Preconditions.checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.",binding);
}
return currentNode;
}
* @param bindingArguments Collection for traversed path arguments
* @return Codec for target node, or @null if the node does not have a
* binding representation (choice, case, leaf).
+ *
*/
- @Nullable NodeCodecContext getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
- final @Nonnull Collection<InstanceIdentifier.PathArgument> bindingArguments) {
- NodeCodecContext currentNode = root;
- ListNodeCodecContext currentList = null;
+ @Nullable NodeCodecContext<?> getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
+ final @Nullable Collection<InstanceIdentifier.PathArgument> bindingArguments) {
+ NodeCodecContext<?> currentNode = root;
+ ListNodeCodecContext<?> currentList = null;
for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
- Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?>, "Unexpected child of non-container node %s", currentNode);
- final DataContainerCodecContext<?> previous = (DataContainerCodecContext<?>) currentNode;
- final NodeCodecContext nextNode = previous.getYangIdentifierChild(domArg);
+ Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?,?>, "Unexpected child of non-container node %s", currentNode);
+ final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?,?>) currentNode;
+ final NodeCodecContext<?> nextNode = previous.yangPathArgumentChild(domArg);
/*
* List representation in YANG Instance Identifier consists of two
// We entered list, so now we have all information to emit
// list path using second list argument.
- bindingArguments.add(currentList.getBindingPathArgument(domArg));
+ if (bindingArguments != null) {
+ bindingArguments.add(currentList.getBindingPathArgument(domArg));
+ }
currentList = null;
currentNode = nextNode;
} else if (nextNode instanceof ListNodeCodecContext) {
// We enter list, we do not update current Node yet,
// since we need to verify
- currentList = (ListNodeCodecContext) nextNode;
+ currentList = (ListNodeCodecContext<?>) nextNode;
} 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<?>) {
- bindingArguments.add(((DataContainerCodecContext<?>) nextNode).getBindingPathArgument(domArg));
+ } else if (nextNode instanceof DataContainerCodecContext<?,?>) {
+ if (bindingArguments != null) {
+ bindingArguments.add(((DataContainerCodecContext<?,?>) nextNode).getBindingPathArgument(domArg));
+ }
currentNode = nextNode;
} else if (nextNode instanceof LeafNodeCodecContext) {
LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
}
if (currentList != null) {
- bindingArguments.add(currentList.getBindingPathArgument(null));
+ if(bindingArguments != null) {
+ bindingArguments.add(currentList.getBindingPathArgument(null));
+ }
return currentList;
}
return currentNode;
}
- NotificationCodecContext getNotificationContext(final SchemaPath notification) {
+ NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
return root.getNotification(notification);
}
- ContainerNodeCodecContext getRpcDataContext(final SchemaPath path) {
+ ContainerNodeCodecContext<?> getRpcDataContext(final SchemaPath path) {
return root.getRpc(path);
}
@Override
- public ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(final Class<?> parentClass,
+ public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
final DataNodeContainer childSchema) {
final HashMap<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
return GETTER_PREFIX + suffix;
}
- private ImmutableMap<String, LeafNodeCodecContext> getLeafNodesUsingReflection(final Class<?> parentClass,
+ private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
final Map<String, DataSchemaNode> getterToLeafSchema) {
- final Map<String, LeafNodeCodecContext> leaves = new HashMap<>();
+ final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
for (final Method method : parentClass.getMethods()) {
if (method.getParameterTypes().length == 0) {
final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
}
final Codec<Object, Object> codec = getCodec(valueType, schema);
- final LeafNodeCodecContext leafNode = new LeafNodeCodecContext(schema, codec, method);
+ final LeafNodeCodecContext<?> leafNode = new LeafNodeCodecContext<>(schema, codec, method);
leaves.put(schema.getQName().getLocalName(), leafNode);
}
}
return ImmutableMap.copyOf(leaves);
}
-
-
private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
final TypeDefinition<?> instantiatedType;
if (schema instanceof LeafSchemaNode) {
return ValueTypeCodec.getCodecFor(valueType, instantiatedType);
}
- private class InstanceIdentifierCodec implements Codec<YangInstanceIdentifier, InstanceIdentifier<?>> {
-
- @Override
- public YangInstanceIdentifier serialize(final InstanceIdentifier<?> input) {
- final List<YangInstanceIdentifier.PathArgument> domArgs = new ArrayList<>();
- getCodecContextNode(input, domArgs);
- return YangInstanceIdentifier.create(domArgs);
- }
-
- @Override
- public InstanceIdentifier<?> deserialize(final YangInstanceIdentifier input) {
- final List<InstanceIdentifier.PathArgument> builder = new ArrayList<>();
- final NodeCodecContext codec = getCodecContextNode(input, builder);
- if (codec == null) {
- return null;
- }
- if (codec instanceof ListNodeCodecContext && Iterables.getLast(builder) instanceof InstanceIdentifier.Item) {
- // We ended up in list, but without key, which means it represent list as a whole,
- // which is not binding representable.
- return null;
- }
- return InstanceIdentifier.create(builder);
- }
- }
-
- private static class IdentityCodec implements Codec<QName, Class<?>> {
- private final BindingRuntimeContext context;
-
- IdentityCodec(final BindingRuntimeContext context) {
- this.context = Preconditions.checkNotNull(context);
- }
-
- @Override
- public Class<?> deserialize(final QName input) {
- Preconditions.checkArgument(input != null, "Input must not be null.");
- return context.getIdentityClass(input);
- }
-
- @Override
- public QName serialize(final Class<?> input) {
- Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
- return BindingReflections.findQName(input);
- }
- }
-
- private static class ValueContext {
-
- Method getter;
- Codec<Object, Object> codec;
-
- public ValueContext(final Class<?> identifier, final LeafNodeCodecContext leaf) {
- final String getterName = GETTER_PREFIX
- + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
- try {
- getter = identifier.getMethod(getterName);
- } catch (NoSuchMethodException | SecurityException e) {
- throw new IllegalStateException(e);
- }
- codec = leaf.getValueCodec();
- }
-
- public Object getAndSerialize(final Object obj) {
- try {
- final Object value = getter.invoke(obj);
- Preconditions.checkArgument(value != null,
- "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
- getter.getDeclaringClass(), getter.getName(), obj);
- return codec.serialize(value);
- } catch (IllegalAccessException | InvocationTargetException e) {
- throw new IllegalArgumentException(e);
- }
- }
-
- public Object deserialize(final Object obj) {
- return codec.deserialize(obj);
- }
-
- }
-
- private static class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
-
- private final Map<QName, ValueContext> keyValueContexts;
- private final ListSchemaNode schema;
- private final Constructor<? extends Identifier<?>> constructor;
- private final Class<?> identifiable;
-
- public IdentifiableItemCodec(final ListSchemaNode schema, final Class<? extends Identifier<?>> keyClass,
- final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
- this.schema = schema;
- this.identifiable = identifiable;
- this.constructor = getConstructor(keyClass);
-
- /*
- * We need to re-index to make sure we instantiate nodes in the order in which
- * they are defined.
- */
- final Map<QName, ValueContext> keys = new LinkedHashMap<>();
- for (final QName qname : schema.getKeyDefinition()) {
- keys.put(qname, keyValueContexts.get(qname));
- }
- this.keyValueContexts = ImmutableMap.copyOf(keys);
- }
-
- @Override
- public IdentifiableItem<?, ?> deserialize(final NodeIdentifierWithPredicates input) {
- final Collection<QName> keys = schema.getKeyDefinition();
- final ArrayList<Object> bindingValues = new ArrayList<>(keys.size());
- for (final QName key : keys) {
- final Object yangValue = input.getKeyValues().get(key);
- bindingValues.add(keyValueContexts.get(key).deserialize(yangValue));
- }
-
- final Identifier<?> identifier;
- try {
- identifier = constructor.newInstance(bindingValues.toArray());
- } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
- throw new IllegalStateException(String.format("Failed to instantiate key class %s", constructor.getDeclaringClass()), e);
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- final IdentifiableItem identifiableItem = new IdentifiableItem(identifiable, identifier);
- return identifiableItem;
- }
-
- @Override
- public NodeIdentifierWithPredicates serialize(final IdentifiableItem<?, ?> input) {
- final Object value = input.getKey();
-
- final Map<QName, Object> values = new LinkedHashMap<>();
- for (final Entry<QName, ValueContext> valueCtx : keyValueContexts.entrySet()) {
- values.put(valueCtx.getKey(), valueCtx.getValue().getAndSerialize(value));
- }
- return new NodeIdentifierWithPredicates(schema.getQName(), values);
- }
- }
-
- @SuppressWarnings("unchecked")
- private static Constructor<? extends Identifier<?>> getConstructor(final Class<? extends Identifier<?>> clazz) {
- for (@SuppressWarnings("rawtypes") final Constructor constr : clazz.getConstructors()) {
- final Class<?>[] parameters = constr.getParameterTypes();
- if (!clazz.equals(parameters[0])) {
- // It is not copy constructor;
- return constr;
- }
- }
- throw new IllegalArgumentException("Supplied class " + clazz + "does not have required constructor.");
- }
-
@Override
public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
final ListSchemaNode schema) {
final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
Identifiable.class);
final Map<QName, ValueContext> valueCtx = new HashMap<>();
- for (final LeafNodeCodecContext leaf : getLeafNodes(identifier, schema).values()) {
+ for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
final QName name = leaf.getDomPathArgument().getNodeType();
valueCtx.put(name, new ValueContext(identifier, leaf));
}
return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
}
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
+ // TODO Do we need defensive check here?
+ return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
+ }
+ @Override
+ public BindingCodecTreeNode<?> getSubtreeCodec(final YangInstanceIdentifier path) {
+ return getCodecContextNode(path, null);
+ }
-
-
+ @Override
+ public BindingCodecTreeNode<?> getSubtreeCodec(final SchemaPath path) {
+ throw new UnsupportedOperationException("Not implemented yet.");
+ }
}