--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+
+/**
+ *
+ * Navigable tree representing hierarchy of Binding to Normalized Node codecs
+ *
+ * This navigable tree is associated to conrete set of YANG models, represented
+ * by SchemaContext and provides access to subtree specific serialization
+ * context.
+ *
+ * TODO: Add more detailed documentation
+ **/
+public interface BindingCodecTree {
+
+ @Nullable <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(InstanceIdentifier<T> path);
+
+ @Nullable BindingCodecTreeNode<?> getSubtreeCodec(YangInstanceIdentifier path);
+
+ @Nullable BindingCodecTreeNode<?> getSubtreeCodec(SchemaPath path);
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public interface BindingCodecTreeFactory {
+
+ /**
+ *
+ * Creates Binding Codec Tree for specified Binding runtime context.
+ *
+ * @param context
+ * Binding Runtime Context for which Binding codecs should be
+ * instantiated.
+ * @return Binding Codec Tree for specified Binding runtime context.
+ */
+ BindingCodecTree create(BindingRuntimeContext context);
+
+ /**
+ *
+ * Creates Binding Codec Tree for specified Binding runtime context.
+ *
+ * @param context
+ * Binding Runtime Context for which Binding codecs should be
+ * instantiated.
+ * @param bindingClasses
+ * Binding Runtime Context will be constructed using bindings
+ * which contains specified classes, in order to support
+ * deserialization in multi-classloader environment.
+ * @return Binding Codec Tree for specified Binding runtime context.
+ */
+ @Beta
+ BindingCodecTree create(SchemaContext context, Class<?>... bindingClasses);
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableCollection;
+import java.util.List;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
+
+/**
+ * Subtree codec specific to model subtree between Java Binding and
+ * NormalizedNode.
+ *
+ */
+@Beta
+public interface BindingCodecTreeNode<T extends DataObject> extends BindingNormalizedNodeCodec<T> {
+
+ /**
+ *
+ * Returns binding class of interface which represents API of current
+ * schema node.
+ *
+ * The result is same as invoking {@link DataObject#getImplementedInterface()}
+ * on instance of data.
+ *
+ * @return interface which defines API of binding representation of data.
+ */
+ @Nonnull
+ Class<T> getBindingClass();
+
+ /**
+ *
+ * Returns child context as if it was walked by
+ * {@link BindingStreamEventWriter}. This means that to enter case, one must
+ * issue getChild(ChoiceClass).getChild(CaseClass).
+ *
+ * @param childClass Child class by Biding Stream navigation
+ * @return Context of child
+ * @throws IllegalArgumentException
+ * If supplied child class is not valid in specified context.
+ */
+ @Nonnull
+ <E extends DataObject> BindingCodecTreeNode<E> streamChild(@Nonnull Class<E> childClass);
+
+ /**
+ *
+ * Returns child context as if it was walked by
+ * {@link BindingStreamEventWriter}. This means that to enter case, one must
+ * issue getChild(ChoiceClass).getChild(CaseClass).
+ *
+ * This method differs from {@link #streamChild(Class)}, that is less
+ * stricter for interfaces representing augmentation and cases, that
+ * may return {@link BindingCodecTreeNode} even if augmentation interface
+ * containing same data was supplied and does not represent augmentation
+ * of this node.
+ *
+ * @param childClass
+ * @return Context of child or Optional absent is supplied class is not
+ * applicable in context.
+ */
+ <E extends DataObject> Optional<? extends BindingCodecTreeNode<E>> possibleStreamChild(@Nonnull Class<E> childClass);
+
+ /**
+ * Returns nested node context using supplied YANG Instance Identifier
+ *
+ * @param child
+ * Yang Instance Identifier Argument
+ * @return Context of child
+ * @throws IllegalArgumentException
+ * If supplied argument does not represent valid child.
+ */
+ @Nonnull
+ BindingCodecTreeNode<?> yangPathArgumentChild(@Nonnull YangInstanceIdentifier.PathArgument child);
+
+ /**
+ * Returns nested node context using supplied Binding Instance Identifier
+ * and adds YANG instance identifiers to supplied list.
+ *
+ * @param arg
+ * Binding Instance Identifier Argument
+ * @param builder
+ * Mutable instance of list, which is appended by YangInstanceIdentifiers
+ * as tree is walked. Use null if such side-product is not needed.
+ * @return Context of child
+ * @throws IllegalArgumentException
+ * If supplied argument does not represent valid child.
+ */
+ @Nonnull
+ BindingCodecTreeNode<?> bindingPathArgumentChild(@Nonnull InstanceIdentifier.PathArgument arg,
+ @Nullable List<YangInstanceIdentifier.PathArgument> builder);
+
+ /**
+ *
+ * Returns codec which uses caches serialization / deserialization results
+ *
+ * Caching may introduce performance penalty to serialization / deserialization
+ * but may decrease use of heap for repetitive objects.
+ *
+ *
+ * @param cacheSpecifier Set of objects, for which cache may be in place
+ * @return Codec whihc uses cache for serialization / deserialization.
+ */
+ @Nonnull
+ BindingNormalizedNodeCachingCodec<T> createCachingCodec(@Nonnull
+ ImmutableCollection<Class<? extends DataObject>> cacheSpecifier);
+
+ @Beta
+ void writeAsNormalizedNode(T data, NormalizedNodeStreamWriter writer);
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+
+/**
+ *
+ * Caching variant of Binding to Normalized Node codec.
+ *
+ * Caching may introduce performance penalty to serialization / deserialization
+ * but may decrease use of heap for repetitive objects.
+ *
+ * @param <T> Binding representtion of data
+ *
+ */
+@Beta
+public interface BindingNormalizedNodeCachingCodec<T extends DataObject> extends BindingNormalizedNodeCodec<T>, AutoCloseable {
+
+ /**
+ *
+ * Invoking close will invalidate this codec and any of its child
+ * codecs and will invalidate cache.
+ *
+ * Any subsequent calls to this codec will fail with {@link IllegalStateException}
+ * thrown.
+ *
+ */
+ @Override
+ public void close();
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import javax.annotation.Nonnull;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ *
+ * Codec providing serialization and deserializiation between Binding
+ * and NormalizedNode representation of data.
+ *
+ *
+ * @param <T> Binding representation of data
+ */
+@Beta
+public interface BindingNormalizedNodeCodec<T extends DataObject> {
+
+ /**
+ * Converts from Normalized Node to Binding representation of data.
+ *
+ * @param data Normalized Node representation of data
+ * @return Binding representation of data
+ */
+ @Nonnull T deserialize(@Nonnull NormalizedNode<?,?> data);
+
+ /**
+ * Converts from Binding to Normalized Node representation of data.
+ *
+ * @param data Binding representation of data
+ * @return Normalized Node representation of data
+ */
+ @Nonnull NormalizedNode<?,?> serialize(@Nonnull T data);
+
+}
* @param binding
* Binding Instance Identifier
* @return DOM Instance Identifier
+ * @throws IllegalArgumentException
+ * If supplied Instance Identifier is not valid.
*/
YangInstanceIdentifier toYangInstanceIdentifier(@Nonnull InstanceIdentifier<?> binding);
* @param data
* Data object representing data
* @return NormalizedNode representation
+ * @throws IllegalArgumentException
+ * If supplied Instance Identifier is not valid.
*/
<T extends DataObject> Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
InstanceIdentifier<T> path, T data);
* Stream writer on which events will be invoked.
* @return Instance Identifier and {@link BindingStreamEventWriter}
* which will write to supplied {@link NormalizedNodeStreamWriter}.
+ * @throws IllegalArgumentException If supplied Instance Identifier is not valid.
*/
@Nonnull Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriterAndIdentifier(@Nonnull InstanceIdentifier<?> path,
@Nonnull NormalizedNodeStreamWriter domWriter);
* @param domWriter Stream writer on which events will be invoked.
* @return {@link BindingStreamEventWriter}
* which will write to supplied {@link NormalizedNodeStreamWriter}.
+ * @throws IllegalArgumentException If supplied Instance Identifier is not valid.
*/
@Nonnull
BindingStreamEventWriter newWriter(@Nonnull InstanceIdentifier<?> path,
import org.opendaylight.yangtools.yang.binding.DataObjectSerializerImplementation;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-abstract class AugmentableDataNodeContainerEmmiterSource extends DataNodeContainerSerializerSource {
+abstract class AugmentableDataNodeContainerEmitterSource extends DataNodeContainerSerializerSource {
private static final String AUGMENTABLE_SERIALIZER = "AUGMENTABLE_SERIALIZER";
- public AugmentableDataNodeContainerEmmiterSource(final AbstractStreamWriterGenerator generator, final GeneratedType type, final DataNodeContainer node) {
+ public AugmentableDataNodeContainerEmitterSource(final AbstractStreamWriterGenerator generator, final GeneratedType type, final DataNodeContainer node) {
super(generator, type, node);
/*
* Eventhough intuition says the serializer could reference the generator directly,
import org.opendaylight.yangtools.yang.binding.DataObjectSerializerImplementation;
import org.opendaylight.yangtools.yang.binding.DataObjectSerializerRegistry;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
emitList(b, getterName, valueType, casted);
} else if (child instanceof ContainerSchemaNode) {
b.append(statement(staticInvokeEmitter(childType, getterName)));
- } else if (child instanceof ChoiceNode) {
+ } else if (child instanceof ChoiceSchemaNode) {
String propertyName = CHOICE_PREFIX + childType.getName();
staticConstant(propertyName, DataObjectSerializerImplementation.class, ChoiceDispatchSerializer.from(loadClass(childType)));
b.append(statement(invoke(propertyName, StreamWriterGenerator.SERIALIZE_METHOD_NAME, REGISTRY, cast(DataObject.class.getName(),getterName), STREAM)));
package org.opendaylight.yangtools.binding.data.codec.gen.impl;
import com.google.common.base.Preconditions;
-
import org.opendaylight.yangtools.binding.data.codec.gen.spi.AbstractSource;
import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
protected final CharSequence leafSetEntryNode(final CharSequence value) {
return invoke(STREAM, "leafSetEntryNode", value);
-
}
protected final CharSequence startContainerNode(final CharSequence type, final CharSequence expected) {
}
protected final CharSequence escape(final String localName) {
- return '"'+localName+'"';
+ return '"' + localName + '"';
}
protected final CharSequence startUnkeyedList(final CharSequence type, final CharSequence expected) {
return invoke(STREAM, "startCase", (localName),expected);
}
-
protected final CharSequence anyxmlNode(final String name, final String value) throws IllegalArgumentException {
return invoke(STREAM, "anyxmlNode", escape(name),name);
}
}
protected final CharSequence forEach(final String iterable,final Type valueType,final CharSequence body) {
- return forEach(iterable,ITERATOR,valueType.getFullyQualifiedName(),CURRENT,body);
+ return forEach(iterable, ITERATOR, valueType.getFullyQualifiedName(), CURRENT, body);
}
protected final CharSequence classReference(final Type type) {
- return new StringBuilder().append(type.getFullyQualifiedName()).append(".class");
+ return type.getFullyQualifiedName() + ".class";
}
protected final CharSequence staticInvokeEmitter(final Type childType, final String name) {
@Override
protected DataObjectSerializerSource generateContainerSerializer(final GeneratedType type, final ContainerSchemaNode node) {
- return new AugmentableDataNodeContainerEmmiterSource(this, type, node) {
+ return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
@Override
public CharSequence emitStartEvent() {
return startContainerNode(classReference(type), getChildSizeFromSchema(node));
@Override
protected DataObjectSerializerSource generateNotificationSerializer(final GeneratedType type, final NotificationDefinition node) {
- return new AugmentableDataNodeContainerEmmiterSource(this, type, node) {
+ return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
@Override
public CharSequence emitStartEvent() {
return startContainerNode(classReference(type), getChildSizeFromSchema(node));
@Override
protected DataObjectSerializerSource generateCaseSerializer(final GeneratedType type, final ChoiceCaseNode node) {
- return new AugmentableDataNodeContainerEmmiterSource(this, type, node) {
+ return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
@Override
public CharSequence emitStartEvent() {
return startCaseNode(classReference(type),getChildSizeFromSchema(node));
@Override
protected DataObjectSerializerSource generateUnkeyedListEntrySerializer(final GeneratedType type, final ListSchemaNode node) {
- return new AugmentableDataNodeContainerEmmiterSource(this, type, node) {
+ return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
@Override
public CharSequence emitStartEvent() {
@Override
protected DataObjectSerializerSource generateMapEntrySerializer(final GeneratedType type, final ListSchemaNode node) {
- return new AugmentableDataNodeContainerEmmiterSource(this, type, node) {
+ return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
@Override
public CharSequence emitStartEvent() {
return startMapEntryNode(invoke(INPUT, "getKey"), getChildSizeFromSchema(node));
package org.opendaylight.yangtools.binding.data.codec.impl;
import com.google.common.base.Preconditions;
+import org.opendaylight.yangtools.yang.binding.Augmentation;
+import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-final class AugmentationNodeContext extends DataObjectCodecContext<AugmentationSchema> {
+final class AugmentationNodeContext<D extends DataObject & Augmentation<?>> extends DataObjectCodecContext<D,AugmentationSchema> {
public AugmentationNodeContext(final DataContainerCodecPrototype<AugmentationSchema> prototype) {
super(prototype);
}
@Override
- protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> normalizedNode) {
+ public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
Preconditions.checkArgument(normalizedNode instanceof AugmentationNode);
return createBindingProxy((AugmentationNode)normalizedNode);
}
+
+ @Override
+ protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+ return deserialize(normalizedNode);
+ }
+
}
\ No newline at end of file
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.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);
static final String GETTER_PREFIX = "get";
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, 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(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,
+ @Nullable NodeCodecContext<?> getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
final @Nonnull Collection<InstanceIdentifier.PathArgument> bindingArguments) {
- NodeCodecContext currentNode = root;
- ListNodeCodecContext currentList = null;
+ 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
} 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<?,?>) {
+ 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);
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);
}
}
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(InstanceIdentifier<T> path) {
+ // TODO Do we need defensive check here?
+ return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
+ }
+
+ @Override
+ public BindingCodecTreeNode<?> getSubtreeCodec(YangInstanceIdentifier path) {
+ return getCodecContextNode(path, null);
+ }
+
+ @Override
+ public BindingCodecTreeNode<?> getSubtreeCodec(SchemaPath path) {
+ throw new UnsupportedOperationException("Not implemented yet.");
+ }
}
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeFactory;
import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer;
import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeWriterFactory;
import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializerGenerator;
import org.opendaylight.yangtools.concepts.Delegator;
+import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
import org.opendaylight.yangtools.yang.binding.DataContainer;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.binding.Notification;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.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.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class BindingNormalizedNodeCodecRegistry implements DataObjectSerializerRegistry, BindingNormalizedNodeWriterFactory, BindingNormalizedNodeSerializer {
+public class BindingNormalizedNodeCodecRegistry implements DataObjectSerializerRegistry,
+ BindingCodecTreeFactory, BindingNormalizedNodeWriterFactory,
+ BindingNormalizedNodeSerializer {
private static final Logger LOG = LoggerFactory.getLogger(BindingNormalizedNodeCodecRegistry.class);
private final DataObjectSerializerGenerator generator;
private final LoadingCache<Class<? extends DataObject>, DataObjectSerializer> serializers;
- private BindingCodecContext codecContext;
+ private volatile BindingCodecContext codecContext;
public BindingNormalizedNodeCodecRegistry(final DataObjectSerializerGenerator generator) {
this.generator = Preconditions.checkNotNull(generator);
}
public void onBindingRuntimeContextUpdated(final BindingRuntimeContext context) {
- codecContext = new BindingCodecContext(context);
+ codecContext = create(context);
generator.onBindingRuntimeContextUpdated(context);
}
}
final List<PathArgument> builder = new ArrayList<>();
- final NodeCodecContext codec = codecContext.getCodecContextNode(path, builder);
+ final NodeCodecContext<?> codec = codecContext.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 = (DataObject) codec.dataFromNormalizedNode(data);
+ final DataObject lazyObj = codec.deserialize(data);
final InstanceIdentifier<?> bindingPath = InstanceIdentifier.create(builder);
return new SimpleEntry<InstanceIdentifier<?>, DataObject>(bindingPath, lazyObj);
}
@Override
public Notification fromNormalizedNodeNotification(final SchemaPath path, final ContainerNode data) {
- final NotificationCodecContext codec = codecContext.getNotificationContext(path);
- return (Notification) codec.dataFromNormalizedNode(data);
+ final NotificationCodecContext<?> codec = codecContext.getNotificationContext(path);
+ return codec.deserialize(data);
}
@Override
public DataObject fromNormalizedNodeRpcData(final SchemaPath path, final ContainerNode data) {
- final ContainerNodeCodecContext codec = codecContext.getRpcDataContext(path);
- return (DataObject) codec.dataFromNormalizedNode(data);
+ final ContainerNodeCodecContext<?> codec = codecContext.getRpcDataContext(path);
+ return codec.deserialize(data);
}
@Override
return codecContext.newNotificationWriter(notification, streamWriter);
}
-
@Override
public BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
final NormalizedNodeStreamWriter streamWriter) {
return codecContext.newRpcWriter(rpcInputOrOutput,streamWriter);
}
-
public <T extends DataObject> Function<Optional<NormalizedNode<?, ?>>, Optional<T>> deserializeFunction(final InstanceIdentifier<T> path) {
- final DataObjectCodecContext<?> ctx = (DataObjectCodecContext<?>) codecContext.getCodecContextNode(path, null);
+ final DataObjectCodecContext<?,?> ctx = (DataObjectCodecContext<?,?>) codecContext.getCodecContextNode(path, null);
return new DeserializeFunction<T>(ctx);
}
+ @Override
+ public BindingCodecContext create(BindingRuntimeContext context) {
+ return new BindingCodecContext(context, this);
+ }
+
+ @Override
+ public BindingCodecContext create(SchemaContext context, Class<?>... bindingClasses) {
+ ModuleInfoBackedContext strategy = ModuleInfoBackedContext.create();
+ for (Class<?> bindingCls : bindingClasses) {
+ try {
+ strategy.registerModuleInfo(BindingReflections.getModuleInfo(bindingCls));
+ } catch (Exception e) {
+ throw new IllegalStateException(
+ "Could not create BindingRuntimeContext from class " + bindingCls.getName(),
+ e);
+ }
+ }
+ BindingRuntimeContext runtimeCtx = BindingRuntimeContext.create(strategy, context);
+ return create(runtimeCtx);
+ }
+
- private static class DeserializeFunction<T> implements Function<Optional<NormalizedNode<?, ?>>, Optional<T>> {
- private final DataObjectCodecContext<?> ctx;
+ private static final class DeserializeFunction<T> implements Function<Optional<NormalizedNode<?, ?>>, Optional<T>> {
+ private final DataObjectCodecContext<?,?> ctx;
- public DeserializeFunction(final DataObjectCodecContext<?> ctx) {
- super();
+ DeserializeFunction(final DataObjectCodecContext<?,?> ctx) {
this.ctx = ctx;
}
@SuppressWarnings("unchecked")
@Override
public Optional<T> apply(final Optional<NormalizedNode<?, ?>> input) {
- if(input.isPresent()) {
- return Optional.of((T) ctx.dataFromNormalizedNode(input.get()));
+ if (input.isPresent()) {
+ return Optional.of((T) ctx.deserialize(input.get()));
}
return Optional.absent();
}
}
- private class GeneratorLoader extends CacheLoader<Class<? extends DataContainer>, DataObjectSerializer> {
-
+ private final class GeneratorLoader extends CacheLoader<Class<? extends DataContainer>, DataObjectSerializer> {
@Override
public DataObjectSerializer load(final Class<? extends DataContainer> key) throws Exception {
final DataObjectSerializerImplementation prototype = generator.getSerializer(key);
}
}
- private class DataObjectSerializerProxy implements DataObjectSerializer,
- Delegator<DataObjectSerializerImplementation> {
-
+ private final class DataObjectSerializerProxy implements DataObjectSerializer, Delegator<DataObjectSerializerImplementation> {
private final DataObjectSerializerImplementation delegate;
DataObjectSerializerProxy(final DataObjectSerializerImplementation delegate) {
class BindingToNormalizedStreamWriter implements BindingStreamEventWriter, Delegator<NormalizedNodeStreamWriter> {
private final NormalizedNodeStreamWriter delegate;
- private final Deque<NodeCodecContext> schema = new ArrayDeque<>();
- private final NodeCodecContext rootNodeSchema;
+ private final Deque<NodeCodecContext<?>> schema = new ArrayDeque<>();
+ private final NodeCodecContext<?> rootNodeSchema;
- public BindingToNormalizedStreamWriter(final NodeCodecContext schema, final NormalizedNodeStreamWriter delegate) {
+ public BindingToNormalizedStreamWriter(final NodeCodecContext<?> schema, final NormalizedNodeStreamWriter delegate) {
this.delegate = Preconditions.checkNotNull(delegate, "Delegate must not be null");
this.rootNodeSchema = Preconditions.checkNotNull(schema);
}
- private NodeCodecContext current() {
+ private NodeCodecContext<?> current() {
return schema.peek();
}
private NodeIdentifier duplicateSchemaEnter() {
- final NodeCodecContext next;
+ final NodeCodecContext<?> next;
if (current() == null) {
// Entry of first node
next = rootNodeSchema;
return (NodeIdentifier) current().getDomPathArgument();
}
+ @SuppressWarnings({"unchecked", "rawtypes"})
private <T extends YangInstanceIdentifier.PathArgument> T enter(final Class<?> name, final Class<T> identifier) {
- final NodeCodecContext next;
+ final NodeCodecContext<?> next;
if (current() == null) {
// Entry of first node
next = rootNodeSchema;
} else {
Preconditions.checkArgument((current() instanceof DataContainerCodecContext), "Could not start node %s",
name);
- next = ((DataContainerCodecContext<?>) current()).getStreamChild(name);
+ next = ((DataContainerCodecContext<?,?>) current()).streamChild((Class) name);
}
this.schema.push(next);
- @SuppressWarnings("unchecked")
T arg = (T) next.getDomPathArgument();
return arg;
}
private <T extends YangInstanceIdentifier.PathArgument> T enter(final String localName, final Class<T> identifier) {
- NodeCodecContext current = current();
- NodeCodecContext next = ((DataObjectCodecContext<?>) current).getLeafChild(localName);
+ NodeCodecContext<?> current = current();
+ NodeCodecContext<?> next = ((DataObjectCodecContext<?,?>) current).getLeafChild(localName);
this.schema.push(next);
@SuppressWarnings("unchecked")
T arg = (T) next.getDomPathArgument();
@Override
public void endNode() throws IOException {
- NodeCodecContext left = schema.pop();
+ NodeCodecContext<?> left = schema.pop();
// NormalizedNode writer does not have entry into case, but into choice
// so for leaving case, we do not emit endNode.
if (!(left instanceof CaseNodeCodecContext)) {
}
private Map.Entry<NodeIdentifier, Object> serializeLeaf(final String localName, final Object value) {
- Preconditions.checkArgument(current() instanceof DataObjectCodecContext<?>);
+ Preconditions.checkArgument(current() instanceof DataObjectCodecContext);
- DataObjectCodecContext<?> currentCasted = (DataObjectCodecContext<?>) current();
- LeafNodeCodecContext leafContext = currentCasted.getLeafChild(localName);
+ DataObjectCodecContext<?,?> currentCasted = (DataObjectCodecContext<?,?>) current();
+ LeafNodeCodecContext<?> leafContext = currentCasted.getLeafChild(localName);
NodeIdentifier domArg = (NodeIdentifier) leafContext.getDomPathArgument();
Object domValue = leafContext.getValueCodec().serialize(value);
@Override
public void leafSetEntryNode(final Object value) throws IOException, IllegalArgumentException {
- LeafNodeCodecContext ctx = (LeafNodeCodecContext) current();
+ LeafNodeCodecContext<?> ctx = (LeafNodeCodecContext<?>) current();
getDelegate().leafSetEntryNode(ctx.getValueCodec().serialize(value));
}
@Override
public void startMapEntryNode(final Identifier<?> key, final int childSizeHint) throws IOException, IllegalArgumentException {
duplicateSchemaEnter();
- NodeIdentifierWithPredicates identifier = ((KeyedListNodeCodecContext) current()).serialize(key);
+ NodeIdentifierWithPredicates identifier = ((KeyedListNodeCodecContext<?>) current()).serialize(key);
getDelegate().startMapEntryNode(identifier, childSizeHint);
};
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSortedMap;
-
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.Callable;
-
import org.opendaylight.yangtools.binding.data.codec.impl.ValueTypeCodec.SchemaUnawareCodec;
import org.opendaylight.yangtools.yang.binding.BindingMapping;
import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
* for construction of bits object.
*/
for (String value : valueGetters.keySet()) {
- if (casted.contains(value)) {
- args[currentArg] = Boolean.TRUE;
- } else {
- args[currentArg] = Boolean.FALSE;
- }
- currentArg++;
+ args[currentArg++] = casted.contains(value);
}
try {
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.impl;
+
+import com.google.common.base.Preconditions;
+import java.util.Set;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeCachingCodec;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+class CachingNormalizedNodeCodecImpl<D extends DataObject> implements BindingNormalizedNodeCachingCodec<D>{
+
+ private final Set<Class<? extends DataObject>> cachedValues;
+ private final DataContainerCodecContext<D, ?> context;
+
+ CachingNormalizedNodeCodecImpl(DataContainerCodecContext<D, ?> subtreeRoot, Set<Class<? extends DataObject>> cacheSpec) {
+ this.context = Preconditions.checkNotNull(subtreeRoot);
+ this.cachedValues = Preconditions.checkNotNull(cacheSpec);
+ }
+
+ @Override
+ public D deserialize(NormalizedNode<?, ?> data) {
+ return context.deserialize(data);
+ }
+
+ @Override
+ public NormalizedNode<?, ?> serialize(D data) {
+ // FIXME: Add real-class based serialization.
+ return context.serialize(data);
+ }
+
+ @Override
+ public void close() {
+ // NOOP as of now.
+ }
+
+}
import com.google.common.base.Preconditions;
import java.util.List;
+import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-final class CaseNodeCodecContext extends DataObjectCodecContext<ChoiceCaseNode> {
+final class CaseNodeCodecContext<D extends DataObject> extends DataObjectCodecContext<D,ChoiceCaseNode> {
public CaseNodeCodecContext(final DataContainerCodecPrototype<ChoiceCaseNode> prototype) {
super(prototype);
}
}
@Override
- protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> normalizedNode) {
+ public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
Preconditions.checkState(normalizedNode instanceof ChoiceNode);
return createBindingProxy((ChoiceNode) normalizedNode);
}
+
+ @Override
+ protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+ return deserialize(normalizedNode);
+ }
}
\ No newline at end of file
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
-
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-final class ChoiceNodeCodecContext extends DataContainerCodecContext<ChoiceNode> {
+final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D,ChoiceSchemaNode> {
private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChild;
private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byClass;
private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClass;
- public ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceNode> prototype) {
+ public ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceSchemaNode> prototype) {
super(prototype);
Map<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChildBuilder = new HashMap<>();
Map<Class<?>, DataContainerCodecPrototype<?>> byClassBuilder = new HashMap<>();
Map<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClassBuilder = new HashMap<>();
Set<Class<?>> potentialSubstitutions = new HashSet<>();
// Walks all cases for supplied choice in current runtime context
- for (Class<?> caze : factory().getRuntimeContext().getCases(bindingClass())) {
+ for (Class<?> caze : factory().getRuntimeContext().getCases(getBindingClass())) {
// We try to load case using exact match thus name
// and original schema must equals
DataContainerCodecPrototype<ChoiceCaseNode> cazeDef = loadCase(caze);
if (cazeDef != null) {
byClassBuilder.put(cazeDef.getBindingClass(), cazeDef);
// Updates collection of case children
- for (Class<? extends DataObject> cazeChild : BindingReflections.getChildrenClasses((Class<? extends DataObject>) caze)) {
+ @SuppressWarnings("unchecked")
+ Class<? extends DataObject> cazeCls = (Class<? extends DataObject>) caze;
+ for (Class<? extends DataObject> cazeChild : BindingReflections.getChildrenClasses(cazeCls)) {
byCaseChildClassBuilder.put(cazeChild, cazeDef);
}
// Updates collection of YANG instance identifier to case
byCaseChildClass = ImmutableMap.copyOf(byCaseChildClassBuilder);
}
+
+ @SuppressWarnings("unchecked")
@Override
- protected DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) {
+ public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(Class<DV> childClass) {
DataContainerCodecPrototype<?> child = byClass.get(childClass);
Preconditions.checkArgument(child != null,"Supplied class is not valid case",childClass);
- return child.get();
+ return (DataContainerCodecContext<DV, ?>) child.get();
}
+
+ @SuppressWarnings("unchecked")
@Override
- protected Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass) {
+ public <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
+ Class<DV> childClass) {
DataContainerCodecPrototype<?> child = byClass.get(childClass);
if(child != null) {
- return Optional.<DataContainerCodecContext<?>>of(child.get());
+ return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV, ?>) child.get());
}
return Optional.absent();
}
}
@Override
- protected NodeCodecContext getYangIdentifierChild(final YangInstanceIdentifier.PathArgument arg) {
+ public NodeCodecContext<?> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
DataContainerCodecPrototype<?> cazeProto = byYangCaseChild.get(arg);
Preconditions.checkArgument(cazeProto != null, "Argument %s is not valid child of %s", arg, schema());
- return cazeProto.get().getYangIdentifierChild(arg);
+ return cazeProto.get().yangPathArgumentChild(arg);
}
+ @SuppressWarnings("unchecked")
@Override
- protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> data) {
+ public D deserialize(final NormalizedNode<?, ?> data) {
Preconditions
.checkArgument(data instanceof org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode);
NormalizedNodeContainer<?, ?, NormalizedNode<?,?>> casted = (NormalizedNodeContainer<?, ?, NormalizedNode<?,?>>) data;
return null;
}
DataContainerCodecPrototype<?> caze = byYangCaseChild.get(first.getIdentifier());
- return caze.get().dataFromNormalizedNode(data);
+ return (D) caze.get().deserialize(data);
}
- public DataContainerCodecContext<?> getCazeByChildClass(final Class<? extends DataObject> type) {
- return byCaseChildClass.get(type).get();
+ @Nullable DataContainerCodecContext<?,?> getCazeByChildClass(final @Nonnull Class<? extends DataObject> type) {
+ final DataContainerCodecPrototype<?> protoCtx = byCaseChildClass.get(type);
+ if(protoCtx != null) {
+ return protoCtx.get();
+ }
+ return null;
+ }
+
+ @Override
+ protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+ return deserialize(normalizedNode);
}
}
package org.opendaylight.yangtools.binding.data.codec.impl;
import com.google.common.base.Preconditions;
+import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-final class ContainerNodeCodecContext extends DataObjectCodecContext<ContainerSchemaNode> {
+final class ContainerNodeCodecContext<D extends DataObject> extends DataObjectCodecContext<D,ContainerSchemaNode> {
ContainerNodeCodecContext(final DataContainerCodecPrototype<ContainerSchemaNode> prototype) {
super(prototype);
}
@Override
- protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> data) {
+ public D deserialize(final NormalizedNode<?, ?> data) {
Preconditions.checkState(data instanceof ContainerNode);
return createBindingProxy((ContainerNode) data);
}
+ @Override
+ protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+ return deserialize(normalizedNode);
+ }
+
}
\ No newline at end of file
package org.opendaylight.yangtools.binding.data.codec.impl;
import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableCollection;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
import java.util.List;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeCachingCodec;
import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+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;
-abstract class DataContainerCodecContext<T> extends NodeCodecContext {
+abstract class DataContainerCodecContext<D extends DataObject,T> extends NodeCodecContext<D> {
private final DataContainerCodecPrototype<T> prototype;
+ private volatile DataObjectSerializer eventStreamSerializer;
protected DataContainerCodecContext(final DataContainerCodecPrototype<T> prototype) {
this.prototype = prototype;
* @return Context of child
* @throws IllegalArgumentException If supplied argument does not represent valid child.
*/
- protected abstract NodeCodecContext getYangIdentifierChild(final YangInstanceIdentifier.PathArgument arg);
+ @Override
+ public abstract NodeCodecContext<?> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg);
/**
* Returns nested node context using supplied Binding Instance Identifier
* and adds YANG instance identifiers to supplied list.
*
* @param arg Binding Instance Identifier Argument
- * @return Context of child
+ * @return Context of child or null if supplied {@code arg} does not represent valid child.
* @throws IllegalArgumentException If supplied argument does not represent valid child.
*/
- protected DataContainerCodecContext<?> getIdentifierChild(final InstanceIdentifier.PathArgument arg,
+ @Override
+ public @Nullable DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
final List<YangInstanceIdentifier.PathArgument> builder) {
- final DataContainerCodecContext<?> child = getStreamChild(arg.getType());
- if (builder != null) {
- child.addYangPathArgument(arg,builder);
+ final DataContainerCodecContext<?,?> child = streamChild(arg.getType());
+ if(child != null) {
+ if (builder != null) {
+ child.addYangPathArgument(arg,builder);
+ }
+ return child;
}
- return child;
+ throw new IllegalArgumentException("SUpplied argument is not valid child");
}
/**
return prototype.getBindingArg();
}
- protected final Class<?> bindingClass() {
- return prototype.getBindingClass();
+ @SuppressWarnings("unchecked")
+ @Override
+ public final Class<D> getBindingClass() {
+ return Class.class.cast(prototype.getBindingClass());
}
/**
* must issue getChild(ChoiceClass).getChild(CaseClass).
*
* @param childClass
- * @return Context of child
+ * @return Context of child node or null, if supplied class is not subtree child
* @throws IllegalArgumentException If supplied child class is not valid in specified context.
*/
- protected abstract DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) throws IllegalArgumentException;
+ @Override
+ public abstract @Nullable <DV extends DataObject> DataContainerCodecContext<DV,?> streamChild(final Class<DV> childClass) throws IllegalArgumentException;
/**
- *
- * Returns child context as if it was walked by
- * {@link BindingStreamEventWriter}. This means that to enter case, one
- * must issue getChild(ChoiceClass).getChild(CaseClass).
- *
- * @param childClass
- * @return Context of child or Optional absent is supplied class is not applicable in context.
- */
- protected abstract Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass);
+ *
+ * Returns child context as if it was walked by
+ * {@link BindingStreamEventWriter}. This means that to enter case, one
+ * must issue getChild(ChoiceClass).getChild(CaseClass).
+ *
+ * @param childClass
+ * @return Context of child or Optional absent is supplied class is not applicable in context.
+ */
+ @Override
+ public abstract <DV extends DataObject> Optional<DataContainerCodecContext<DV,?>> possibleStreamChild(final Class<DV> childClass);
@Override
public String toString() {
return getClass().getSimpleName() + " [" + prototype.getBindingClass() + "]";
}
+ @Override
+ public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
+ ImmutableCollection<Class<? extends DataObject>> cacheSpecifier) {
+ return new CachingNormalizedNodeCodecImpl<D>(this,ImmutableSet.copyOf(cacheSpecifier));
+ }
+
+ BindingStreamEventWriter createWriter(NormalizedNodeStreamWriter domWriter) {
+ return new BindingToNormalizedStreamWriter(this, domWriter);
+ }
+
+ DataObjectSerializer eventStreamSerializer() {
+ if(eventStreamSerializer == null) {
+ eventStreamSerializer = factory().getEventStreamSerializer(getBindingClass());
+ }
+ return eventStreamSerializer;
+ }
+
+ @Override
+ public NormalizedNode<?, ?> serialize(D data) {
+ final NormalizedNodeResult result = new NormalizedNodeResult();
+ // We create DOM stream writer which produces normalized nodes
+ final NormalizedNodeStreamWriter domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
+ writeAsNormalizedNode(data, domWriter);
+ return result.getResult();
+ }
+
+ @Override
+ public void writeAsNormalizedNode(D data, NormalizedNodeStreamWriter writer) {
+ try {
+ eventStreamSerializer().serialize(data, createWriter(writer));
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed to serialize Binding DTO",e);
+ }
+ }
+
}
\ No newline at end of file
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-class DataContainerCodecPrototype<T> implements NodeContextSupplier {
+final class DataContainerCodecPrototype<T> implements NodeContextSupplier {
private final T schema;
private final QNameModule namespace;
private final Class<?> bindingClass;
private final InstanceIdentifier.Item<?> bindingArg;
private final YangInstanceIdentifier.PathArgument yangArg;
- private volatile DataContainerCodecContext<T> instance = null;
+ private volatile DataContainerCodecContext<?,T> instance = null;
+ @SuppressWarnings({"rawtypes", "unchecked"})
private DataContainerCodecPrototype(final Class<?> cls, final YangInstanceIdentifier.PathArgument arg, final T nodeSchema,
final CodecContextFactory factory) {
super();
}
}
+ @SuppressWarnings({"rawtypes", "unchecked"})
private DataContainerCodecPrototype(final Class<?> cls, final YangInstanceIdentifier.PathArgument arg, final T nodeSchema,
- final CodecContextFactory factory,final DataContainerCodecContext<T> instance) {
+ final CodecContextFactory factory,final DataContainerCodecContext<?,T> instance) {
super();
this.yangArg = arg;
this.schema = nodeSchema;
}
@Override
- public DataContainerCodecContext<T> get() {
- DataContainerCodecContext<T> tmp = instance;
+ public DataContainerCodecContext<?,T> get() {
+ DataContainerCodecContext<?,T> tmp = instance;
if (tmp == null) {
synchronized (this) {
tmp = instance;
@GuardedBy("this")
@SuppressWarnings({ "rawtypes", "unchecked" })
- private DataContainerCodecContext createInstance() {
+ private DataContainerCodecContext<?,T> createInstance() {
// FIXME: make protected abstract
if (schema instanceof ContainerSchemaNode) {
- return new ContainerNodeCodecContext((DataContainerCodecPrototype) this);
+ return new ContainerNodeCodecContext(this);
} else if (schema instanceof ListSchemaNode) {
if (Identifiable.class.isAssignableFrom(getBindingClass())) {
- return new KeyedListNodeCodecContext((DataContainerCodecPrototype) this);
+ return new KeyedListNodeCodecContext(this);
} else {
- return new ListNodeCodecContext((DataContainerCodecPrototype) this);
+ return new ListNodeCodecContext(this);
}
- } else if (schema instanceof ChoiceNode) {
- return new ChoiceNodeCodecContext((DataContainerCodecPrototype) this);
+ } else if (schema instanceof ChoiceSchemaNode) {
+ return new ChoiceNodeCodecContext(this);
} else if (schema instanceof AugmentationSchema) {
- return new AugmentationNodeContext((DataContainerCodecPrototype) this);
+ return new AugmentationNodeContext(this);
} else if (schema instanceof ChoiceCaseNode) {
- return new CaseNodeCodecContext((DataContainerCodecPrototype) this);
+ return new CaseNodeCodecContext(this);
}
throw new IllegalArgumentException("Unsupported type " + bindingClass + " " + schema);
}
boolean isChoice() {
- return schema instanceof ChoiceNode;
+ return schema instanceof ChoiceSchemaNode;
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataContainerCodecContext<T> {
+abstract class DataObjectCodecContext<D extends DataObject,T extends DataNodeContainer> extends DataContainerCodecContext<D,T> {
private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
private static final Lookup LOOKUP = MethodHandles.publicLookup();
private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
}
};
- private final ImmutableMap<String, LeafNodeCodecContext> leafChild;
+ private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
private final MethodHandle proxyConstructor;
- // FIXME: this field seems to be unused
- private final Method augmentationGetter;
-
protected DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
super(prototype);
- this.leafChild = factory().getLeafNodes(bindingClass(), schema());
+ this.leafChild = factory().getLeafNodes(getBindingClass(), schema());
- Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass());
+ final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
- Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
- SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
- Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
- Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
+ final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
+ final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
+ final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
+ final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
// Adds leaves to mapping
- for (LeafNodeCodecContext leaf : leafChild.values()) {
+ for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
byMethodBuilder.put(leaf.getGetter(), leaf);
byYangBuilder.put(leaf.getDomPathArgument(), leaf);
}
- for (Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
- DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
+ for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
+ final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
byMethodBuilder.put(childDataObj.getValue(), childProto);
byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
byYangBuilder.put(childProto.getYangArg(), childProto);
if (childProto.isChoice()) {
- ChoiceNodeCodecContext choice = (ChoiceNodeCodecContext) childProto.get();
- for(Class<?> cazeChild : choice.getCaseChildrenClasses()) {
+ final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
+ for(final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
byBindingArgClassBuilder.put(cazeChild, childProto);
}
}
}
this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
- if (Augmentable.class.isAssignableFrom(bindingClass())) {
- try {
- augmentationGetter = bindingClass().getMethod("getAugmentation", Class.class);
- } catch (NoSuchMethodException | SecurityException e) {
- throw new IllegalStateException("Could not get required method.",e);
- }
- ImmutableMap<AugmentationIdentifier, Type> augmentations = factory().getRuntimeContext()
+ if (Augmentable.class.isAssignableFrom(getBindingClass())) {
+ final ImmutableMap<AugmentationIdentifier, Type> augmentations = factory().getRuntimeContext()
.getAvailableAugmentationTypes(schema());
- for (Entry<AugmentationIdentifier, Type> augment : augmentations.entrySet()) {
- DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
+ for (final Entry<AugmentationIdentifier, Type> augment : augmentations.entrySet()) {
+ final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
if (augProto != null) {
byYangBuilder.put(augProto.getYangArg(), augProto);
byStreamClassBuilder.put(augProto.getBindingClass(), augProto);
}
}
- } else {
- augmentationGetter = null;
}
this.byYang = ImmutableMap.copyOf(byYangBuilder);
byBindingArgClassBuilder.putAll(byStreamClass);
this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
- final Class<?> proxyClass = Proxy.getProxyClass(bindingClass().getClassLoader(), new Class[] { bindingClass() });
+ final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(), new Class[] { getBindingClass() });
try {
proxyConstructor = LOOKUP.findConstructor(proxyClass, CONSTRUCTOR_TYPE).asType(DATAOBJECT_TYPE);
} catch (NoSuchMethodException | IllegalAccessException e) {
}
}
+
+ @SuppressWarnings("unchecked")
@Override
- protected DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) {
+ public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(final Class<DV> childClass) {
DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
if (childProto != null) {
- return childProto.get();
+ return (DataContainerCodecContext<DV,?>) childProto.get();
}
if (Augmentation.class.isAssignableFrom(childClass)) {
*
* FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
*/
- Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
- if ((bindingClass().equals(augTarget))) {
- for (DataContainerCodecPrototype<?> realChild : byStreamClass.values()) {
+ @SuppressWarnings("rawtypes")
+ final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
+ if ((getBindingClass().equals(augTarget))) {
+ for (final DataContainerCodecPrototype<?> realChild : byStreamClass.values()) {
if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
&& BindingReflections.isSubstitutionFor(childClass,realChild.getBindingClass())) {
childProto = realChild;
}
}
Preconditions.checkArgument(childProto != null, " Child %s is not valid child.",childClass);
- return childProto.get();
+ return (DataContainerCodecContext<DV, ?>) childProto.get();
}
+
+ @SuppressWarnings("unchecked")
@Override
- protected Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass) {
- DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
+ public <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
+ Class<DV> childClass) {
+ final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
if(childProto != null) {
- return Optional.<DataContainerCodecContext<?>>of(childProto.get());
+ return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV,?>) childProto.get());
}
return Optional.absent();
}
@Override
- protected DataContainerCodecContext<?> getIdentifierChild(final InstanceIdentifier.PathArgument arg,
+ public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
final List<YangInstanceIdentifier.PathArgument> builder) {
- Class<? extends DataObject> argType = arg.getType();
- DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
- Preconditions.checkArgument(ctxProto != null,"Invalid child");
-
- DataContainerCodecContext<?> context = ctxProto.get();
- if(context instanceof ChoiceNodeCodecContext) {
- ChoiceNodeCodecContext casted = (ChoiceNodeCodecContext) context;
- casted.addYangPathArgument(arg, builder);
- DataContainerCodecContext<?> caze = casted.getCazeByChildClass(arg.getType());
- caze.addYangPathArgument(arg, builder);
- return caze.getIdentifierChild(arg, builder);
+ final Class<? extends DataObject> argType = arg.getType();
+ final DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
+ if(ctxProto != null) {
+ final DataContainerCodecContext<?,?> context = ctxProto.get();
+ if(context instanceof ChoiceNodeCodecContext) {
+ final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
+ final DataContainerCodecContext<?,?> caze = choice.getCazeByChildClass(arg.getType());
+ if(caze != null) {
+ choice.addYangPathArgument(arg, builder);
+ caze.addYangPathArgument(arg, builder);
+ return caze.bindingPathArgumentChild(arg, builder);
+ }
+ return null;
+ }
+ context.addYangPathArgument(arg, builder);
+ return context;
}
- context.addYangPathArgument(arg, builder);
- return context;
+ // Argument is not valid child.
+ return null;
}
+ @SuppressWarnings("unchecked")
@Override
- protected NodeCodecContext getYangIdentifierChild(YangInstanceIdentifier.PathArgument arg) {
+ public NodeCodecContext<D> yangPathArgumentChild(YangInstanceIdentifier.PathArgument arg) {
if(arg instanceof NodeIdentifierWithPredicates) {
arg = new NodeIdentifier(arg.getNodeType());
}
- NodeContextSupplier childSupplier = byYang.get(arg);
+ final NodeContextSupplier childSupplier = byYang.get(arg);
Preconditions.checkArgument(childSupplier != null, "Argument %s is not valid child of %s", arg, schema());
- return childSupplier.get();
+ return (NodeCodecContext<D>) childSupplier.get();
}
- protected final LeafNodeCodecContext getLeafChild(final String name) {
- final LeafNodeCodecContext value = leafChild.get(name);
- Preconditions.checkArgument(value != null, "Leaf %s is not valid for %s", name, bindingClass());
+ protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
+ final LeafNodeCodecContext<?> value = leafChild.get(name);
+ Preconditions.checkArgument(value != null, "Leaf %s is not valid for %s", name, getBindingClass());
return value;
}
private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
- DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
+ final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
// Direct instantiation or use in same module in which grouping
// was defined.
DataSchemaNode sameName;
try {
sameName = schema().getDataChildByName(origDef.getQName());
- } catch (IllegalArgumentException e) {
+ } catch (final IllegalArgumentException e) {
sameName = null;
}
final DataSchemaNode childSchema;
}
} else {
// We are looking for instantiation via uses in other module
- QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
- DataSchemaNode potential = schema().getDataChildByName(instantiedName);
+ final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
+ final DataSchemaNode potential = schema().getDataChildByName(instantiedName);
// We check if it is really instantiated from same
// definition as class was derived
if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
}
private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
- ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
+ final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
@SuppressWarnings("rawtypes")
final Class augClass;
try {
augClass = loader.loadClass(value);
- } catch (ClassNotFoundException e) {
+ } catch (final ClassNotFoundException e) {
LOG.warn("Failed to load augmentation prototype for {}", value, e);
return null;
}
- Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
+ @SuppressWarnings("unchecked")
+ final Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
.getResolvedAugmentationSchema(schema(), augClass);
return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
}
@SuppressWarnings("rawtypes")
Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
- NodeCodecContext childContext = byMethod.get(method).get();
- Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
+ final NodeCodecContext<?> childContext = byMethod.get(method).get();
+ @SuppressWarnings("unchecked")
+ final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
if (domChild.isPresent()) {
- return childContext.dataFromNormalizedNode(domChild.get());
+ return childContext.deserializeObject(domChild.get());
}
return null;
}
- protected final DataObject createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
+ protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
try {
- return (DataObject) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject(this, node));
- } catch (Throwable e) {
+ return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
+ } catch (final Throwable e) {
throw Throwables.propagate(e);
}
}
+ @SuppressWarnings("unchecked")
public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
@SuppressWarnings("rawtypes")
- Map map = new HashMap<>();
+ final Map map = new HashMap<>();
- for(DataContainerCodecPrototype<?> value : byStreamClass.values()) {
+ for(final DataContainerCodecPrototype<?> value : byStreamClass.values()) {
if(Augmentation.class.isAssignableFrom(value.getBindingClass())) {
- Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
+ final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
if(augData.isPresent()) {
- map.put(value.getBindingClass(), value.get().dataFromNormalizedNode(augData.get()));
+ map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
}
}
}
import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
-class EnumerationCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
+final class EnumerationCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
- ImmutableBiMap<String, Enum<?>> yangValueToBinding;
+ private final ImmutableBiMap<String, Enum<?>> yangValueToBinding;
public EnumerationCodec(final Class<? extends Enum<?>> enumeration, final Map<String, Enum<?>> schema) {
super(enumeration);
yangValueToBinding = ImmutableBiMap.copyOf(schema);
}
-
static Callable<EnumerationCodec> loader(final Class<?> returnType,
final EnumTypeDefinition enumSchema) {
Preconditions.checkArgument(Enum.class.isAssignableFrom(returnType));
};
}
-
@Override
public Object deserialize(final Object input) {
Enum<?> value = yangValueToBinding.get(input);
package org.opendaylight.yangtools.binding.data.codec.impl;
import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
-import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
final class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
+ private static final Comparator<QName> KEYARG_COMPARATOR = new Comparator<QName>() {
+ @Override
+ public int compare(final QName q1, final QName q2) {
+ return q1.getLocalName().compareToIgnoreCase(q2.getLocalName());
+ }
+ };
private static final Lookup LOOKUP = MethodHandles.publicLookup();
- private final MethodHandle ctor;
- private final MethodHandle ctorInvoker;
private final Map<QName, ValueContext> keyValueContexts;
+ private final List<QName> keysInBindingOrder;
private final ListSchemaNode schema;
private final Class<?> identifiable;
+ private final MethodHandle ctorInvoker;
+ private final MethodHandle ctor;
public IdentifiableItemCodec(final ListSchemaNode schema, final Class<? extends Identifier<?>> keyClass,
final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
keys.put(qname, keyValueContexts.get(qname));
}
this.keyValueContexts = ImmutableMap.copyOf(keys);
+
+ /*
+ * When instantiating binding objects we need to specify constructor arguments
+ * in alphabetic order. We play a couple of tricks here to optimize CPU/memory
+ * trade-offs.
+ *
+ * We do not have to perform a sort if the source collection has less than two
+ * elements.
+
+ * We always perform an ImmutableList.copyOf(), as that will turn into a no-op
+ * if the source is already immutable. It will also produce optimized implementations
+ * for empty and singleton collections.
+ *
+ * BUG-2755: remove this if order is made declaration-order-dependent
+ */
+ final List<QName> unsortedKeys = schema.getKeyDefinition();
+ final List<QName> sortedKeys;
+ if (unsortedKeys.size() > 1) {
+ final List<QName> tmp = new ArrayList<>(unsortedKeys);
+ Collections.sort(tmp, KEYARG_COMPARATOR);
+ sortedKeys = tmp;
+ } else {
+ sortedKeys = unsortedKeys;
+ }
+
+ this.keysInBindingOrder = ImmutableList.copyOf(sortedKeys);
}
@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[] bindingValues = new Object[keysInBindingOrder.size()];
+ int offset = 0;
+
+ for (final QName key : keysInBindingOrder) {
final Object yangValue = input.getKeyValues().get(key);
- bindingValues.add(keyValueContexts.get(key).deserialize(yangValue));
+ bindingValues[offset++] = keyValueContexts.get(key).deserialize(yangValue);
}
final Identifier<?> identifier;
try {
- identifier = (Identifier<?>) ctorInvoker.invokeExact(ctor, bindingValues.toArray());
+ identifier = (Identifier<?>) ctorInvoker.invokeExact(ctor, bindingValues);
} catch (Throwable e) {
throw Throwables.propagate(e);
}
@Override
public InstanceIdentifier<?> deserialize(final YangInstanceIdentifier input) {
final List<InstanceIdentifier.PathArgument> builder = new ArrayList<>();
- final NodeCodecContext codec = context.getCodecContextNode(input, builder);
+ final NodeCodecContext<?> codec = context.getCodecContextNode(input, builder);
if (codec == null) {
return null;
}
import java.lang.reflect.Method;
import java.util.List;
import org.opendaylight.yangtools.concepts.Codec;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+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.data.api.schema.NormalizedNodeContainer;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-final class KeyedListNodeCodecContext extends ListNodeCodecContext {
+final class KeyedListNodeCodecContext<D extends DataObject & Identifiable<?>> extends ListNodeCodecContext<D> {
private final Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> codec;
private final Method keyGetter;
KeyedListNodeCodecContext(final DataContainerCodecPrototype<ListSchemaNode> prototype) {
super(prototype);
- this.codec = factory().getPathArgumentCodec(bindingClass(), schema());
+ this.codec = factory().getPathArgumentCodec(getBindingClass(), schema());
try {
- this.keyGetter = bindingClass().getMethod("getKey");
+ this.keyGetter = getBindingClass().getMethod("getKey");
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Required method not available", e);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
NodeIdentifierWithPredicates serialize(final Identifier<?> key) {
- return codec.serialize(new IdentifiableItem(bindingClass(), key));
+ return codec.serialize(new IdentifiableItem(getBindingClass(), key));
}
}
import org.opendaylight.yangtools.binding.data.codec.util.AugmentationReader;
import org.opendaylight.yangtools.yang.binding.Augmentable;
import org.opendaylight.yangtools.yang.binding.Augmentation;
+import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-class LazyDataObject implements InvocationHandler, AugmentationReader {
+class LazyDataObject<D extends DataObject> implements InvocationHandler, AugmentationReader {
private static final Logger LOG = LoggerFactory.getLogger(LazyDataObject.class);
private static final String GET_IMPLEMENTED_INTERFACE = "getImplementedInterface";
private final ConcurrentHashMap<Method, Object> cachedData = new ConcurrentHashMap<>();
private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
- private final DataObjectCodecContext<?> context;
+ private final DataObjectCodecContext<D,?> context;
private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
private volatile Integer cachedHashcode = null;
@SuppressWarnings({ "rawtypes", "unchecked" })
- LazyDataObject(final DataObjectCodecContext<?> ctx, final NormalizedNodeContainer data) {
+ LazyDataObject(final DataObjectCodecContext<D,?> ctx, final NormalizedNodeContainer data) {
this.context = Preconditions.checkNotNull(ctx, "Context must not be null");
this.data = Preconditions.checkNotNull(data, "Data must not be null");
}
if (method.getParameterTypes().length == 0) {
final String name = method.getName();
if (GET_IMPLEMENTED_INTERFACE.equals(name)) {
- return context.bindingClass();
+ return context.getBindingClass();
} else if (TO_STRING.equals(name)) {
return bindingToString();
} else if (HASHCODE.equals(name)) {
if (other == null) {
return false;
}
- if (!context.bindingClass().isAssignableFrom(other.getClass())) {
+ if (!context.getBindingClass().isAssignableFrom(other.getClass())) {
return false;
}
try {
final Object value = getBindingData(m);
result += prime * result + ((value == null) ? 0 : value.hashCode());
}
- if (Augmentation.class.isAssignableFrom(context.bindingClass())) {
+ if (Augmentation.class.isAssignableFrom(context.getBindingClass())) {
result += prime * result + (getAugmentations(this).hashCode());
}
cachedHashcode = result;
return aug.get(cls);
}
Preconditions.checkNotNull(cls,"Supplied augmentation must not be null.");
- final Optional<DataContainerCodecContext<?>> augCtx= context.getPossibleStreamChild(cls);
+
+ @SuppressWarnings({"unchecked","rawtypes"})
+ final Optional<DataContainerCodecContext<?,?>> augCtx= context.possibleStreamChild((Class) cls);
if(augCtx.isPresent()) {
final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.get().getDomPathArgument());
if (augData.isPresent()) {
- return augCtx.get().dataFromNormalizedNode(augData.get());
+ return augCtx.get().deserialize(augData.get());
}
}
return null;
}
public String bindingToString() {
- final ToStringHelper helper = MoreObjects.toStringHelper(context.bindingClass()).omitNullValues();
+ final ToStringHelper helper = MoreObjects.toStringHelper(context.getBindingClass()).omitNullValues();
for (final Method m :context.getHashCodeAndEqualsMethods()) {
helper.add(m.getName(), getBindingData(m));
}
- if (Augmentable.class.isAssignableFrom(context.bindingClass())) {
+ if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
helper.add("augmentations", getAugmentationsImpl());
}
return helper.toString();
if (getClass() != obj.getClass()) {
return false;
}
- final LazyDataObject other = (LazyDataObject) obj;
+ final LazyDataObject<?> other = (LazyDataObject<?>) obj;
if (context == null) {
if (other.context != null) {
return false;
*/
package org.opendaylight.yangtools.binding.data.codec.impl;
-import com.google.common.collect.Iterables;
-
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableCollection;
import java.lang.reflect.Method;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
-
+import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeNode;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeCachingCodec;
import org.opendaylight.yangtools.concepts.Codec;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-final class LeafNodeCodecContext extends NodeCodecContext implements NodeContextSupplier {
+final class LeafNodeCodecContext<D extends DataObject> extends NodeCodecContext<D> implements NodeContextSupplier {
private final YangInstanceIdentifier.PathArgument yangIdentifier;
private final Codec<Object, Object> valueCodec;
}
@Override
- protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> normalizedNode) {
+ public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
+ throw new UnsupportedOperationException("Leaf can not be deserialized to DataObject");
+ }
+
+ @Override
+ public NodeCodecContext<?> get() {
+ return this;
+ }
+
+ final Method getGetter() {
+ return getter;
+ }
+
+ @Override
+ public BindingCodecTreeNode<?> bindingPathArgumentChild(PathArgument arg,
+ List<YangInstanceIdentifier.PathArgument> builder) {
+ return null;
+ }
+
+ @Override
+ public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
+ ImmutableCollection<Class<? extends DataObject>> cacheSpecifier) {
+ return null;
+ }
+
+ @Override
+ public Class<D> getBindingClass() {
+ return null;
+ }
+
+ @Override
+ public NormalizedNode<?, ?> serialize(D data) {
+ throw new UnsupportedOperationException("Separete serialization of leaf node is not supported.");
+ }
+
+ @Override
+ public void writeAsNormalizedNode(D data, NormalizedNodeStreamWriter writer) {
+ throw new UnsupportedOperationException("Separete serialization of leaf node is not supported.");
+ }
+
+ @Override
+ public <E extends DataObject> BindingCodecTreeNode<E> streamChild(Class<E> childClass) {
+ return null;
+ }
+
+ @Override
+ public <E extends DataObject> Optional<? extends BindingCodecTreeNode<E>> possibleStreamChild(
+ Class<E> childClass) {
+ return null;
+ }
+
+ @Override
+ public BindingCodecTreeNode<?> yangPathArgumentChild(
+ org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument child) {
+ return null;
+ }
+
+ @Override
+ protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
if (normalizedNode instanceof LeafNode<?>) {
return valueCodec.deserialize(normalizedNode.getValue());
} else if(normalizedNode instanceof LeafSetNode<?>) {
- Iterable<LeafSetEntryNode<Object>> domValues = ((LeafSetNode<Object>) normalizedNode).getValue();
- List<Object> result = new ArrayList<>(Iterables.size(domValues));
+ @SuppressWarnings("unchecked")
+ Collection<LeafSetEntryNode<Object>> domValues = ((LeafSetNode<Object>) normalizedNode).getValue();
+ List<Object> result = new ArrayList<>(domValues.size());
for (LeafSetEntryNode<Object> valueNode : domValues) {
result.add(valueCodec.deserialize(valueNode.getValue()));
}
return null;
}
- @Override
- public NodeCodecContext get() {
- return this;
- }
-
- final Method getGetter() {
- return getter;
- }
-
}
\ No newline at end of file
*/
package org.opendaylight.yangtools.binding.data.codec.impl;
-import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.List;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-class ListNodeCodecContext extends DataObjectCodecContext<ListSchemaNode> {
+class ListNodeCodecContext<D extends DataObject> extends DataObjectCodecContext<D,ListSchemaNode> {
protected ListNodeCodecContext(final DataContainerCodecPrototype<ListSchemaNode> prototype) {
super(prototype);
}
@Override
- protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> node) {
+ public D deserialize(final NormalizedNode<?, ?> node) {
+ if (node instanceof MapEntryNode) {
+ return fromMapEntry((MapEntryNode) node);
+ } else if (node instanceof UnkeyedListEntryNode) {
+ return fromUnkeyedListEntry((UnkeyedListEntryNode) node);
+ } else {
+ throw new IllegalStateException("Unsupported data type " + node.getClass());
+ }
+ }
+
+ @Override
+ protected Object deserializeObject(NormalizedNode<?, ?> node) {
if (node instanceof MapNode) {
return fromMap((MapNode) node);
} else if (node instanceof MapEntryNode) {
}
}
- private List<DataObject> fromMap(final MapNode nodes) {
- List<DataObject> ret = new ArrayList<>(Iterables.size(nodes.getValue()));
- for(MapEntryNode node : nodes.getValue()) {
+ private List<D> fromMap(final MapNode nodes) {
+ List<D> ret = new ArrayList<>(nodes.getValue().size());
+ for (MapEntryNode node : nodes.getValue()) {
ret.add(fromMapEntry(node));
}
return ret;
}
- private DataObject fromMapEntry(final MapEntryNode node) {
+ private D fromMapEntry(final MapEntryNode node) {
return createBindingProxy(node);
}
- private DataObject fromUnkeyedListEntry(final UnkeyedListEntryNode node) {
+ private D fromUnkeyedListEntry(final UnkeyedListEntryNode node) {
return createBindingProxy(node);
}
- private List<DataObject> fromUnkeyedList(final UnkeyedListNode nodes) {
+ private List<D> fromUnkeyedList(final UnkeyedListNode nodes) {
// FIXME: Could be this lazy transformed list?
- List<DataObject> ret = new ArrayList<>(Iterables.size(nodes.getValue()));
+ List<D> ret = new ArrayList<>(nodes.getValue().size());
for (UnkeyedListEntryNode node : nodes.getValue()) {
ret.add(fromUnkeyedListEntry(node));
}
return ret;
}
+
}
\ No newline at end of file
package org.opendaylight.yangtools.binding.data.codec.impl;
import com.google.common.collect.ImmutableMap;
-
import java.util.List;
-
+import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeNode;
import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
* </ul>
*
*/
-abstract class NodeCodecContext {
+abstract class NodeCodecContext<D extends DataObject> implements BindingCodecTreeNode<D> {
/**
* Returns Yang Instance Identifier Path Argument of current node
* @param schema Instantiated schema of binding type.
* @return Map of local name to leaf node context.
*/
- ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(Class<?> type, DataNodeContainer schema);
+ ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(Class<?> type, DataNodeContainer schema);
/**
* Returns Path argument codec for list item
*/
Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(Class<?> type,
ListSchemaNode schema);
+
+ DataObjectSerializer getEventStreamSerializer(Class<?> type);
}
/**
}
}
- /**
- * Return the data object for a normalized node
- *
- * @param normalizedNode Backing normalized node
- * @return Data object
- */
- protected abstract Object dataFromNormalizedNode(NormalizedNode<?, ?> normalizedNode);
+ protected abstract Object deserializeObject(NormalizedNode<?, ?> normalizedNode);
}
/**
* Type capture of an entity producing NodeCodecContexts.
*/
-interface NodeContextSupplier extends Supplier<NodeCodecContext> {
+interface NodeContextSupplier extends Supplier<NodeCodecContext<?>> {
@Override
- @Nonnull NodeCodecContext get();
+ @Nonnull NodeCodecContext<?> get();
}
package org.opendaylight.yangtools.binding.data.codec.impl;
import com.google.common.base.Preconditions;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.Notification;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
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.NotificationDefinition;
-final class NotificationCodecContext extends DataObjectCodecContext<NotificationDefinition> {
+final class NotificationCodecContext<D extends DataObject & Notification> extends DataObjectCodecContext<D,NotificationDefinition> {
public NotificationCodecContext(final Class<?> key, final NotificationDefinition schema, final CodecContextFactory factory) {
super(DataContainerCodecPrototype.from(key, schema, factory));
}
@Override
- protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> data) {
+ public D deserialize(final NormalizedNode<?, ?> data) {
Preconditions.checkState(data instanceof ContainerNode);
return createBindingProxy((NormalizedNodeContainer<?, ?, ?>) data);
}
+ @Override
+ protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+ return deserialize(normalizedNode);
+ }
+
}
\ No newline at end of file
import org.opendaylight.yangtools.yang.binding.BindingMapping;
import org.opendaylight.yangtools.yang.binding.ChildOf;
import org.opendaylight.yangtools.yang.binding.DataContainer;
+import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.DataRoot;
import org.opendaylight.yangtools.yang.binding.Notification;
import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
-final class SchemaRootCodecContext extends DataContainerCodecContext<SchemaContext> {
+final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D,SchemaContext> {
- private final LoadingCache<Class<?>, DataContainerCodecContext<?>> childrenByClass = CacheBuilder.newBuilder()
- .build(new CacheLoader<Class<?>, DataContainerCodecContext<?>>() {
+ private final LoadingCache<Class<?>, DataContainerCodecContext<?,?>> childrenByClass = CacheBuilder.newBuilder()
+ .build(new CacheLoader<Class<?>, DataContainerCodecContext<?,?>>() {
@Override
- public DataContainerCodecContext<?> load(final Class<?> key) {
+ public DataContainerCodecContext<?,?> load(final Class<?> key) {
return createDataTreeChildContext(key);
}
});
- private final LoadingCache<Class<?>, ContainerNodeCodecContext> rpcDataByClass = CacheBuilder.newBuilder().build(
- new CacheLoader<Class<?>, ContainerNodeCodecContext>() {
+ private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder().build(
+ new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
@Override
- public ContainerNodeCodecContext load(final Class<?> key) {
+ public ContainerNodeCodecContext<?> load(final Class<?> key) {
return createRpcDataContext(key);
}
});
- private final LoadingCache<Class<?>, NotificationCodecContext> notificationsByClass = CacheBuilder.newBuilder()
- .build(new CacheLoader<Class<?>, NotificationCodecContext>() {
+ private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
+ .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
@Override
- public NotificationCodecContext load(final Class<?> key) {
+ public NotificationCodecContext<?> load(final Class<?> key) {
return createNotificationDataContext(key);
}
});
- private final LoadingCache<QName, DataContainerCodecContext<?>> childrenByQName = CacheBuilder.newBuilder().build(
- new CacheLoader<QName, DataContainerCodecContext<?>>() {
+ private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName = CacheBuilder.newBuilder().build(
+ new CacheLoader<QName, DataContainerCodecContext<?,?>>() {
+ @SuppressWarnings("unchecked")
@Override
- public DataContainerCodecContext<?> load(final QName qname) {
+ public DataContainerCodecContext<?,?> load(final QName qname) {
final DataSchemaNode childSchema = schema().getDataChildByName(qname);
Preconditions.checkArgument(childSchema != null, "Argument %s is not valid child of %s", qname,
schema());
- if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceNode) {
- final Class<?> childCls = factory().getRuntimeContext().getClassForSchema(childSchema);
- return getStreamChild(childCls);
+ if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
+ @SuppressWarnings("rawtypes")
+ final Class childCls = factory().getRuntimeContext().getClassForSchema(childSchema);
+ return streamChild(childCls);
} else {
throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
}
}
});
- private final LoadingCache<SchemaPath, ContainerNodeCodecContext> rpcDataByPath = CacheBuilder.newBuilder().build(
- new CacheLoader<SchemaPath, ContainerNodeCodecContext>() {
+ private final LoadingCache<SchemaPath, ContainerNodeCodecContext<?>> rpcDataByPath = CacheBuilder.newBuilder().build(
+ new CacheLoader<SchemaPath, ContainerNodeCodecContext<?>>() {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
}
});
- private final LoadingCache<SchemaPath, NotificationCodecContext> notificationsByPath = CacheBuilder.newBuilder()
- .build(new CacheLoader<SchemaPath, NotificationCodecContext>() {
+ private final LoadingCache<SchemaPath, NotificationCodecContext<?>> notificationsByPath = CacheBuilder.newBuilder()
+ .build(new CacheLoader<SchemaPath, NotificationCodecContext<?>>() {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
* CodecContextFactory
* @return
*/
- static SchemaRootCodecContext create(final CodecContextFactory factory) {
+ static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
final DataContainerCodecPrototype<SchemaContext> prototype = DataContainerCodecPrototype.rootPrototype(factory);
- return new SchemaRootCodecContext(prototype);
+ return new SchemaRootCodecContext<>(prototype);
}
+
+ @SuppressWarnings("unchecked")
@Override
- protected DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) {
- return childrenByClass.getUnchecked(childClass);
+ public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(Class<DV> childClass)
+ throws IllegalArgumentException {
+ return (DataContainerCodecContext<DV, ?>) childrenByClass.getUnchecked(childClass);
}
@Override
- protected Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass) {
+ public <E extends DataObject> Optional<DataContainerCodecContext<E,?>> possibleStreamChild(final Class<E> childClass) {
throw new UnsupportedOperationException("Not supported");
}
@Override
- protected NodeCodecContext getYangIdentifierChild(final PathArgument arg) {
+ public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
return childrenByQName.getUnchecked(arg.getNodeType());
}
@Override
- protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> normalizedNode) {
- throw new UnsupportedOperationException("Could not create Binding data representation for root");
+ public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
+ throw new UnsupportedOperationException(
+ "Could not create Binding data representation for root");
}
- ContainerNodeCodecContext getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
+
+ ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
return rpcDataByClass.getUnchecked(rpcInputOrOutput);
}
- NotificationCodecContext getNotification(final Class<? extends Notification> notification) {
+ NotificationCodecContext<?> getNotification(final Class<? extends Notification> notification) {
return notificationsByClass.getUnchecked(notification);
}
- NotificationCodecContext getNotification(final SchemaPath notification) {
+ NotificationCodecContext<?> getNotification(final SchemaPath notification) {
return notificationsByPath.getUnchecked(notification);
}
- ContainerNodeCodecContext getRpc(final SchemaPath notification) {
+ ContainerNodeCodecContext<?> getRpc(final SchemaPath notification) {
return rpcDataByPath.getUnchecked(notification);
}
- private DataContainerCodecContext<?> createDataTreeChildContext(final Class<?> key) {
+ private DataContainerCodecContext<?,?> createDataTreeChildContext(final Class<?> key) {
final Class<Object> parent = ClassLoaderUtils.findFirstGenericArgument(key, ChildOf.class);
Preconditions.checkArgument(DataRoot.class.isAssignableFrom(parent));
final QName qname = BindingReflections.findQName(key);
return DataContainerCodecPrototype.from(key, childSchema, factory()).get();
}
- private ContainerNodeCodecContext createRpcDataContext(final Class<?> key) {
+ private ContainerNodeCodecContext<?> createRpcDataContext(final Class<?> key) {
Preconditions.checkArgument(DataContainer.class.isAssignableFrom(key));
final QName qname = BindingReflections.findQName(key);
final QNameModule module = qname.getModule();
Preconditions.checkArgument(rpc != null, "Supplied class %s is not valid RPC class.", key);
final ContainerSchemaNode schema = SchemaNodeUtils.getRpcDataSchema(rpc, qname);
Preconditions.checkArgument(schema != null, "Schema for %s does not define input / output.", rpc.getQName());
- return (ContainerNodeCodecContext) DataContainerCodecPrototype.from(key, schema, factory()).get();
+ return (ContainerNodeCodecContext<?>) DataContainerCodecPrototype.from(key, schema, factory()).get();
}
- private NotificationCodecContext createNotificationDataContext(final Class<?> notificationType) {
+ private NotificationCodecContext<?> createNotificationDataContext(final Class<?> notificationType) {
Preconditions.checkArgument(Notification.class.isAssignableFrom(notificationType));
Preconditions.checkArgument(notificationType.isInterface(), "Supplied class must be interface.");
final QName qname = BindingReflections.findQName(notificationType);
SchemaPath.create(true, qname));
Preconditions.checkArgument(schema != null, "Supplied %s is not valid notification", notificationType);
- return new NotificationCodecContext(notificationType, schema, factory());
+ return new NotificationCodecContext<>(notificationType, schema, factory());
+ }
+
+ @Override
+ protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+ throw new UnsupportedOperationException("Unable to deserialize root");
}
}
\ No newline at end of file
package org.opendaylight.yangtools.binding.data.codec.impl;
import com.google.common.collect.ImmutableSet;
-
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
-
import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.binding.BindingMapping;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
final class UnionTypeCodec extends ReflectionBasedCodec {
- private Constructor<?> charConstructor;
- private ImmutableSet<UnionValueOptionContext> typeCodecs;
+ private final ImmutableSet<UnionValueOptionContext> typeCodecs;
+ private final Constructor<?> charConstructor;
private UnionTypeCodec(final Class<?> unionCls,final Set<UnionValueOptionContext> codecs) {
super(unionCls);
}
}
- static final Callable<UnionTypeCodec> loader(final Class<?> unionCls, final UnionTypeDefinition unionType) {
+ static Callable<UnionTypeCodec> loader(final Class<?> unionCls, final UnionTypeDefinition unionType) {
return new Callable<UnionTypeCodec>() {
@Override
public UnionTypeCodec call() throws NoSuchMethodException, SecurityException {
};
}
- private static Codec<Object, Object> getCodecForType(Class valueType, TypeDefinition subtype) {
+ private static Codec<Object, Object> getCodecForType(final Class<?> valueType, final TypeDefinition<?> subtype) {
if (subtype.getBaseType() instanceof UnionType) {
try {
return UnionTypeCodec.loader(valueType, (UnionType) subtype.getBaseType()).call();
@Override
public Object serialize(final Object input) {
- if(input != null) {
- for(UnionValueOptionContext valCtx : typeCodecs) {
+ if (input != null) {
+ for (UnionValueOptionContext valCtx : typeCodecs) {
Object domValue = valCtx.serialize(input);
- if(domValue != null) {
+ if (domValue != null) {
return domValue;
}
}
private final Class<?> identifier;
private final String getterName;
- ValueContext(final Class<?> identifier, final LeafNodeCodecContext leaf) {
+ ValueContext(final Class<?> identifier, final LeafNodeCodecContext <?>leaf) {
getterName = BindingCodecContext.GETTER_PREFIX + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
try {
getter = LOOKUP.unreflect(identifier.getMethod(getterName)).asType(OBJECT_METHOD);
public static final SchemaUnawareCodec EMPTY_CODEC = new SchemaUnawareCodec() {
@Override
- public Object serialize(Object arg0) {
+ public Object serialize(final Object arg0) {
// Empty type has null value in NormalizedNode and Composite Node
// representation
return null;
}
@Override
- public Object deserialize(Object arg0) {
+ public Object deserialize(final Object arg0) {
/* Empty type has boolean.TRUE representation in Binding-aware world
* otherwise it is null / false.
* So when codec is triggered, empty leaf is present, that means we
private static final Callable<? extends SchemaUnawareCodec> EMPTY_LOADER = new Callable<SchemaUnawareCodec>() {
@Override
- public SchemaUnawareCodec call() throws Exception {
+ public SchemaUnawareCodec call() {
return EMPTY_CODEC;
}
};
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
import com.google.common.collect.Iterables;
import javassist.ClassPool;
import org.junit.Before;
assertEquals(TopLevelList.class, instanceIdentifier.getTargetType());
assertFalse(instanceIdentifier.isWildcarded());
assertTrue(last instanceof InstanceIdentifier.IdentifiableItem);
- final Identifier key = ((InstanceIdentifier.IdentifiableItem) last).getKey();
+ final Identifier<?> key = ((InstanceIdentifier.IdentifiableItem<?, ?>) last).getKey();
assertEquals(TopLevelListKey.class, key.getClass());
assertEquals(TOP_LEVEL_LIST_KEY_VALUE, ((TopLevelListKey)key).getName());
}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import com.google.common.base.Preconditions;
-
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javassist.ClassPool;
-
-import org.eclipse.xtext.xbase.lib.Extension;
-import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
-import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
-import org.opendaylight.yangtools.util.ClassLoaderUtils;
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-
-/**
- * Abstract base class which defines the baseline for the real {@link TransformerGenerator}.
- * This class exists to expose the basic interface and common interactions with the rest
- * of the package.
- */
-abstract class AbstractTransformerGenerator {
- private static final Map<SchemaPath, InstanceIdentifier<?>> PATH_TO_BINDING_IDENTIFIER = new ConcurrentHashMap<>();
-
- /*
- * The generator has to always use this strategy, otherwise we may end up
- * will VerificationErrors.
- */
- @Extension
- protected static final ClassLoadingStrategy CLASS_LOADING_STRATEGY = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
- @Extension
- protected final TypeResolver typeResolver;
- @Extension
- protected final JavassistUtils javAssist;
-
- /*
- * This is effectively final, but we have an implementation circle, where this
- * class notifies LazyGeneratedCodecRegistry and it calls our methods. The
- * listener is initialized to non-null before it is exposed.
- */
- private GeneratorListener listener;
-
- protected AbstractTransformerGenerator(final TypeResolver typeResolver, final ClassPool pool) {
- this.typeResolver = Preconditions.checkNotNull(typeResolver);
- this.javAssist = JavassistUtils.forClassPool(pool);
- }
-
- protected final GeneratorListener getListener() {
- if (listener == null) {
- synchronized (this) {
- Preconditions.checkState(listener != null, "Implementation not fully initialized");
- }
- }
-
- return listener;
- }
-
- synchronized final void setListener(final GeneratorListener listener) {
- Preconditions.checkState(this.listener == null, "Implementation already initialized");
- this.listener = Preconditions.checkNotNull(listener);
- }
-
- protected final <V> V runOnClassLoader(final ClassLoader cls, final Callable<V> function) throws Exception {
- synchronized (javAssist) {
- javAssist.appendClassLoaderIfMissing(cls);
- return ClassLoaderUtils.withClassLoader(cls, function);
- }
- }
-
- protected final InstanceIdentifier<?> getBindingIdentifierByPath(final SchemaPath path) {
- return PATH_TO_BINDING_IDENTIFIER.get(path);
- }
-
- protected final void putPathToBindingIdentifier(final SchemaPath path, final InstanceIdentifier<?> bindingIdentifier) {
- PATH_TO_BINDING_IDENTIFIER.put(path, bindingIdentifier);
- }
-
- protected final InstanceIdentifier<?> putPathToBindingIdentifier(final SchemaPath path,
- final InstanceIdentifier<?> bindingIdentifier, final Class<?> childClass) {
- @SuppressWarnings({ "unchecked", "rawtypes" })
- InstanceIdentifier<?> newId = bindingIdentifier.builder().child((Class) childClass).build();
- PATH_TO_BINDING_IDENTIFIER.put(path, newId);
- return newId;
- }
-
- protected abstract Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentationTransformerForImpl(Class<?> inputType);
- protected abstract Class<? extends BindingCodec<Object, Object>> caseCodecForImpl(Class<?> inputType, ChoiceCaseNode node);
- protected abstract Class<? extends BindingCodec<Map<QName, Object>, Object>> keyTransformerForIdentifiableImpl(Class<?> parentType);
- protected abstract Class<? extends BindingCodec<Map<QName, Object>, Object>> keyTransformerForIdentifierImpl(Class<?> inputType);
- protected abstract Class<? extends BindingCodec<Map<QName, Object>, Object>> transformerForImpl(Class<?> inputType);
-
- // Called from LazyGeneratedCodecRegistry
- final Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentationTransformerFor(final Class<?> inputType) throws TransformerGeneratorException {
- try {
- return augmentationTransformerForImpl(inputType);
- } catch (Exception e) {
- throw TransformerGeneratorException.wrap(inputType, e);
- }
- }
-
- final Class<? extends BindingCodec<Object, Object>> caseCodecFor(final Class<?> inputType, final ChoiceCaseNode node) throws TransformerGeneratorException {
- try {
- return caseCodecForImpl(inputType, node);
- } catch (Exception e) {
- throw TransformerGeneratorException.wrap(inputType, e);
- }
- }
-
- final Class<? extends BindingCodec<Map<QName, Object>, Object>> keyTransformerForIdentifiable(final Class<?> parentType) throws TransformerGeneratorException {
- try {
- return keyTransformerForIdentifiableImpl(parentType);
- } catch (Exception e) {
- throw TransformerGeneratorException.wrap(parentType, e);
- }
- }
-
- final Class<? extends BindingCodec<Map<QName, Object>, Object>> keyTransformerForIdentifier(final Class<?> inputType) throws TransformerGeneratorException {
- try {
- return keyTransformerForIdentifierImpl(inputType);
- } catch (Exception e) {
- throw TransformerGeneratorException.wrap(inputType, e);
- }
- }
-
- final Class<? extends BindingCodec<Map<QName, Object>, Object>> transformerFor(final Class<?> inputType) throws TransformerGeneratorException {
- try {
- return transformerForImpl(inputType);
- } catch (Exception e) {
- throw TransformerGeneratorException.wrap(inputType, e);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-public interface BindingClassListener {
-
- void onBindingClassCaptured(Class<?> cls);
-
- void onBindingClassProcessed(Class<?> cls);
-}
import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
+
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.BaseTypes;
import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
+import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
import org.opendaylight.yangtools.yang.model.util.UnionType;
import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
private static final Splitter COLON_SPLITTER = Splitter.on(':');
private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
private static final char NEW_LINE = '\n';
+ private static final String QNAME_FQCN = QName.class.getName();
/**
* Constant with the concrete name of identifier.
schemaContext = context;
typeProvider = new TypeProviderImpl(context);
- Module[] modulesArray = new Module[context.getModules().size()];
+ final Module[] modulesArray = new Module[context.getModules().size()];
context.getModules().toArray(modulesArray);
final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
genTypeBuilders = new HashMap<>();
- for (Module contextModule : contextModules) {
+ for (final Module contextModule : contextModules) {
moduleToGenTypes(contextModule, context);
}
- for (Module contextModule : contextModules) {
+ for (final Module contextModule : contextModules) {
allAugmentsToGenTypes(contextModule);
}
final List<Type> filteredGenTypes = new ArrayList<>();
- for (Module m : modules) {
+ for (final Module m : modules) {
final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
filteredGenTypes.addAll(ctx.getGeneratedTypes());
final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL.");
- for (TypeDefinition<?> typedef : typeDefinitions) {
+ for (final TypeDefinition<?> typedef : typeDefinitions) {
if (typedef != null) {
final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
typedef);
genType.addImplementsType(identifiableMarker);
}
- for (DataSchemaNode schemaNode : node.getChildNodes()) {
+ for (final DataSchemaNode schemaNode : node.getChildNodes()) {
if (!schemaNode.isAugmenting()) {
addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
}
private void processUsesAugments(final DataNodeContainer node, final Module module) {
final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
- for (UsesNode usesNode : node.getUses()) {
- for (AugmentationSchema augment : usesNode.getAugmentations()) {
+ for (final UsesNode usesNode : node.getUses()) {
+ for (final AugmentationSchema augment : usesNode.getAugmentations()) {
usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
processUsesAugments(augment, module);
}
final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
final List<AugmentationSchema> augmentations = resolveAugmentations(module);
- for (AugmentationSchema augment : augmentations) {
+ for (final AugmentationSchema augment : augmentations) {
augmentationToGenTypes(basePackageName, augment, module);
}
}
checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
final Set<AugmentationSchema> augmentations = module.getAugmentations();
- List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
+ final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
return sortedAugmentations;
interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
- for (RpcDefinition rpc : rpcDefinitions) {
+ for (final RpcDefinition rpc : rpcDefinitions) {
if (rpc != null) {
final String rpcName = BindingMapping.getClassName(rpc.getQName());
final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
- for (NotificationDefinition notification : notifications) {
+ for (final NotificationDefinition notification : notifications) {
if (notification != null) {
processUsesAugments(notification, module);
final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
- for (IdentitySchemaNode identity : schemaIdentities) {
+ for (final IdentitySchemaNode identity : schemaIdentities) {
identityToGenType(module, basePackageName, identity, context);
}
}
private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
final QName name) {
- StringBuilder sb = new StringBuilder("org.opendaylight.yangtools.yang.common.QName");
+ final StringBuilder sb = new StringBuilder(QNAME_FQCN);
+ sb.append(".cachedReference(");
+ sb.append(QNAME_FQCN);
sb.append(".create(");
sb.append('"');
sb.append(name.getNamespace());
sb.append(name.getFormattedRevision());
sb.append("\",\"");
sb.append(name.getLocalName());
- sb.append("\");");
+ sb.append("\"))");
return toBuilder.addConstant(typeForClass(QName.class), constantName, sb.toString());
}
final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
.sort(groupings);
- for (GroupingDefinition grouping : groupingsSortedByDependencies) {
+ for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
groupingToGenType(basePackageName, grouping, module);
}
}
* builder
* @param typeBuilder
* GeneratedTypeBuilder to which will be enum builder assigned
+ * @param module
+ * Module in which type should be generated
* @return enumeration builder which contains data from
* <code>enumTypeDef</code>
*/
private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
- final GeneratedTypeBuilder typeBuilder) {
+ final GeneratedTypeBuilder typeBuilder, Module module) {
if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
&& (enumTypeDef.getQName().getLocalName() != null)) {
final String enumerationName = BindingMapping.getClassName(enumName);
final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
enumBuilder.setDescription(enumTypeDef.getDescription());
enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
+ ModuleContext ctx = genCtx.get(module);
+ ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
return enumBuilder;
}
return null;
throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
}
- if (!(targetSchemaNode instanceof ChoiceNode)) {
- String packageName = augmentPackageName;
+ if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
+ final String packageName = augmentPackageName;
final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
targetTypeBuilder.getName());
addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
} else {
generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
- (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
+ (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
}
}
processUsesAugments(augSchema, module);
final SchemaPath targetPath = augSchema.getTargetPath();
- SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
+ final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
if (targetSchemaNode == null) {
throw new IllegalArgumentException("augment target not found: " + targetPath);
}
throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
}
- if (!(targetSchemaNode instanceof ChoiceNode)) {
+ if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
String packageName = augmentPackageName;
if (usesNodeParent instanceof SchemaNode) {
packageName = packageNameForGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath(),
augSchema);
} else {
generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
- (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
+ (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
}
}
* @return node from its original location in grouping
*/
private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
- SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
+ final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
.getPathFromRoot());
if (!(targetGrouping instanceof GroupingDefinition)) {
throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
}
- GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
+ final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
SchemaNode result = grouping;
- for (QName node : targetPath.getPathFromRoot()) {
+ for (final QName node : targetPath.getPathFromRoot()) {
// finding by local name is valid, grouping cannot contain nodes
// with same name and different namespace
if (result instanceof DataNodeContainer) {
result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
- } else if (result instanceof ChoiceNode) {
- result = ((ChoiceNode) result).getCaseNodeByName(node.getLocalName());
+ } else if (result instanceof ChoiceSchemaNode) {
+ result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
}
}
if (result == null) {
}
boolean fromUses = ((DataSchemaNode) result).isAddedByUses();
- Iterator<UsesNode> groupingUses = grouping.getUses().iterator();
+ final Iterator<UsesNode> groupingUses = grouping.getUses().iterator();
while (groupingUses.hasNext() && fromUses) {
result = findOriginalTargetFromGrouping(targetPath, groupingUses.next());
if (result != null) {
* @return nodeParameter of UnknownSchemaNode
*/
private String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
- for (UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
+ for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
final QName nodeType = unknownSchemaNode.getNodeType();
if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
&& YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
if (schemaNodes != null && parent != null) {
- for (DataSchemaNode schemaNode : schemaNodes) {
+ for (final DataSchemaNode schemaNode : schemaNodes) {
if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
}
final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
final Iterable<DataSchemaNode> schemaNodes) {
if ((schemaNodes != null) && (typeBuilder != null)) {
- for (DataSchemaNode schemaNode : schemaNodes) {
+ for (final DataSchemaNode schemaNode : schemaNodes) {
if (!schemaNode.isAugmenting()) {
addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
}
final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
if (node != null && typeBuilder != null) {
if (node instanceof LeafSchemaNode) {
- resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node);
+ resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
} else if (node instanceof LeafListSchemaNode) {
- resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node);
+ resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
} else if (node instanceof ContainerSchemaNode) {
containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
} else if (node instanceof ListSchemaNode) {
listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
- } else if (node instanceof ChoiceNode) {
- choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) node);
+ } else if (node instanceof ChoiceSchemaNode) {
+ choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
} else {
// TODO: anyxml not yet supported
LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
* </ul>
*/
private void choiceToGeneratedType(final Module module, final String basePackageName,
- final GeneratedTypeBuilder parent, final ChoiceNode choiceNode) {
+ final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
* </ul>
*/
private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
- final Type refChoiceType, final ChoiceNode choiceNode) {
+ final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
return;
}
- for (ChoiceCaseNode caseNode : caseNodes) {
+ for (final ChoiceCaseNode caseNode : caseNodes) {
if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
* </ul>
*/
private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
- final Type targetType, final ChoiceNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
+ final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
- for (DataSchemaNode caseNode : augmentedNodes) {
+ for (final DataSchemaNode caseNode : augmentedNodes) {
if (caseNode != null) {
final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
* @param leaf
* leaf schema node which is mapped as getter method which is
* added to <code>typeBuilder</code>
+ * @param module
+ * Module in which type was defined
* @return boolean value
* <ul>
* <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
* <li>true - in other cases</li>
* </ul>
*/
- private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf) {
+ private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, Module module) {
Type returnType = null;
if ((leaf != null) && (typeBuilder != null)) {
final String leafName = leaf.getQName().getLocalName();
returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
- typeBuilder);
+ typeBuilder,module);
if (enumBuilder != null) {
returnType = enumBuilder.toInstance(typeBuilder);
private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
final Module module) {
- for (UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
+ for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
final QName nodeType = node.getNodeType();
if ("context-reference".equals(nodeType.getLocalName())) {
final String nodeParam = node.getNodeParameter();
identity = findIdentityByName(module.getIdentities(), iterator.next());
basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
} else if (length == 2) {
- String prefix = iterator.next();
+ final String prefix = iterator.next();
final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
if (dependentModule == null) {
throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
}
private IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
- for (IdentitySchemaNode id : identities) {
+ for (final IdentitySchemaNode id : identities) {
if (id.getQName().getLocalName().equals(name)) {
return id;
}
}
private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
- for (ModuleImport imp : imports) {
+ for (final ModuleImport imp : imports) {
if (imp.getPrefix().equals(prefix)) {
return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
}
if (leafDesc == null) {
leafDesc = "";
}
-
- if (leafName != null) {
- Type returnType = null;
- final TypeDefinition<?> typeDef = leaf.getType();
- if (typeDef instanceof UnionTypeDefinition) {
- // GeneratedType for this type definition should be already
- // created
- QName qname = typeDef.getQName();
- Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
- qname.getRevision());
- final ModuleContext mc = genCtx.get(unionModule);
- returnType = mc.getTypedefs().get(typeDef.getPath());
- } else {
- returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
- }
- return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
+ Type returnType = null;
+ final TypeDefinition<?> typeDef = leaf.getType();
+ if (typeDef instanceof UnionTypeDefinition) {
+ // GeneratedType for this type definition should be already
+ // created
+ final QName qname = typeDef.getQName();
+ final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
+ qname.getRevision());
+ final ModuleContext mc = genCtx.get(unionModule);
+ returnType = mc.getTypedefs().get(typeDef.getPath());
+ } else if (typeDef instanceof EnumTypeDefinition && BaseTypes.ENUMERATION_QNAME.equals(typeDef.getQName())) {
+ // Annonymous enumeration (already generated, since it is inherited via uses).
+ LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
+ QName qname = originalLeaf.getQName();
+ final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
+ qname.getRevision());
+ returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
+ } else {
+ returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
}
+ return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
}
return false;
}
* @param node
* leaf list schema node which is added to
* <code>typeBuilder</code> as getter method
+ * @param module
* @return boolean value
* <ul>
* <li>true - if <code>node</code>, <code>typeBuilder</code>,
* <li>false - other cases</li>
* </ul>
*/
- private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node) {
+ private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, Module module) {
if ((node != null) && (typeBuilder != null)) {
final QName nodeName = node.getQName();
returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
- typeBuilder);
+ typeBuilder,module);
returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
} else if (typeDef instanceof UnionType) {
genTOBuilder.setIsUnion(true);
((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
- // union builder
- final GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),
- genTOBuilder.getName() + "Builder");
- unionBuilder.setIsUnionBuilder(true);
+
+
+ final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
+
+
final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
method.setReturnType(returnType);
method.addParameter(Types.STRING, "defaultValue");
return returnType.toInstance();
}
+ private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
+
+ final String outerCls = Types.getOuterClassName(genTOBuilder);
+ final StringBuilder name;
+ if(outerCls != null) {
+ name = new StringBuilder(outerCls);
+ } else {
+ name = new StringBuilder();
+ }
+ name.append(genTOBuilder.getName());
+ name.append("Builder");
+ final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
+ unionBuilder.setIsUnionBuilder(true);
+ return unionBuilder;
+ }
+
private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
final Module module) {
return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
} else {
method.append("get");
}
- String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
+ final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
method.append(name);
return method.toString();
}
if (schemaNode instanceof LeafSchemaNode) {
final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
final String leafName = leaf.getQName().getLocalName();
- final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf);
+ final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
if (listKeys.contains(leafName)) {
if (type == null) {
resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
}
} else if (!schemaNode.isAddedByUses()) {
if (schemaNode instanceof LeafListSchemaNode) {
- resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode);
+ resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
} else if (schemaNode instanceof ContainerSchemaNode) {
containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
- } else if (schemaNode instanceof ChoiceNode) {
- choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) schemaNode);
+ } else if (schemaNode instanceof ChoiceSchemaNode) {
+ choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
} else if (schemaNode instanceof ListSchemaNode) {
listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
}
checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
if (genTOBuilder != null) {
- GeneratedTransferObject genTO = genTOBuilder.toInstance();
+ final GeneratedTransferObject genTO = genTOBuilder.toInstance();
constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
}
private List<String> listKeys(final ListSchemaNode list) {
final List<String> listKeys = new ArrayList<>();
- List<QName> keyDefinition = list.getKeyDefinition();
+ final List<QName> keyDefinition = list.getKeyDefinition();
if (keyDefinition != null) {
- for (QName keyDef : keyDefinition) {
+ for (final QName keyDef : keyDefinition) {
listKeys.add(keyDef.getLocalName());
}
}
throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
}
resultTOBuilder = types.remove(0);
- for (GeneratedTOBuilder genTOBuilder : types) {
+ for (final GeneratedTOBuilder genTOBuilder : types) {
resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
}
packageName, typeDef, classNameFromLeaf, parentModule.getName()));
}
if (genTOBuilders != null && !genTOBuilders.isEmpty()) {
- for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
+ for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
typeBuilder.addEnclosingTransferObject(genTOBuilder);
}
return genTOBuilders.get(0);
*/
private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
final GeneratedTypeBuilder builder) {
- for (UsesNode usesNode : dataNodeContainer.getUses()) {
+ for (final UsesNode usesNode : dataNodeContainer.getUses()) {
if (usesNode.getGroupingPath() != null) {
final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
if (genType == null) {
final Module module = findParentModule(schemaContext, schemaNode);
final StringBuilder linkToBuilderClass = new StringBuilder();
final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
- String className = namespace[namespace.length - 1];
+ final String className = namespace[namespace.length - 1];
if (hasBuilderClass(schemaNode)) {
linkToBuilderClass.append(className);
}
private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
- for (ModuleContext ctx : genCtx.values()) {
- GeneratedTypeBuilder result = ctx.getChildNode(path);
+ for (final ModuleContext ctx : genCtx.values()) {
+ final GeneratedTypeBuilder result = ctx.getChildNode(path);
if (result != null) {
return result;
}
}
private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
- for (ModuleContext ctx : genCtx.values()) {
- GeneratedTypeBuilder result = ctx.getGrouping(path);
+ for (final ModuleContext ctx : genCtx.values()) {
+ final GeneratedTypeBuilder result = ctx.getGrouping(path);
if (result != null) {
return result;
}
}
private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
- for (ModuleContext ctx : genCtx.values()) {
- GeneratedTypeBuilder result = ctx.getCase(path);
+ for (final ModuleContext ctx : genCtx.values()) {
+ final GeneratedTypeBuilder result = ctx.getCase(path);
if (result != null) {
return result;
}
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
final QName targetQName) {
for (DataSchemaNode child : ctx.getChildNodes()) {
- if (child instanceof ChoiceNode) {
- DataNodeContainer potential = findInCases(((ChoiceNode) child), targetQName);
+ if (child instanceof ChoiceSchemaNode) {
+ DataNodeContainer potential = findInCases(((ChoiceSchemaNode) child), targetQName);
if (potential != null) {
return Optional.of(potential);
}
return Optional.absent();
}
- private static DataNodeContainer findInCases(final ChoiceNode choiceNode, final QName targetQName) {
+ private static DataNodeContainer findInCases(final ChoiceSchemaNode choiceNode, final QName targetQName) {
for (ChoiceCaseNode caze : choiceNode.getCases()) {
Optional<DataNodeContainer> potential = findDataNodeContainer(caze, targetQName);
if (potential.isPresent()) {
return augmentations;
}
- public static Optional<ChoiceNode> findInstantiatedChoice(final DataNodeContainer parent, final Class<?> choiceClass) {
+ public static Optional<ChoiceSchemaNode> findInstantiatedChoice(final DataNodeContainer parent, final Class<?> choiceClass) {
return findInstantiatedChoice(parent, BindingReflections.findQName(choiceClass));
}
- public static Optional<ChoiceNode> findInstantiatedChoice(final DataNodeContainer ctxNode, final QName choiceName) {
+ public static Optional<ChoiceSchemaNode> findInstantiatedChoice(final DataNodeContainer ctxNode, final QName choiceName) {
DataSchemaNode potential = ctxNode.getDataChildByName(choiceName);
if (potential == null) {
potential = ctxNode.getDataChildByName(choiceName.getLocalName());
}
- if (potential instanceof ChoiceNode) {
- return Optional.of((ChoiceNode) potential);
+ if (potential instanceof ChoiceSchemaNode) {
+ return Optional.of((ChoiceSchemaNode) potential);
}
return Optional.absent();
}
- public static Optional<ChoiceCaseNode> findInstantiatedCase(final ChoiceNode instantiatedChoice, final ChoiceCaseNode originalDefinition) {
+ public static Optional<ChoiceCaseNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice, final ChoiceCaseNode originalDefinition) {
ChoiceCaseNode potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName());
if(originalDefinition.equals(potential)) {
return Optional.of(potential);
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import java.lang.reflect.Field;
-import java.util.Map;
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class CodecMapping {
-
- private static final Logger LOG = LoggerFactory.getLogger(CodecMapping.class);
-
- public static final String INSTANCE_IDENTIFIER_CODEC = "INSTANCE_IDENTIFIER_CODEC";
- public static final String IDENTITYREF_CODEC = "IDENTITYREF_CODEC";
-
- public static final String CLASS_TO_CASE_MAP = "CLASS_TO_CASE";
- public static final String COMPOSITE_TO_CASE = "COMPOSITE_TO_CASE";
- public static final String AUGMENTATION_CODEC = "AUGMENTATION_CODEC";
- public static final String DISPATCH_CODEC = "DISPATCH_CODEC";
-
- private CodecMapping() {
- throw new UnsupportedOperationException("Utility class should not be instantiated");
- }
-
- public static void setIdentifierCodec(Class<?> obj,InstanceIdentifierCodec codec) {
- Field instanceIdField;
- try {
- instanceIdField = obj.getField(INSTANCE_IDENTIFIER_CODEC);
- if (instanceIdField != null) {
- instanceIdField.set(null, codec);
- }
- } catch (NoSuchFieldException e) {
- LOG.trace("Instance identifier codec is not needed for {}",obj.getName(),e);
- } catch (SecurityException | IllegalAccessException e) {
- LOG.error("Instance identifier could not be set for {}",obj.getName(),e);
- }
- }
-
- public static void setIdentityRefCodec(Class<?> obj,IdentityCodec<?> codec) {
- Field instanceIdField;
- try {
- instanceIdField = obj.getField(IDENTITYREF_CODEC);
- if (instanceIdField != null) {
- instanceIdField.set(null, codec);
- }
- } catch (NoSuchFieldException e) {
- LOG.trace("Instance identifier codec is not needed for {}",obj.getName(),e);
- } catch (SecurityException | IllegalAccessException e) {
- LOG.error("Instance identifier could not be set for {}",obj.getName(),e);
- }
- }
-
- public static void setClassToCaseMap(Class<? extends BindingCodec<?,?>> codec,
- Map<Class<?>,BindingCodec<?,?>> classToCaseRawCodec) {
- Field instanceIdField;
- try {
- instanceIdField = codec.getField(CLASS_TO_CASE_MAP);
- instanceIdField.set(null, classToCaseRawCodec);
- } catch (NoSuchFieldException e) {
- LOG.debug("BUG: Class to case mappping is not needed for {}",codec.getName(),e);
- } catch (SecurityException | IllegalAccessException e) {
- LOG.error("Class to case mappping could not be set for {}",codec.getName(),e);
- }
- }
-
- public static void setCompositeNodeToCaseMap(Class<? extends BindingCodec<?,?>> codec,
- Map<CompositeNode,BindingCodec<?,?>> compositeToCase) {
- Field instanceIdField;
- try {
- instanceIdField = codec.getField(COMPOSITE_TO_CASE);
- instanceIdField.set(null, compositeToCase);
- } catch (NoSuchFieldException e) {
- LOG.debug("BUG: Class to case mappping is not needed for {}",codec.getName(),e);
- } catch (SecurityException | IllegalAccessException e) {
- LOG.error("Composite node to case mappping could not be set for {}",codec.getName(),e);
- }
- }
-
- public static void setDispatchCodec(Class<? extends BindingCodec<?,?>> codec,
- BindingCodec<?, ?> dispatchCodec) {
- Field instanceIdField;
- try {
- instanceIdField = codec.getField(DISPATCH_CODEC);
- instanceIdField.set(null, dispatchCodec);
- } catch (NoSuchFieldException e) {
- LOG.debug("BUG: dispatch codec is not needed for {}",codec.getName(),e);
- } catch (SecurityException | IllegalAccessException e) {
- LOG.error("Dispatch codec could not be set for {}",codec.getName(),e);
- }
- }
-
- public static void setAugmentationCodec(Class<? extends BindingCodec<?,?>> dataCodec,
- BindingCodec<?,?> augmentableCodec) {
- Field instanceIdField;
- try {
- instanceIdField = dataCodec.getField(AUGMENTATION_CODEC);
- instanceIdField.set(null, augmentableCodec);
- } catch (NoSuchFieldException e) {
- LOG.debug("BUG: Augmentation codec is not needed for {}",dataCodec.getName(),e);
- } catch (SecurityException | IllegalAccessException e) {
- LOG.error("Augmentation codec could not be set for {}",dataCodec.getName(),e);
- }
- }
-
-
- public static BindingCodec<?,?> getAugmentationCodec(Class<? extends BindingCodec<?,?>> dataCodec) {
- Field instanceIdField;
- try {
- instanceIdField = dataCodec.getField(AUGMENTATION_CODEC);
- return (BindingCodec<?,?>) instanceIdField.get(null);
- } catch (NoSuchFieldException e) {
- LOG.debug("BUG: Augmentation codec is not needed for {}",dataCodec.getName(),e);
- } catch (SecurityException | IllegalAccessException e) {
- LOG.error("Augmentation codec could not be set for {}",dataCodec.getName(),e);
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
-
-public interface GeneratorListener {
- void onClassProcessed(Class<?> cl);
-
- void onCodecCreated(Class<?> codec);
- void onValueCodecCreated(Class<?> valueClass, Class<?> valueCodec);
- void onCaseCodecCreated(Class<?> choiceClass, Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec);
- void onDataContainerCodecCreated(Class<?> dataClass, Class<? extends BindingCodec<?, ?>> dataCodec);
-
- void onChoiceCodecCreated(Class<?> choiceClass,
- Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, ChoiceNode schema);
-}
+++ /dev/null
-/**
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import com.google.common.collect.ImmutableList;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.WeakHashMap;
-import java.util.concurrent.ConcurrentHashMap;
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-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.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
-import org.opendaylight.yangtools.yang.data.impl.codec.IdentifierCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec {
- private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
-
- private final CodecRegistry codecRegistry;
-
- private final Map<Class<?>,Set<List<QName>>> augmentationAdapted = new WeakHashMap<>();
-
- private final Map<Class<?>, Map<List<QName>, Class<?>>> classToPreviousAugment = Collections
- .synchronizedMap(new WeakHashMap<Class<?>, Map<List<QName>, Class<?>>>());
-
- public InstanceIdentifierCodecImpl(final CodecRegistry registry) {
- this.codecRegistry = registry;
- }
-
- @Override
- public InstanceIdentifier<? extends Object> deserialize(
- final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier input) {
- Class<?> baType = null;
- Iterable<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument> biArgs = input.getPathArguments();
- List<QName> scannedPath = new ArrayList<>();
- List<InstanceIdentifier.PathArgument> baArgs = new ArrayList<InstanceIdentifier.PathArgument>();
- for (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument biArg : biArgs) {
-
- scannedPath.add(biArg.getNodeType());
- org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument baArg = deserializePathArgument(
- biArg, scannedPath);
- if (baArg != null) {
- baType = baArg.getType();
- }
- Map<List<QName>, Class<?>> injectAugment = classToPreviousAugment.get(baType);
- if (injectAugment != null) {
- @SuppressWarnings("unchecked")
- Class<? extends DataObject> augment = (Class<? extends DataObject>) injectAugment.get(scannedPath);
- if (augment != null) {
- baArgs.add(new Item(augment));
- }
- }
- baArgs.add(baArg);
- }
- InstanceIdentifier<?> ret = InstanceIdentifier.create(baArgs);
- LOG.debug("DOM Instance Identifier {} deserialized to {}", input, ret);
- return ret;
- }
-
- @Override
- public InstanceIdentifier<? extends Object> deserialize(
- final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier input,
- final InstanceIdentifier<?> bindingIdentifier) {
- return deserialize(input);
- }
-
- private InstanceIdentifier.PathArgument deserializeNodeIdentifier(
- final NodeIdentifier argument, final List<QName> processedPath) {
- @SuppressWarnings("rawtypes")
- final Class cls = codecRegistry.getClassForPath(processedPath);
- @SuppressWarnings("unchecked")
- Item<DataObject> item = new Item<>(cls);
- return item;
- }
-
- private InstanceIdentifier.PathArgument deserializeNodeIdentifierWithPrecicates(
- final NodeIdentifierWithPredicates argument, final List<QName> processedPath) {
- @SuppressWarnings("rawtypes")
- final Class type = codecRegistry.getClassForPath(processedPath);
- @SuppressWarnings({ "unchecked", "rawtypes" })
- final IdentifierCodec codec = codecRegistry
- .<Identifiable<? extends Object>> getIdentifierCodecForIdentifiable(type);
- CompositeNode _compositeNode = this.toCompositeNode(argument);
- @SuppressWarnings("unchecked")
- ValueWithQName<CompositeNode> deserialize = codec.deserialize(_compositeNode);
- Object value = null;
- if (deserialize != null) {
- value = deserialize.getValue();
- }
- return CodecTypeUtils.newIdentifiableItem(type, value);
- }
-
- public CompositeNode toCompositeNode(final NodeIdentifierWithPredicates predicates) {
- Set<Map.Entry<QName, Object>> keyValues = predicates.getKeyValues().entrySet();
- List<Node<?>> values = new ArrayList<>(keyValues.size());
- for (Map.Entry<QName, Object> keyValue : keyValues) {
- values.add(new SimpleNodeTOImpl<Object>(keyValue.getKey(), null, keyValue.getValue()));
- }
- return new CompositeNodeTOImpl(predicates.getNodeType(), null, values);
- }
-
- @Override
- public org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier serialize(final InstanceIdentifier<?> input) {
- Class<?> previousAugmentation = null;
- Iterable<InstanceIdentifier.PathArgument> pathArgs = input.getPathArguments();
- QName previousQName = null;
- List<PathArgument> components = new ArrayList<>();
- List<QName> qnamePath = new ArrayList<>();
- for (InstanceIdentifier.PathArgument baArg : pathArgs) {
- if (!Augmentation.class.isAssignableFrom(baArg.getType())) {
- PathArgument biArg = serializePathArgumentAndUpdateMapping(qnamePath, baArg, previousQName,previousAugmentation);
- components.add(biArg);
- qnamePath.add(biArg.getNodeType());
- previousQName = biArg.getNodeType();
- previousAugmentation = null;
- } else {
- previousQName = codecRegistry.getQNameForAugmentation(baArg.getType());
- previousAugmentation = baArg.getType();
- ensureAugmentation(qnamePath,previousQName,baArg.getType());
- }
- }
- org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier ret =
- org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.create(components);
- LOG.debug("Binding Instance Identifier {} serialized to DOM InstanceIdentifier {}", input, ret);
- return ret;
- }
-
- private synchronized void ensureAugmentation(final List<QName> augPath, final QName augQName, final Class<? extends DataObject> type) {
- Set<List<QName>> augPotential = augmentationAdapted.get(type);
- if(augPotential == null) {
- augPotential = new HashSet<>();
- augmentationAdapted.put(type, augPotential);
- }
- ImmutableList<QName> augTargetPath = ImmutableList.copyOf(augPath);
- if(augPotential.contains(augPath)) {
- return;
- }
-
- for(Class<? extends DataObject> child : BindingReflections.getChildrenClasses(type)) {
- Item<? extends DataObject> baArg = new Item<>(child);
- PathArgument biArg = serializePathArgumentAndUpdateMapping(augPath, baArg, augQName,type);
- }
- augPotential.add(augTargetPath);
- }
-
-
- public Class<? extends Object> updateAugmentationInjection(final Class<? extends DataObject> class1,
- final List<QName> list, final Class<?> augmentation) {
- if (classToPreviousAugment.get(class1) == null) {
- classToPreviousAugment.put(class1, new ConcurrentHashMap<List<QName>, Class<?>>());
- }
- return classToPreviousAugment.get(class1).put(list, augmentation);
- }
-
- private PathArgument serializeItem(final Item<?> argument, final QName previousQname) {
- Class<?> type = argument.getType();
- QName qname = BindingReflections.findQName(type);
- if (previousQname == null || (BindingReflections.isAugmentationChild(argument.getType()))) {
- return new NodeIdentifier(qname);
- }
- return new NodeIdentifier(QName.create(previousQname, qname.getLocalName()));
- }
-
- private PathArgument serializeIdentifiableItem(final IdentifiableItem<?,?> argument, final QName previousQname) {
- @SuppressWarnings("rawtypes")
- Class type = argument.getType();
- @SuppressWarnings("unchecked")
- IdentifierCodec<? extends Object> keyCodec = codecRegistry.getIdentifierCodecForIdentifiable(type);
- QName qname = BindingReflections.findQName(type);
- if (previousQname != null && !(BindingReflections.isAugmentationChild(argument.getType()))) {
- qname = QName.create(previousQname, qname.getLocalName());
- }
- @SuppressWarnings({ "rawtypes", "unchecked" })
- ValueWithQName combinedInput = new ValueWithQName(previousQname, argument.getKey());
- @SuppressWarnings("unchecked")
- CompositeNode compositeOutput = keyCodec.serialize(combinedInput);
-
- final Map<QName, Object> predicates = new LinkedHashMap<>();
- for (Node<?> outputValue : compositeOutput.getValue()) {
- predicates.put(outputValue.getNodeType(), outputValue.getValue());
- }
- if (previousQname == null) {
- return new NodeIdentifierWithPredicates(qname, predicates);
- }
- return new NodeIdentifierWithPredicates(qname, predicates);
- }
-
- private org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument deserializePathArgument(
- final PathArgument argument, final List<QName> processedPath) {
- if (argument instanceof NodeIdentifier) {
- return deserializeNodeIdentifier((NodeIdentifier) argument, processedPath);
- } else if (argument instanceof NodeIdentifierWithPredicates) {
- return deserializeNodeIdentifierWithPrecicates((NodeIdentifierWithPredicates) argument, processedPath);
- } else {
- throw new IllegalArgumentException("Unhandled parameter types: "
- + Arrays.<Object> asList(argument, processedPath).toString());
- }
- }
-
- private PathArgument serializePathArgumentAndUpdateMapping(final List<QName> parentPath, final InstanceIdentifier.PathArgument baArg, final QName previousQName, final Class<?> previousAugmentation) {
- org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument biArg = serializePathArgument(baArg, previousQName);
- List<QName> qnamePath = new ArrayList<>(parentPath);
- qnamePath.add(biArg.getNodeType());
- ImmutableList<QName> currentPath = ImmutableList.copyOf(qnamePath);
- codecRegistry.putPathToClass(currentPath, baArg.getType());
- if (previousAugmentation != null) {
- updateAugmentationInjection(baArg.getType(), currentPath, previousAugmentation);
- }
- return biArg;
- }
-
- private PathArgument serializePathArgument(
- final InstanceIdentifier.PathArgument argument,
- final QName previousQname) {
- if (argument instanceof IdentifiableItem) {
- return serializeIdentifiableItem((IdentifiableItem<?,?>) argument, previousQname);
- } else if (argument instanceof Item) {
- return serializeItem((Item<?>) argument, previousQname);
- } else {
- throw new IllegalArgumentException("Unhandled parameter types: "
- + Arrays.<Object> asList(argument, previousQname).toString());
- }
- }
-
-
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import com.google.common.base.Preconditions;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
-
-/**
- * @deprecated Use {@link NormalizedNode} and their stream writer codec suite.
- */
-@Deprecated
-public class IntermediateMapping {
- private IntermediateMapping() {
- throw new UnsupportedOperationException("Utility class should not be instantiated");
- }
-
- public static Node<? extends Object> toNode(final Map<? extends Object, ? extends Object> map) {
- if ((map instanceof Node<?>)) {
- return ((Node<?>) map);
- }
- @SuppressWarnings("unchecked")
- final Map<QName, Object> nodeMap = ((Map<QName, Object>) map);
- Preconditions.checkArgument(map.size() == 1);
- final Entry<QName, Object> elem = nodeMap.entrySet().iterator().next();
- final QName qname = elem.getKey();
- final Object value = elem.getValue();
- return toNodeImpl(qname, value);
- }
-
- protected static Node<? extends Object> _toNodeImpl(final QName name, final List<? extends Object> objects) {
- List<Node<? extends Object>> values = new ArrayList<>(objects.size());
- for (Object obj : objects) {
- if ((obj instanceof Node<?>)) {
- values.add(((Node<?>) obj));
- } else {
- if ((obj instanceof Map<?, ?>)) {
- Node<? extends Object> _node = IntermediateMapping.toNode(((Map<?, ?>) obj));
- values.add(_node);
- }
- }
- }
- return new CompositeNodeTOImpl(name, null, values);
- }
-
- protected static Node<? extends Object> _toNodeImpl(final QName name, final Map<QName, Object> object) {
- throw new UnsupportedOperationException("Unsupported node hierarchy.");
- }
-
- protected static Node<? extends Object> _toNodeImpl(final QName name, final Object object) {
- return new SimpleNodeTOImpl<Object>(name, null, object);
- }
-
- @SuppressWarnings("unchecked")
- public static Node<? extends Object> toNodeImpl(final QName name, final Object objects) {
- if (objects instanceof List) {
- return _toNodeImpl(name, (List<?>) objects);
- } else if (objects instanceof Map) {
- return _toNodeImpl(name, (Map<QName, Object>) objects);
- } else if (objects != null) {
- return _toNodeImpl(name, objects);
- } else {
- throw new IllegalArgumentException("Unhandled parameter types: "
- + Arrays.<Object> asList(name, objects).toString());
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.BiMap;
-import com.google.common.collect.HashBiMap;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Multimap;
-import com.google.common.collect.Multimaps;
-import java.util.AbstractMap.SimpleEntry;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.WeakHashMap;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
-import org.opendaylight.yangtools.binding.generator.util.Types;
-import org.opendaylight.yangtools.concepts.Delegator;
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
-import org.opendaylight.yangtools.sal.binding.generator.util.CodeGenerationException;
-import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
-import org.opendaylight.yangtools.sal.binding.model.api.Type;
-import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
-import org.opendaylight.yangtools.util.ClassLoaderUtils;
-import org.opendaylight.yangtools.yang.binding.Augmentable;
-import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.binding.BindingMapping;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.Identifier;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.codec.AugmentationCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCaseCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
-import org.opendaylight.yangtools.yang.data.impl.codec.DataContainerCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.DomCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.IdentifierCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class LazyGeneratedCodecRegistry implements CodecRegistry, SchemaContextListener, GeneratorListener {
-
- private static final Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
-
- // Concrete class to codecs
- private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = Collections
- .synchronizedMap(new WeakHashMap<Class<?>, DataContainerCodec<?>>());
- private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = Collections
- .synchronizedMap(new WeakHashMap<Class<?>, IdentifierCodec<?>>());
- private static final Map<Class<?>, PublicChoiceCodecImpl<?>> choiceCodecs = Collections
- .synchronizedMap(new WeakHashMap<Class<?>, PublicChoiceCodecImpl<?>>());
- private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = Collections
- .synchronizedMap(new WeakHashMap<Class<?>, ChoiceCaseCodecImpl<?>>());
- private static final Map<Class<?>, AugmentableDispatchCodec> augmentableCodecs = Collections
- .synchronizedMap(new WeakHashMap<Class<?>, AugmentableDispatchCodec>());
- private static final Map<Class<?>, AugmentationCodecWrapper<?>> augmentationCodecs = Collections
- .synchronizedMap(new WeakHashMap<Class<?>, AugmentationCodecWrapper<?>>());
-
- private static final Map<Class<?>, LocationAwareDispatchCodec<?>> dispatchCodecs = Collections
- .synchronizedMap(new WeakHashMap<Class<?>, LocationAwareDispatchCodec<?>>());
-
- private static final Map<Class<?>, QName> identityQNames = Collections
- .synchronizedMap(new WeakHashMap<Class<?>, QName>());
- private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
-
- private static final ConcurrentMap<Type, ChoiceCaseNode> caseTypeToCaseSchema = new ConcurrentHashMap<>();
-
- private static final Map<SchemaPath, Type> pathToType = new ConcurrentHashMap<>();
- private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
- private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
- private static final BiMap<Type, AugmentationSchema> typeToAugment = HashBiMap
- .create(new ConcurrentHashMap<Type, AugmentationSchema>());
-
- private static final Multimap<Type, Type> augmentableToAugmentations = Multimaps.synchronizedMultimap(HashMultimap
- .<Type, Type> create());
- private static final Multimap<Type, Type> choiceToCases = Multimaps.synchronizedMultimap(HashMultimap
- .<Type, Type> create());
-
- private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
- private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
- private final ClassLoadingStrategy classLoadingStrategy;
- private final AbstractTransformerGenerator generator;
- private final SchemaLock lock;
-
- // FIXME: how is this protected?
- private SchemaContext currentSchema;
-
- LazyGeneratedCodecRegistry(final SchemaLock lock, final AbstractTransformerGenerator generator,
- final ClassLoadingStrategy classLoadingStrategy) {
- this.lock = Preconditions.checkNotNull(lock);
- this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy);
- this.generator = Preconditions.checkNotNull(generator);
- }
-
- public SchemaLock getLock() {
- return lock;
- }
-
- @Override
- public InstanceIdentifierCodec getInstanceIdentifierCodec() {
- return instanceIdentifierCodec;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T extends Augmentation<?>> AugmentationCodecWrapper<T> getCodecForAugmentation(final Class<T> augClass) {
- AugmentationCodecWrapper<T> codec = null;
- @SuppressWarnings("rawtypes")
- AugmentationCodecWrapper potentialCodec = augmentationCodecs.get(augClass);
- if (potentialCodec != null) {
- codec = potentialCodec;
- } else {
- lock.waitForSchema(augClass);
- Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
- .augmentationTransformerFor(augClass);
-
- BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(augmentRawCodec);
- codec = new AugmentationCodecWrapper<T>(rawCodec, augClass);
- augmentationCodecs.put(augClass, codec);
- }
-
- final Class<? extends Augmentable<?>> objectSupertype;
- try {
- objectSupertype = BindingReflections.findAugmentationTarget(augClass);
- } catch (Exception e) {
- LOG.warn("Failed to find target for augmentation {}, ignoring it", augClass, e);
- return codec;
- }
-
- if (objectSupertype == null) {
- LOG.warn("Augmentation target for {} not found, ignoring it", augClass);
- return codec;
- }
-
- getAugmentableCodec(objectSupertype).addImplementation(codec);
- return codec;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public QName getQNameForAugmentation(final Class<?> cls) {
- Preconditions.checkArgument(Augmentation.class.isAssignableFrom(cls));
- return getCodecForAugmentation((Class<? extends Augmentation<?>>) cls).getAugmentationQName();
- }
-
- @Override
- public Class<?> getClassForPath(final List<QName> names) {
- DataSchemaNode node = getSchemaNode(names);
- Preconditions.checkArgument(node != null, "Path %s points to invalid schema location", names);
- SchemaNode originalDefinition = SchemaNodeUtils.getRootOriginalIfPossible(node);
- if (originalDefinition instanceof DataSchemaNode) {
- node = (DataSchemaNode) originalDefinition;
- }
- final SchemaPath path = node.getPath();
- final Type t = pathToType.get(path);
-
- final Type type;
- if (t != null) {
- type = new ReferencedTypeImpl(t.getPackageName(), t.getName());
- } else {
- type = pathToInstantiatedType.get(names);
- Preconditions.checkState(type != null, "Failed to lookup instantiated type for path %s", path);
- }
-
- try {
- return classLoadingStrategy.loadClass(type);
- } catch (ClassNotFoundException e) {
- throw new IllegalStateException(String.format("Could not find loaded class for path: %s and type: %s",
- path, type.getFullyQualifiedName()));
- }
- }
-
- @Override
- public void putPathToClass(final List<QName> names, final Class<?> cls) {
- final Type reference = Types.typeForClass(cls);
- pathToInstantiatedType.put(names, reference);
- LOG.trace("Path {} attached to class {} reference {}", names, cls, reference);
- bindingClassEncountered(cls);
- }
-
- @Override
- public IdentifierCodec<?> getKeyCodecForPath(final List<QName> names) {
- @SuppressWarnings("unchecked")
- Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
- return getIdentifierCodecForIdentifiable(cls);
- }
-
- @Override
- public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(final Class<T> type) {
- @SuppressWarnings("unchecked")
- DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
- if (ret != null) {
- return ret;
- }
- Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
- BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
- DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
- containerCodecs.put(type, newWrapper);
- return newWrapper;
- }
-
- @Override
- @SuppressWarnings("rawtypes")
- public void bindingClassEncountered(final Class cls) {
- if (Augmentation.class.isAssignableFrom(cls)) {
- // Intentionally NOOP
- } else if (DataObject.class.isAssignableFrom(cls)) {
- getCodecForDataObject((Class<? extends DataObject>) cls);
- }
- }
-
- @Override
- public void onClassProcessed(final Class<?> cls) {
-
- }
-
- private DataSchemaNode getSchemaNode(final List<QName> path) {
- QName firstNode = path.get(0);
- DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
- firstNode.getRevision());
- Preconditions.checkArgument(previous != null, "Failed to find module %s for path %s", firstNode, path);
-
- Iterator<QName> iterator = path.iterator();
- while (iterator.hasNext()) {
- QName arg = iterator.next();
- DataSchemaNode currentNode = previous.getDataChildByName(arg);
- if (currentNode == null) {
- currentNode = searchInChoices(previous, arg);
- }
- if (currentNode instanceof DataNodeContainer) {
- previous = (DataNodeContainer) currentNode;
- } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
- Preconditions.checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
- return currentNode;
- }
- }
- return (DataSchemaNode) previous;
- }
-
- private DataSchemaNode searchInChoices(final DataNodeContainer node, final QName arg) {
- for (DataSchemaNode child : node.getChildNodes()) {
- if (child instanceof ChoiceNode) {
- ChoiceNode choiceNode = (ChoiceNode) child;
- DataSchemaNode potential = searchInCases(choiceNode, arg);
- if (potential != null) {
- return potential;
- }
- }
- }
- return null;
- }
-
- private DataSchemaNode searchInCases(final ChoiceNode choiceNode, final QName arg) {
- Set<ChoiceCaseNode> cases = choiceNode.getCases();
- for (ChoiceCaseNode caseNode : cases) {
- DataSchemaNode node = caseNode.getDataChildByName(arg);
- if (node != null) {
- return node;
- }
- }
- return null;
- }
-
- private static <T> T newInstanceOf(final Class<?> cls) {
- try {
- @SuppressWarnings("unchecked")
- T ret = (T) cls.newInstance();
- return ret;
- } catch (InstantiationException e) {
- LOG.error("Failed to instantiate codec {}", cls.getSimpleName(), e);
- throw new IllegalStateException(String.format("Failed to instantiate codec %s", cls), e);
- } catch (IllegalAccessException e) {
- LOG.debug(
- "Run-time consistency issue: constructor for {} is not available. This indicates either a code generation bug or a misconfiguration of JVM.",
- cls.getSimpleName(), e);
- throw new IllegalStateException(String.format("Cannot access contructor of %s", cls), e);
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class identifiable) {
-
- Class identifier = ClassLoaderUtils.findFirstGenericArgument(identifiable,
- org.opendaylight.yangtools.yang.binding.Identifiable.class);
- IdentifierCodec<?> obj = identifierCodecs.get(identifier);
- if (obj != null) {
- return obj;
- }
- return createIdentifierCodec(identifier, identifiable);
- }
-
- @Override
- public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> identifier) {
- @SuppressWarnings("unchecked")
- IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(identifier);
- if (obj != null) {
- return obj;
- }
- Class<? extends Identifiable<T>> identifiable = ClassLoaderUtils.findFirstGenericArgument(identifier,
- Identifier.class);
- return createIdentifierCodec(identifier, identifiable);
- }
-
- private <T extends Identifier<?>> IdentifierCodec<T> createIdentifierCodec(final Class<T> identifier,
- final Class<? extends Identifiable<T>> identifiable) {
- Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
- .keyTransformerForIdentifiable(identifiable);
- BindingCodec<Map<QName, Object>, Object> newInstance;
- newInstance = newInstanceOf(newCodec);
- IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
- identifierCodecs.put(identifier, newWrapper);
- return newWrapper;
- }
-
- @Override
- public IdentityCodec<?> getIdentityCodec() {
- return identityRefCodec;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(final Class<T> codec) {
- bindingClassEncountered(codec);
- return identityRefCodec;
- }
-
- @Override
- public void onCodecCreated(final Class<?> cls) {
- CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
- CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
- }
-
- @SuppressWarnings("rawtypes")
- public ChoiceCaseCodecImpl getCaseCodecFor(final Class caseClass) {
- ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
- if (potential != null) {
- return potential;
- }
- ConcreteType typeref = Types.typeForClass(caseClass);
- ChoiceCaseNode caseSchema = caseTypeToCaseSchema.get(typeref);
-
- Preconditions.checkState(caseSchema != null, "Case schema is not available for %s", caseClass.getName());
- Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseSchema);
- BindingCodec newInstance = newInstanceOf(newCodec);
- @SuppressWarnings("unchecked")
- ChoiceCaseCodecImpl caseCodec = new ChoiceCaseCodecImpl(caseClass, caseSchema, newInstance);
- caseCodecs.put(caseClass, caseCodec);
- return caseCodec;
- }
-
- public void onModuleContextAdded(final SchemaContext schemaContext, final Module module, final ModuleContext context) {
- pathToType.putAll(context.getChildNodes());
-
- BiMap<Type, AugmentationSchema> bimap = context.getTypeToAugmentation();
- for (Map.Entry<Type, AugmentationSchema> entry : bimap.entrySet()) {
- Type key = entry.getKey();
- AugmentationSchema value = entry.getValue();
- Collection<DataSchemaNode> augmentedNodes = value.getChildNodes();
- if (augmentedNodes != null && !augmentedNodes.isEmpty()) {
- typeToAugment.put(key, value);
- }
- }
-
- qnamesToIdentityMap.putAll(context.getIdentities());
- for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
- typeToQname.put(
- new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
- identity.getKey());
- }
-
- synchronized (augmentableToAugmentations) {
- augmentableToAugmentations.putAll(context.getAugmentableToAugmentations());
- }
- synchronized (choiceToCases) {
- choiceToCases.putAll(context.getChoiceToCases());
- }
- synchronized (caseTypeToCaseSchema) {
- caseTypeToCaseSchema.putAll(context.getCaseTypeToSchemas());
- }
- }
-
- @Override
- public void onGlobalContextUpdated(final SchemaContext context) {
- currentSchema = context;
- resetDispatchCodecsAdaptation();
-
- }
-
- /**
- * Resets / clears adaptation for all schema context sensitive codecs in
- * order for them to adapt to new schema context and maybe newly discovered
- * augmentations This ensure correct behaviour for augmentations and
- * augmented cases for preexisting codecs, which augmentations were
- * introduced at later point in time.
- *
- * This also makes removed augmentations unavailable.
- */
- private void resetDispatchCodecsAdaptation() {
- synchronized (dispatchCodecs) {
- for (LocationAwareDispatchCodec<?> codec : dispatchCodecs.values()) {
- codec.resetCodec(this);
- }
- }
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public void onChoiceCodecCreated(final Class<?> choiceClass,
- final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, final ChoiceNode schema) {
- ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
- Preconditions.checkState(oldCodec == null);
- BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
- PublicChoiceCodecImpl<?> newCodec = new PublicChoiceCodecImpl(delegate);
- DispatchChoiceCodecImpl dispatchCodec = new DispatchChoiceCodecImpl(choiceClass, this);
- choiceCodecs.put(choiceClass, newCodec);
- synchronized (dispatchCodecs) {
- dispatchCodecs.put(choiceClass, dispatchCodec);
- }
- CodecMapping.setDispatchCodec(choiceCodec, dispatchCodec);
- }
-
- @Override
- public void onValueCodecCreated(final Class<?> valueClass, final Class<?> valueCodec) {
- }
-
- @Override
- public void onCaseCodecCreated(final Class<?> choiceClass,
- final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
- }
-
- @Override
- public void onDataContainerCodecCreated(final Class<?> dataClass,
- final Class<? extends BindingCodec<?, ?>> dataCodec) {
- if (Augmentable.class.isAssignableFrom(dataClass)) {
- AugmentableDispatchCodec augmentableCodec = getAugmentableCodec(dataClass);
- CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
- }
- }
-
- public synchronized AugmentableDispatchCodec getAugmentableCodec(final Class<?> dataClass) {
- AugmentableDispatchCodec ret = augmentableCodecs.get(dataClass);
- if (ret != null) {
- return ret;
- }
- ret = new AugmentableDispatchCodec(dataClass, this);
- augmentableCodecs.put(dataClass, ret);
- synchronized (dispatchCodecs) {
- dispatchCodecs.put(dataClass, ret);
- }
- ret.tryToLoadImplementations();
- return ret;
- }
-
- private static abstract class IntermediateCodec<T> implements DomCodec<T>,
- Delegator<BindingCodec<Map<QName, Object>, Object>> {
-
- private final BindingCodec<Map<QName, Object>, Object> delegate;
-
- @Override
- public BindingCodec<Map<QName, Object>, Object> getDelegate() {
- return delegate;
- }
-
- public IntermediateCodec(final BindingCodec<Map<QName, Object>, Object> delegate) {
- this.delegate = delegate;
- }
-
- @Override
- public Node<?> serialize(final ValueWithQName<T> input) {
- Map<QName, Object> intermediateOutput = delegate.serialize(input);
- return IntermediateMapping.toNode(intermediateOutput);
- }
-
- }
-
- private static class IdentifierCodecImpl<T extends Identifier<?>> extends IntermediateCodec<T> implements
- IdentifierCodec<T> {
-
- public IdentifierCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
- super(delegate);
- }
-
- @Override
- public ValueWithQName<T> deserialize(final Node<?> input) {
- QName qname = input.getNodeType();
- @SuppressWarnings("unchecked")
- T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
- return new ValueWithQName<T>(qname, value);
- }
-
- @Override
- public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
- QName qname = input.getNodeType();
- @SuppressWarnings("unchecked")
- T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
- return new ValueWithQName<T>(qname, value);
- }
-
- @Override
- public CompositeNode serialize(final ValueWithQName<T> input) {
- return (CompositeNode) super.serialize(input);
- }
- }
-
- private static class DataContainerCodecImpl<T extends DataContainer> extends IntermediateCodec<T> implements
- DataContainerCodec<T> {
-
- public DataContainerCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
- super(delegate);
- }
-
- @Override
- public ValueWithQName<T> deserialize(final Node<?> input) {
- if (input == null) {
- return null;
- }
- QName qname = input.getNodeType();
- @SuppressWarnings("unchecked")
- T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
- return new ValueWithQName<T>(qname, value);
- }
-
- @Override
- public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
- if (input == null) {
- return null;
- }
- QName qname = input.getNodeType();
- @SuppressWarnings("unchecked")
- T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
- return new ValueWithQName<T>(qname, value);
- }
-
- @Override
- public CompositeNode serialize(final ValueWithQName<T> input) {
- return (CompositeNode) super.serialize(input);
- }
- }
-
- private interface LocationAwareBindingCodec<P, I> extends BindingCodec<P, I> {
-
- boolean isApplicable(InstanceIdentifier<?> parentPath, CompositeNode data);
-
- public Class<?> getDataType();
-
- }
-
- @SuppressWarnings("rawtypes")
- private static abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements
- BindingCodec {
-
- private final Map<Class, T> implementations = Collections.synchronizedMap(new WeakHashMap<Class, T>());
- private final Set<InstanceIdentifier<?>> adaptedForPaths = new HashSet<>();
- private LazyGeneratedCodecRegistry registry;
-
- protected LocationAwareDispatchCodec(final LazyGeneratedCodecRegistry registry) {
- this.registry = registry;
- }
-
- protected Map<Class, T> getImplementations() {
- return implementations;
- }
-
- /**
- * Resets codec adaptation based on location and schema context.
- *
- * This is required if new cases / augmentations were introduced or
- * removed and first use of codec is triggered by invocation from DOM to
- * Java, so the implementations may change and this may require loading
- * of new codecs and/or removal of existing ones.
- *
- */
- public synchronized void resetCodec(final LazyGeneratedCodecRegistry currentRegistry) {
- registry = currentRegistry;
- adaptedForPaths.clear();
- resetAdaptationImpl();
- }
-
- protected void resetAdaptationImpl() {
- // Intentionally NOOP, subclasses may specify their custom
- // behaviour.
- }
-
- protected final LazyGeneratedCodecRegistry getRegistry() {
- return registry;
- }
-
- protected void addImplementation(final T implementation) {
- implementations.put(implementation.getDataType(), implementation);
- }
-
- @Override
- public final Object deserialize(final Object input) {
- throw new UnsupportedOperationException("Invocation of deserialize without Tree location is unsupported");
- }
-
- @Override
- public final Object deserialize(final Object parent, final InstanceIdentifier parentPath) {
- adaptForPath(parentPath);
- Preconditions.checkArgument(parent instanceof CompositeNode, "node must be of CompositeNode type.");
- CompositeNode parentData = (CompositeNode) parent;
- ArrayList<T> applicable = new ArrayList<>(implementations.size());
-
- /*
- * Codecs are filtered to only ones, which are applicable in
- * supplied parent context.
- */
- for (T impl : getImplementations().values()) {
- @SuppressWarnings("unchecked")
- boolean codecApplicable = impl.isApplicable(parentPath, parentData);
- if (codecApplicable) {
- applicable.add(impl);
- }
- }
- LOG.trace("{}: Deserializing mixins from {}, Schema Location {}, Applicable Codecs: {}, All Codecs: {}",
- this, parent, parentPath, applicable, getImplementations().values());
-
- /*
- * In case of none is applicable, we return null. Since there is no
- * mixin which is applicable in this location.
- */
- if (applicable.isEmpty()) {
- return null;
- }
- return deserializeImpl(parentData, parentPath, applicable);
- }
-
- protected abstract Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> parentPath,
- Iterable<T> applicableCodecs);
-
- @Override
- public Object serialize(final Object input) {
- Preconditions.checkArgument(input instanceof DataContainer);
- Class<? extends DataContainer> inputType = ((DataContainer) input).getImplementedInterface();
- T implementation = implementations.get(inputType);
- if (implementation == null) {
- implementation = tryToLoadImplementationImpl(inputType);
- }
- return implementation;
- }
-
- private T tryToLoadImplementationImpl(final Class<? extends DataContainer> inputType) {
- T implementation = tryToLoadImplementation(inputType);
- Preconditions.checkArgument(implementation != null, "Data type %s is not supported.", inputType);
- addImplementation(implementation);
- return implementation;
- }
-
- protected final synchronized void adaptForPath(final InstanceIdentifier<?> path) {
- if (adaptedForPaths.contains(path)) {
- return;
- }
- LOG.debug("Adapting mixin codec {} for path {}", this, path);
- /**
- * We search in schema context if the use of this location aware
- * codec (augmentable codec, case codec) makes sense on provided
- * location (path)
- *
- */
- Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(
- getRegistry().currentSchema, path);
- /**
- * If context node is present, this codec makes sense on provided
- * location.
- *
- */
- if (contextNode.isPresent()) {
- synchronized (this) {
- /**
- *
- * We adapt (turn on / off) possible implementations of
- * child codecs (augmentations, cases) based on this
- * location.
- *
- *
- */
-
- adaptForPathImpl(path, contextNode.get());
- try {
- /**
- * We trigger serialization of instance identifier, to
- * make sure instance identifier codec is aware of
- * combination of this path / augmentation / case
- */
- getRegistry().getInstanceIdentifierCodec().serialize(path);
- } catch (Exception e) {
- LOG.warn("Exception during preparation of instance identifier codec for path {}.", path, e);
- }
- adaptedForPaths.add(path);
- }
- } else {
- LOG.debug("Context node (parent node) not found for {}", path);
- }
- }
-
- protected abstract T tryToLoadImplementation(Class<? extends DataContainer> inputType);
-
- protected abstract void tryToLoadImplementations();
-
- protected abstract void adaptForPathImpl(InstanceIdentifier<?> path, DataNodeContainer ctx);
- }
-
- @SuppressWarnings("rawtypes")
- private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
- Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
- private final BindingCodec delegate;
- private final ChoiceCaseNode schema;
- private final Map<InstanceIdentifier<?>, ChoiceCaseNode> instantiatedLocations;
- private final Class<?> dataType;
-
- public ChoiceCaseCodecImpl(final Class<?> caseClass, final ChoiceCaseNode caseNode,
- final BindingCodec newInstance) {
- this.delegate = newInstance;
- this.dataType = caseClass;
- this.schema = caseNode;
- instantiatedLocations = new HashMap<>();
- }
-
- @Override
- public ValueWithQName<T> deserialize(final Node<?> input) {
- throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
- }
-
- @Override
- public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
- if (input == null) {
- return null;
- }
- QName qname = input.getNodeType();
- synchronized (instantiatedLocations) {
- ChoiceCaseNode instantiation = instantiatedLocations.get(bindingIdentifier);
- if (instantiation != null) {
- qname = instantiatedLocations.get(bindingIdentifier).getQName();
- }
- }
- @SuppressWarnings("unchecked")
- T value = (T) getDelegate().deserialize(new SimpleEntry(qname, input), bindingIdentifier);
- return new ValueWithQName<T>(qname, value);
- }
-
- @Override
- public CompositeNode serialize(final ValueWithQName<T> input) {
- throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
- }
-
- @Override
- public BindingCodec getDelegate() {
- return delegate;
- }
-
- public ChoiceCaseNode getSchema() {
- return schema;
- }
-
- @Override
- @Deprecated
- public boolean isAcceptable(final Node<?> input) {
- return checkAgainstSchema(schema, input);
- }
-
- private static boolean checkAgainstSchema(final ChoiceCaseNode schema, final Node<?> node) {
- if (node instanceof CompositeNode) {
- CompositeNode input = (CompositeNode) node;
- for (Node<?> childNode : input.getValue()) {
- QName child = childNode.getNodeType();
- if (schema.getDataChildByName(child) != null) {
- return true;
- }
- }
- }
- return false;
- }
-
- @Override
- public Class<?> getDataType() {
- return dataType;
- }
-
- public void adaptForPath(final InstanceIdentifier<?> augTarget, final ChoiceCaseNode choiceCaseNode) {
- synchronized (instantiatedLocations) {
- instantiatedLocations.put(augTarget, choiceCaseNode);
- }
- }
-
- @Override
- public boolean isApplicable(final InstanceIdentifier path, final CompositeNode input) {
- ChoiceCaseNode instantiatedSchema = null;
- synchronized (instantiatedLocations) {
- instantiatedSchema = instantiatedLocations.get(path);
- }
- if (instantiatedSchema == null) {
- return false;
- }
- return checkAgainstSchema(instantiatedSchema, input);
- }
-
- protected boolean isAugmenting(final QName choiceName, final QName proposedQName) {
- if (schema.isAugmenting()) {
- return true;
- }
- // Choice QName
- QName parentQName = Iterables.get(schema.getPath().getPathTowardsRoot(), 1);
- if (!parentQName.getNamespace().equals(schema.getQName().getNamespace())) {
- return true;
- }
- if (!parentQName.equals(choiceName)) {
- // This item is instantiation of choice via uses in other YANG
- // module
- if (choiceName.getNamespace().equals(schema.getQName().getNamespace())) {
- // Original definition of grouping is in same namespace
- // as original definition of case
- // so for sure case is introduced via instantiation of
- // grouping
- return false;
- }
- // Since we are still here, that means case has same namespace
- // as its parent, which is instantiation of grouping
- // but case namespace is different from parent node
- // so it is augmentation.
- return true;
- }
- return false;
- }
-
- @Override
- public String toString() {
- return "ChoiceCaseCodec [case=" + dataType + ", knownLocations=" + instantiatedLocations.keySet() + "]";
- }
- }
-
- private static class PublicChoiceCodecImpl<T> implements ChoiceCodec<T>,
- Delegator<BindingCodec<Map<QName, Object>, Object>> {
-
- private final BindingCodec<Map<QName, Object>, Object> delegate;
-
- public PublicChoiceCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
- this.delegate = delegate;
- }
-
- @Override
- public ValueWithQName<T> deserialize(final Node<?> input) {
- throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
- }
-
- @Override
- public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
- throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
- }
-
- @Override
- public Node<?> serialize(final ValueWithQName<T> input) {
- throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
- }
-
- @Override
- public BindingCodec<Map<QName, Object>, Object> getDelegate() {
- return delegate;
- }
-
- }
-
- class DispatchChoiceCodecImpl extends LocationAwareDispatchCodec<ChoiceCaseCodecImpl<?>> {
- private final Class<?> choiceType;
- private final QName choiceName;
-
- private DispatchChoiceCodecImpl(final Class<?> type, final LazyGeneratedCodecRegistry registry) {
- super(registry);
- choiceType = type;
- choiceName = BindingReflections.findQName(type);
- }
-
- @Override
- public Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
- final Iterable<ChoiceCaseCodecImpl<?>> codecs) {
- ChoiceCaseCodecImpl<?> caseCodec = Iterables.getOnlyElement(codecs);
- ValueWithQName<?> value = caseCodec.deserialize(input, path);
- if (value != null) {
- return value.getValue();
- }
- return null;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Object serialize(final Object input) {
- Preconditions.checkArgument(input instanceof Map.Entry<?, ?>, "Input must be QName, Value");
- @SuppressWarnings("rawtypes")
- QName derivedQName = (QName) ((Map.Entry) input).getKey();
- @SuppressWarnings("rawtypes")
- Object inputValue = ((Map.Entry) input).getValue();
- Preconditions.checkArgument(inputValue instanceof DataObject);
- Class<? extends DataContainer> inputType = ((DataObject) inputValue).getImplementedInterface();
- ChoiceCaseCodecImpl<?> codec = tryToLoadImplementation(inputType);
- Preconditions.checkState(codec != null, "Unable to get codec for %s", inputType);
- if (codec.isAugmenting(choiceName, derivedQName)) {
- // If choice is augmenting we use QName which defined this
- // augmentation
- return codec.getDelegate().serialize(new ValueWithQName<>(codec.getSchema().getQName(), inputValue));
- }
- return codec.getDelegate().serialize(input);
- }
-
- @SuppressWarnings("rawtypes")
- protected Optional<ChoiceCaseCodecImpl> tryToLoadImplementation(final Type potential) {
- try {
- @SuppressWarnings("unchecked")
- Class<? extends DataContainer> clazz = (Class<? extends DataContainer>) classLoadingStrategy
- .loadClass(potential);
- ChoiceCaseCodecImpl codec = tryToLoadImplementation(clazz);
- addImplementation(codec);
- return Optional.of(codec);
- } catch (ClassNotFoundException e) {
- LOG.warn("Failed to find class for choice {}", potential, e);
- }
- return Optional.absent();
- }
-
- @Override
- protected ChoiceCaseCodecImpl<?> tryToLoadImplementation(final Class<? extends DataContainer> inputType) {
- ChoiceCaseCodecImpl<?> codec = getCaseCodecFor(inputType);
- addImplementation(codec);
- return codec;
- }
-
- @Override
- protected void tryToLoadImplementations() {
- Type type = referencedType(choiceType);
- Collection<Type> potentialCases;
- synchronized (choiceToCases) {
- potentialCases = choiceToCases.get(type);
- }
- for (Type potential : potentialCases) {
- try {
- tryToLoadImplementation(potential);
- } catch (CodeGenerationException e) {
- LOG.warn("Failed to proactively generate choice code for {}", type, e);
- }
- }
- }
-
- @Override
- protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
- tryToLoadImplementations();
- Optional<ChoiceNode> newChoice = BindingSchemaContextUtils.findInstantiatedChoice(ctxNode, choiceType);
- if(!newChoice.isPresent()) {
- // Choice is nested inside other choice, so we need to look two levels deep.
- in_choices: for(DataSchemaNode child : ctxNode.getChildNodes()) {
- if(child instanceof ChoiceNode) {
- Optional<ChoiceNode> potential = findChoiceInChoiceCases((ChoiceNode) child, choiceType);
- if(potential.isPresent()) {
- newChoice = potential;
- break in_choices;
- }
- }
- }
- }
-
- Preconditions.checkState(newChoice.isPresent(), "BUG: Unable to find instantiated choice node in schema.");
- for (@SuppressWarnings("rawtypes")
- Entry<Class, ChoiceCaseCodecImpl<?>> codec : getImplementations().entrySet()) {
- ChoiceCaseCodecImpl<?> caseCodec = codec.getValue();
- Optional<ChoiceCaseNode> instantiatedSchema = BindingSchemaContextUtils.findInstantiatedCase(
- newChoice.get(), caseCodec.getSchema());
- if (instantiatedSchema.isPresent()) {
- caseCodec.adaptForPath(augTarget, instantiatedSchema.get());
- }
- }
- }
-
- private Optional<ChoiceNode> findChoiceInChoiceCases(final ChoiceNode choice, final Class<?> choiceType) {
- for(ChoiceCaseNode caze : choice.getCases()) {
- Optional<ChoiceNode> potential = BindingSchemaContextUtils.findInstantiatedChoice(caze, choiceType);
- if(potential.isPresent()) {
- return potential;
- }
- }
- return Optional.absent();
- }
-
- @Override
- public String toString() {
- return "DispatchChoiceCodecImpl [choiceType=" + choiceType + "]";
- }
- }
-
- /**
- *
- * Dispatch codec for augmented object, which processes augmentations
- * <p>
- * This codec is used from DataObject codec generated using
- * {@link TransformerGenerator#transformerFor(Class)} and is wired during
- * {@link LazyGeneratedCodecRegistry#onDataContainerCodecCreated(Class, Class)}.
- * <p>
- * Instance of this codec is associated with class of Binding DTO which
- * represents target for augmentations.
- *
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- static class AugmentableDispatchCodec extends LocationAwareDispatchCodec<AugmentationCodecWrapper> {
-
- private final Class augmentableType;
-
- /**
- * Construct augmetable dispatch codec.
- *
- * @param type
- * Class representing augmentation target
- * @param registry
- * Registry with which this codec is associated.
- */
- public AugmentableDispatchCodec(final Class type, final LazyGeneratedCodecRegistry registry) {
- super(registry);
- Preconditions.checkArgument(Augmentable.class.isAssignableFrom(type));
- augmentableType = type;
- }
-
- /**
- * Serializes object to list of values which needs to be injected into
- * resulting DOM Node. Injection of data to parent DOM Node is handled
- * by caller (in this case generated codec).
- *
- * TODO: Deprecate use of augmentation codec without instance instance
- * identifier
- *
- * @return list of nodes, which needs to be added to parent node.
- *
- */
- @Override
- public Object serialize(final Object input) {
- Preconditions.checkArgument(augmentableType.isInstance(input), "Object %s is not instance of %s ", input,
- augmentableType);
- if (input instanceof Augmentable<?>) {
- Map<Class<? extends Augmentation<?>>, Augmentation<?>> augmentations = BindingReflections
- .getAugmentations((Augmentable<?>) input);
- return serializeImpl(augmentations);
- }
- return null;
- }
-
- /**
- *
- * Serialization of augmentations, returns list of composite nodes,
- * which needs to be injected to parent node.
- *
- * @param input
- * Map of classes to augmentations
- * @return List of nodes, which should be added to parent node.
- */
- private List serializeImpl(final Map<Class<? extends Augmentation<?>>, Augmentation<?>> input) {
- List ret = new ArrayList<>();
- for (Entry<Class<? extends Augmentation<?>>, Augmentation<?>> entry : input.entrySet()) {
- AugmentationCodec codec = getRegistry().getCodecForAugmentation(entry.getKey());
- CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
- ret.addAll(node.getValue());
- }
- return ret;
- }
-
- /**
- *
- * Deserialization of augmentation which is location aware.
- *
- * Note: In case of composite nodes as an input, each codec is invoked
- * since there is no augmentation identifier and we need to look for
- * concrete classes. FIXME: Maybe faster variation will be by extending
- * {@link AugmentationCodecWrapper} to look for particular QNames, which
- * will filter incoming set of codecs.
- *
- *
- * @param input
- * Input representation of data
- * @param path
- * Wildcarded instance identifier representing location of
- * augmentation parent in conceptual schema tree
- * @param codecs
- * Set of codecs which are applicable for supplied
- * <code>path</code>, selected by caller to be used by
- * deserialization
- *
- *
- */
- @Override
- public Map<Class, Augmentation> deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
- final Iterable<AugmentationCodecWrapper> codecs) {
- LOG.trace("{}: Going to deserialize augmentations from {} in location {}. Available codecs {}", this,
- input, path, codecs);
- Map<Class, Augmentation> ret = new HashMap<>();
- for (AugmentationCodecWrapper codec : codecs) {
- // We add Augmentation Identifier to path, in order to
- // correctly identify children.
- Class type = codec.getDataType();
- final InstanceIdentifier augmentPath = path.augmentation(type);
- ValueWithQName<?> value = codec.deserialize(input, augmentPath);
- if (value != null && value.getValue() != null) {
- ret.put(type, (Augmentation) value.getValue());
- }
- }
- return ret;
- }
-
- /**
- *
- * Tries to load implementation of concrete augmentation codec for
- * supplied type
- *
- * Loading of codec may fail, because of supplied type may not be
- * visible by classloaders known by registry. If class was not found
- * returns {@link Optional#absent()}.
- *
- * @param potential
- * Augmentation class identifier for which codecs should be
- * loaded.
- * @return Optional with codec for supplied type
- *
- */
- protected Optional<AugmentationCodecWrapper> tryToLoadImplementation(final Type potential) {
- try {
- Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) getRegistry().classLoadingStrategy
- .loadClass(potential);
- return Optional.of(tryToLoadImplementation(clazz));
- } catch (ClassNotFoundException e) {
- LOG.warn("Failed to find class for augmentation of {}", potential, e);
- }
- return Optional.absent();
- }
-
- @Override
- protected AugmentationCodecWrapper tryToLoadImplementation(final Class inputType) {
- AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getRegistry().getCodecForAugmentation(
- inputType);
- addImplementation(potentialImpl);
- return potentialImpl;
- }
-
- @Override
- protected void tryToLoadImplementations() {
- Type type = referencedType(augmentableType);
- Collection<Type> potentialAugmentations;
- synchronized (augmentableToAugmentations) {
- potentialAugmentations = new ArrayList(augmentableToAugmentations.get(type));
- }
- for (Type potential : potentialAugmentations) {
- try {
- tryToLoadImplementation(potential);
- } catch (CodeGenerationException e) {
- LOG.warn("Failed to proactively generate augment code for {}", type, e);
- }
- }
- }
-
- @Override
- protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
- if (ctxNode instanceof AugmentationTarget) {
- Set<AugmentationSchema> availableAugmentations = ((AugmentationTarget) ctxNode)
- .getAvailableAugmentations();
- if (!availableAugmentations.isEmpty()) {
- updateAugmentationMapping(augTarget, availableAugmentations);
- }
- }
- }
-
- /**
- *
- * Adapts augmentation codec for specific provider location (target)
- *
- * Since augmentation are not forward-referencing and may be discovered
- * during runtime, we need to adapt {@link AugmentableDispatchCodec},
- * {@link AugmentationCodecWrapper} and {@link InstanceIdentifierCodec}
- * for this newly discovered location where augmentation may be used.
- *
- * Adaptation consists of:
- * <ol>
- * <li>scan of available (valid) augmentations for current location
- * <li>lookup for Java classes derived from this augmentations
- * <li>generation of missing codecs
- * <li>updating Augmentation codecs to work with new location
- * <li>updating Instance Identifier to work with new location
- *
- */
- private void updateAugmentationMapping(final InstanceIdentifier<?> augTarget,
- final Set<AugmentationSchema> availableAugmentations) {
- for (AugmentationSchema aug : availableAugmentations) {
-
- Type potentialType = getTypeForAugmentation(aug);
- if (potentialType != null) {
- Optional<AugmentationCodecWrapper> potentialImpl = tryToLoadImplementation(potentialType);
- if (potentialImpl.isPresent()) {
- potentialImpl.get().addApplicableFor(augTarget, aug);
- Class augType = potentialImpl.get().getDataType();
- InstanceIdentifier augPath = augTarget.augmentation(augType);
- try {
-
- org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier domPath = getRegistry()
- .getInstanceIdentifierCodec().serialize(augPath);
- if (domPath == null) {
- LOG.error("Unable to serialize instance identifier for {}", augPath);
- }
- } catch (Exception e) {
- LOG.error("Unable to serialize instance identifiers for {}", augPath, e);
- }
-
- }
- } else {
- // Omits warning for empty augmentations since they are not
- // represented in data
- if (!aug.getChildNodes().isEmpty()) {
- LOG.warn("Could not find generated type for augmentation {} with children {}", aug,
- aug.getChildNodes());
- }
- }
- }
- }
-
- private Type getTypeForAugmentation(final AugmentationSchema aug) {
- Optional<AugmentationSchema> currentAug = Optional.of(aug);
- while (currentAug.isPresent()) {
- Type potentialType = typeToAugment.inverse().get(currentAug.get());
- if (potentialType != null) {
- return potentialType;
- }
- currentAug = currentAug.get().getOriginalDefinition();
- }
- return null;
- }
-
- @Override
- public String toString() {
- return "AugmentableDispatchCodec [augmentable=" + augmentableType + "]";
- }
-
- }
-
- @SuppressWarnings("rawtypes")
- private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
- Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
-
- private final BindingCodec delegate;
- private final QName augmentationQName;
- private final Multimap<InstanceIdentifier<?>, QName> validAugmentationTargets;
- private final Class<?> augmentationType;
-
- public AugmentationCodecWrapper(final BindingCodec<Map<QName, Object>, Object> rawCodec, final Class<?> dataType) {
- this.delegate = rawCodec;
- this.augmentationType = dataType;
- this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
- this.validAugmentationTargets = Multimaps.synchronizedSetMultimap(HashMultimap
- .<InstanceIdentifier<?>, QName> create());
- }
-
- public void addApplicableFor(final InstanceIdentifier<?> path, final AugmentationSchema aug) {
- for (DataSchemaNode child : aug.getChildNodes()) {
- validAugmentationTargets.put(path, child.getQName());
- }
- }
-
- @Override
- public BindingCodec getDelegate() {
- return delegate;
- }
-
- @Override
- public CompositeNode serialize(final ValueWithQName<T> input) {
- @SuppressWarnings("unchecked")
- List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
- List<Node<?>> serialized = new ArrayList<>(rawValues.size());
- for (Map<QName, Object> val : rawValues) {
- serialized.add(IntermediateMapping.toNode(val));
- }
- return new CompositeNodeTOImpl(input.getQname(), null, serialized);
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public ValueWithQName<T> deserialize(final Node<?> input) {
- Object rawCodecValue = getDelegate().deserialize(input);
- return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
- Object rawCodecValue = getDelegate().deserialize(input, bindingIdentifier);
- return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
- }
-
- @Override
- public QName getAugmentationQName() {
- return augmentationQName;
- }
-
- @Override
- public boolean isAcceptable(final InstanceIdentifier<?> path) {
- if (path == null) {
- return false;
- }
- return validAugmentationTargets.containsKey(path);
- }
-
- @Override
- public boolean isApplicable(final InstanceIdentifier parentPath, final CompositeNode parentData) {
- return isAcceptable(parentPath);
- }
-
- @Override
- public Class<?> getDataType() {
- return augmentationType;
- }
-
- @Override
- public String toString() {
- return "AugmentationCodecWrapper [augmentation=" + augmentationType + ", knownLocations="
- + validAugmentationTargets.keySet() + "]";
- }
- }
-
- @SuppressWarnings("rawtypes")
- private class IdentityCompositeCodec implements IdentityCodec {
-
- @Override
- public Object deserialize(final Object input) {
- Preconditions.checkArgument(input instanceof QName);
- return deserialize((QName) input);
- }
-
- @Override
- public Class<?> deserialize(final QName input) {
- if (input == null) {
- return null;
- }
- Type type = qnamesToIdentityMap.get(input);
- if (type == null) {
- String packageName = BindingMapping.getRootPackageName(input);
- String className = BindingMapping.getClassName(input);
- type = new ReferencedTypeImpl(packageName, className);
- }
- try {
- final Class<?> cls = classLoadingStrategy.loadClass(type);
- if (cls != null) {
- serialize(cls);
- return cls;
- }
- } catch (Exception e) {
- LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
- type.getFullyQualifiedName(), e);
- }
- return null;
-
- }
-
- @Override
- public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
- return deserialize(input);
- }
-
- @Override
- public QName serialize(final Class input) {
- Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
- bindingClassEncountered(input);
- QName qname = identityQNames.get(input);
- if (qname != null) {
- return qname;
- }
- qname = BindingReflections.findQName(input);
- if (qname != null) {
- identityQNames.put(input, qname);
- }
- return qname;
- }
-
- @Override
- public Object serialize(final Object input) {
- Preconditions.checkArgument(input instanceof Class);
- return serialize((Class) input);
- }
-
- }
-
- private static final Type referencedType(final Class<?> augmentableType) {
- return new ReferencedTypeImpl(augmentableType.getPackage().getName(), augmentableType.getSimpleName());
- }
-
-}
import java.util.Map;
import java.util.Set;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
+import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
import org.opendaylight.yangtools.yang.common.QName;
private final BiMap<Type,ChoiceCaseNode> caseTypeToSchema = HashBiMap.create();
private final Multimap<Type, Type> augmentableToAugmentations = HashMultimap.create();
+ private final Map<SchemaPath, Type> innerTypes = new HashMap<>();
List<Type> getGeneratedTypes() {
List<Type> result = new ArrayList<>();
typeToSchema.put(type, typedef);
}
+ /**
+ * Adds mapping between schema path and inner enum.
+ *
+ * @param path
+ * @param enumBuilder
+ */
+ void addInnerTypedefType(SchemaPath path, EnumBuilder enumBuilder) {
+ innerTypes.put(path, enumBuilder);
+ }
+
+ public Type getInnerType(SchemaPath path) {
+ return innerTypes.get(path);
+ }
+
}
+++ /dev/null
-/**
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Multimap;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-import javassist.ClassPool;
-import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
-import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
-import org.opendaylight.yangtools.binding.generator.util.Types;
-import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
-import org.opendaylight.yangtools.sal.binding.generator.util.YangSchemaUtils;
-import org.opendaylight.yangtools.sal.binding.model.api.Type;
-import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
-import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.BindingMapping;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
-import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-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.PathArgument;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.codec.AugmentationCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
-import org.opendaylight.yangtools.yang.data.impl.codec.DataContainerCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
-import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.concurrent.GuardedBy;
-import java.net.URI;
-import java.util.AbstractMap.SimpleEntry;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ExecutionException;
-
-public class RuntimeGeneratedMappingServiceImpl implements BindingIndependentMappingService, SchemaContextListener,
-SchemaLock, AutoCloseable, SchemaContextHolder, TypeResolver {
-
- private static final Logger LOG = LoggerFactory.getLogger(RuntimeGeneratedMappingServiceImpl.class);
-
- private final ConcurrentMap<Type, Set<QName>> serviceTypeToRpc = new ConcurrentHashMap<>();
-
- /**
- * This is map of types which users are waiting for.
- */
- @GuardedBy("this")
- private final Multimap<Type, SettableFuture<Type>> promisedTypes = HashMultimap.create();
-
- private final ClassLoadingStrategy classLoadingStrategy;
-
- private final AbstractTransformerGenerator binding;
- private final LazyGeneratedCodecRegistry registry;
- private final ClassPool pool;
-
- /*
- * FIXME: updated here, access from AbstractTransformer
- */
- private final Map<Type, AugmentationSchema> typeToAugmentation = new ConcurrentHashMap<>();
- private final ConcurrentMap<Type, GeneratedTypeBuilder> typeToDefinition = new ConcurrentHashMap<>();
- private final ConcurrentMap<Type, SchemaNode> typeToSchemaNode = new ConcurrentHashMap<>();
- private final Map<SchemaPath, GeneratedTypeBuilder> pathToType = new ConcurrentHashMap<>();
-
- // FIXME: need to figure these out
- private final ConcurrentMap<Type, Type> typeDefinitions = new ConcurrentHashMap<>();
- private SchemaContext schemaContext;
-
- public RuntimeGeneratedMappingServiceImpl(final ClassPool pool) {
- this(pool, GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
- }
-
- public RuntimeGeneratedMappingServiceImpl(final ClassPool pool, final ClassLoadingStrategy strat) {
- this.pool = Preconditions.checkNotNull(pool);
- this.classLoadingStrategy = Preconditions.checkNotNull(strat);
- // FIXME: this escapes constructor
- binding = new TransformerGenerator(this, pool);
- registry = new LazyGeneratedCodecRegistry(this, binding, classLoadingStrategy);
- binding.setListener(registry);
-
- // if (ctx !== null) {
- // listenerRegistration = ctx.registerService(SchemaContextListener,
- // this, new Hashtable<String, String>());
- // }
- }
-
- @Override
- public synchronized SchemaContext getSchemaContext() {
- return schemaContext;
- }
-
- @Override
- public synchronized void onGlobalContextUpdated(final SchemaContext context) {
- this.schemaContext = Preconditions.checkNotNull(context);
- this.recreateBindingContext(context);
- this.registry.onGlobalContextUpdated(context);
- }
-
- @GuardedBy("this")
- private void recreateBindingContext(final SchemaContext schemaContext) {
- BindingGeneratorImpl newBinding = new BindingGeneratorImpl(false);
- newBinding.generateTypes(schemaContext);
-
- for (Map.Entry<Module, ModuleContext> entry : newBinding.getModuleContexts().entrySet()) {
-
- registry.onModuleContextAdded(schemaContext, entry.getKey(), entry.getValue());
- pathToType.putAll(entry.getValue().getChildNodes());
- Module module = entry.getKey();
- ModuleContext context = entry.getValue();
- updateBindingFor(context.getChildNodes(), schemaContext);
- updateBindingFor(context.getCases(), schemaContext);
- String namespace = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
-
- if (!module.getRpcs().isEmpty()) {
- Set<QName> rpcs = new HashSet<>();
- for (RpcDefinition rpc : module.getRpcs()) {
- rpcs.add(rpc.getQName());
- }
- Type serviceClass = new ReferencedTypeImpl(namespace, BindingMapping.getClassName(module.getName())
- + "Service");
- serviceTypeToRpc.put(serviceClass, rpcs);
- updatePromisedSchemas(serviceClass);
- }
-
- Map<SchemaPath, Type> typedefs = context.getTypedefs();
- for (Map.Entry<SchemaPath, Type> typedef : typedefs.entrySet()) {
- Type value = typedef.getValue();
- Type typeRef = new ReferencedTypeImpl(value.getPackageName(), value.getName());
- typeDefinitions.put(typeRef, value);
- TypeDefinition<?> schemaNode = YangSchemaUtils.findTypeDefinition(schemaContext, typedef.getKey());
- if (schemaNode != null) {
-
- typeToSchemaNode.put(typeRef, schemaNode);
- } else {
- LOG.error("Type definition for {} is not available", value);
- }
- }
- List<GeneratedTypeBuilder> augmentations = context.getAugmentations();
- for (GeneratedTypeBuilder augmentation : augmentations) {
- typeToDefinition.put(augmentation, augmentation);
- }
- typeToAugmentation.putAll(context.getTypeToAugmentation());
- for (GeneratedTypeBuilder augmentation : augmentations) {
- updatePromisedSchemas(augmentation);
- }
- }
- }
-
- @Override
- public CompositeNode toDataDom(final DataObject data) {
- return toCompositeNodeImpl(data);
- }
-
- @Override
- public Entry<YangInstanceIdentifier, CompositeNode> toDataDom(
- final Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject> entry) {
- try {
- org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier key = toDataDom(entry.getKey());
- CompositeNode data;
- if (Augmentation.class.isAssignableFrom(entry.getKey().getTargetType())) {
- data = toCompositeNodeImplAugument(key, entry.getValue());
- } else {
- data = toCompositeNodeImpl(key, entry.getValue());
- }
- return new SimpleEntry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode>(key,
- data);
-
- } catch (Exception e) {
- LOG.error("Error during serialization for {}.", entry.getKey(), e);
- throw e;
- }
- }
-
- private CompositeNode toCompositeNodeImpl(final DataObject object) {
- Class<? extends DataContainer> cls = object.getImplementedInterface();
- waitForSchema(cls);
- DataContainerCodec<DataObject> codec = (DataContainerCodec<DataObject>) registry.getCodecForDataObject(cls);
- return codec.serialize(new ValueWithQName<DataObject>(null, object));
- }
-
- private CompositeNode toCompositeNodeImpl(final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier identifier,
- final DataObject object) {
- PathArgument last = identifier.getLastPathArgument();
- Class<? extends DataContainer> cls = object.getImplementedInterface();
- waitForSchema(cls);
- DataContainerCodec<DataObject> codec = (DataContainerCodec<DataObject>) registry.getCodecForDataObject(cls);
- return codec.serialize(new ValueWithQName<DataObject>(last.getNodeType(), object));
- }
-
- private CompositeNode toCompositeNodeImplAugument(
- final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier identifier, final DataObject object) {
-
- // val cls = object.implementedInterface;
- // waitForSchema(cls);
- org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument last = identifier.getLastPathArgument();
- AugmentationCodec codec = registry.getCodecForAugmentation((Class) object.getImplementedInterface());
- CompositeNode ret = codec.serialize(new ValueWithQName<DataObject>(last.getNodeType(), object));
- if (last instanceof NodeIdentifierWithPredicates) {
- NodeIdentifierWithPredicates predicates = (NodeIdentifierWithPredicates) last;
- List<Node<?>> newNodes = new ArrayList<Node<?>>(predicates.getKeyValues().size());
- for (Map.Entry<QName, Object> predicate : predicates.getKeyValues().entrySet()) {
- newNodes.add(new SimpleNodeTOImpl<Object>(predicate.getKey(), null, predicate.getValue()));
- }
- newNodes.addAll(ret.getValue());
- return new CompositeNodeTOImpl(last.getNodeType(), null, newNodes);
- }
- return ret;
- }
-
- @Override
- public void waitForSchema(final Class<?> cls) {
- final ListenableFuture<Type> f = getSchemaDefinition(cls);
- if (f != null) {
- try {
- f.get();
- } catch (InterruptedException | ExecutionException e) {
- LOG.warn("Waiting for schema for class {} failed", cls, e);
- throw new IllegalStateException(String.format("Failed to get schema for %s", cls), e);
- }
- LOG.info("Schema for {} became available, thread unblocked", cls);
- }
- }
-
- @Override
- public YangInstanceIdentifier toDataDom(
- final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> path) {
- for (final org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument arg : path.getPathArguments()) {
- this.waitForSchema(arg.getType());
- }
-
- final InstanceIdentifierCodec c = registry.getInstanceIdentifierCodec();
- Preconditions.checkState(c != null, "InstanceIdentifierCodec not present");
- return c.serialize(path);
- }
-
- @Override
- public DataObject dataObjectFromDataDom(
- final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> path,
- final CompositeNode domData) throws DeserializationException {
- if (domData == null) {
- return null;
- }
-
- try {
- final Class<? extends DataContainer> container = path.getTargetType();
- // FIXME: deprecate use without iid
- final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> wildcardedPath = createWildcarded(path);
-
- final DataContainerCodec<? extends DataContainer> transformer = registry.getCodecForDataObject(container);
- Preconditions.checkState(transformer != null, "Failed to find codec for type %s", container);
-
- final ValueWithQName<? extends DataContainer> deserialize = transformer.deserialize(domData, wildcardedPath);
- if (deserialize == null) {
- return null;
- }
-
- return (DataObject) deserialize.getValue();
- } catch (Exception e) {
- LOG.warn("Failed to deserialize path {} data {}", path, domData);
- throw new DeserializationException("Data deserialization failed", e);
- }
- }
-
- @Override
- public org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends Object> fromDataDom(final YangInstanceIdentifier entry) throws DeserializationException {
- try {
- final InstanceIdentifierCodec c = registry.getInstanceIdentifierCodec();
- Preconditions.checkState(c != null, "InstanceIdentifierCodec not present");
- return c.deserialize(entry);
- } catch (Exception e) {
- LOG.warn("Failed to deserialize entry {}", entry);
- throw new DeserializationException("Entry deserialization failed", e);
- }
- }
-
- @Override
- public CodecRegistry getCodecRegistry() {
- return this.registry;
- }
-
- private void updateBindingFor(final Map<SchemaPath, GeneratedTypeBuilder> map, final SchemaContext module) {
- for (Map.Entry<SchemaPath, GeneratedTypeBuilder> entry : map.entrySet()) {
- SchemaNode schemaNode = SchemaContextUtil.findDataSchemaNode(module, entry.getKey());
-
- // LOG.info("{} : {}",entry.key,entry.value.fullyQualifiedName)
- Type typeRef = new ReferencedTypeImpl(entry.getValue().getPackageName(), entry.getValue().getName());
- typeToDefinition.put(typeRef, entry.getValue());
- if (schemaNode != null) {
- typeToSchemaNode.put(typeRef, schemaNode);
- updatePromisedSchemas(entry.getValue());
- }
- }
- }
-
-
- @Override
- public Set<QName> getRpcQNamesFor(final Class<? extends RpcService> service) {
- Set<QName> serviceRef = serviceTypeToRpc.get(new ReferencedTypeImpl(service.getPackage().getName(), service
- .getSimpleName()));
- if (serviceRef == null) {
- waitForSchema(service);
- serviceRef = serviceTypeToRpc.get(new ReferencedTypeImpl(service.getPackage().getName(), service
- .getSimpleName()));
- }
- return serviceRef;
- }
-
- private ListenableFuture<Type> getSchemaDefinition(final Class<?> cls) {
- final Type type = Types.typeForClass(cls);
- synchronized (this) {
- if (typeToDefinition.containsKey(type)) {
- return null;
- }
-
- LOG.info("Thread is going to wait for schema for: {}", type.getFullyQualifiedName());
- final SettableFuture<Type> f = SettableFuture.create();
- promisedTypes.put(type, f);
- return f;
- }
- }
-
- @GuardedBy("this")
- private void updatePromisedSchemas(final Type builder) {
- final Type ref = new ReferencedTypeImpl(builder.getPackageName(), builder.getName());
- final Collection<SettableFuture<Type>> futures = promisedTypes.get(ref);
-
- if (futures != null) {
- for (SettableFuture<Type> future : futures) {
- future.set(builder);
- }
- promisedTypes.removeAll(builder);
- }
- }
-
- @Override
- public void close() {
- // Nothing to do
- }
-
- @Override
- public DataContainer dataObjectFromDataDom(final Class<? extends DataContainer> container,
- final CompositeNode domData) {
- // FIXME: Add check for valids inputs
- // which are Notification and Rpc Input / Rpc Output
-
- org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataContainer> id = org.opendaylight.yangtools.yang.binding.InstanceIdentifier
- .create((Class) container);
- Preconditions.checkNotNull(id, "Failed to create path for type %s", container);
-
- try {
- return dataObjectFromDataDom(id, domData);
- } catch (DeserializationException e) {
- LOG.warn("Conversion of class {} path {} data {} failed", container, id, domData, e);
- throw new IllegalStateException("Failed to create data object", e);
- }
- }
-
- @Override
- public synchronized Optional<Class<? extends RpcService>> getRpcServiceClassFor(final String namespace, final String revision) {
- Module module = null;
- if (schemaContext != null) {
- module = schemaContext.findModuleByNamespaceAndRevision(URI.create(namespace), QName.parseRevision(revision));
- }
- if (module == null) {
- return Optional.absent();
- }
- try {
- Optional<Type> rpcTypeName = getRpcServiceType(module);
- if (rpcTypeName.isPresent()) {
- Class<?> rpcClass = classLoadingStrategy.loadClass(rpcTypeName.get().getFullyQualifiedName());
- return Optional.<Class<? extends RpcService>> of((Class<? extends RpcService>) rpcClass);
- }
- } catch (Exception e) {
- LOG.debug("RPC class not present for {},{}", namespace, revision, e);
- }
- return Optional.absent();
- }
-
- public Optional<Type> getRpcServiceType(final Module module) {
- String namespace = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
- if (module.getRpcs().isEmpty()) {
- return Optional.<Type> absent();
- }
- return Optional.<Type> of(new ReferencedTypeImpl(namespace, BindingMapping.getClassName(module.getName())
- + BindingMapping.RPC_SERVICE_SUFFIX));
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private static final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> createWildcarded(
- final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> path) {
-
- LinkedList<org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument> wildcardedArgs = new LinkedList<>();
- for(org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument pathArg : path.getPathArguments()) {
- if(pathArg instanceof IdentifiableItem<?,?>) {
- pathArg = new Item(pathArg.getType());
- }
- wildcardedArgs.add(pathArg);
- }
- return org.opendaylight.yangtools.yang.binding.InstanceIdentifier.create(wildcardedArgs);
- }
-
- @Override
- public final AugmentationSchema getAugmentation(final Type type) {
- return typeToAugmentation.get(type);
- }
-
- @Override
- public final GeneratedTypeBuilder getDefinition(final Type type) {
- return typeToDefinition.get(type);
- }
-
- @Override
- public final SchemaNode getSchemaNode(final Type type) {
- return typeToSchemaNode.get(type);
- }
-
- @Override
- public final GeneratedTypeBuilder getTypeBuilder(final SchemaPath path) {
- return pathToType.get(path);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-public interface StaticFieldInitializer {
-
- void initializeStaticFields(Class<?> cls);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl
-
-import com.google.common.base.Joiner
-import com.google.common.base.Supplier
-import java.io.File
-import java.security.ProtectionDomain
-import java.util.AbstractMap.SimpleEntry
-import java.util.Collection
-import java.util.Collections
-import java.util.HashMap
-import java.util.HashSet
-import java.util.Iterator
-import java.util.List
-import java.util.Map
-import java.util.Map.Entry
-import java.util.Set
-import java.util.TreeSet
-import javassist.CannotCompileException
-import javassist.ClassPool
-import javassist.CtClass
-import javassist.CtField
-import javassist.CtMethod
-import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl
-import org.opendaylight.yangtools.binding.generator.util.Types
-import org.opendaylight.yangtools.sal.binding.generator.util.CodeGenerationException
-import org.opendaylight.yangtools.sal.binding.generator.util.SourceCodeGenerator
-import org.opendaylight.yangtools.sal.binding.generator.util.SourceCodeGeneratorFactory
-import org.opendaylight.yangtools.sal.binding.generator.util.XtendHelper
-import org.opendaylight.yangtools.sal.binding.model.api.Enumeration
-import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty
-import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject
-import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
-import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType
-import org.opendaylight.yangtools.sal.binding.model.api.Type
-import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder
-import org.opendaylight.yangtools.util.ClassLoaderUtils
-import org.opendaylight.yangtools.yang.binding.Augmentation
-import org.opendaylight.yangtools.yang.binding.BindingCodec
-import org.opendaylight.yangtools.yang.binding.BindingDeserializer
-import org.opendaylight.yangtools.yang.binding.BindingMapping
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier
-import org.opendaylight.yangtools.yang.common.QName
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
-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.NotificationDefinition
-import org.opendaylight.yangtools.yang.model.api.SchemaNode
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition
-import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
-import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit
-import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition
-import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition
-import org.opendaylight.yangtools.yang.model.util.EnumerationType
-import org.opendaylight.yangtools.yang.model.util.ExtendedType
-import org.slf4j.LoggerFactory
-
-import static com.google.common.base.Preconditions.*
-import static javassist.Modifier.*
-import static org.opendaylight.yangtools.sal.binding.generator.impl.CodecMapping.*
-
-import static extension org.opendaylight.yangtools.sal.binding.generator.util.YangSchemaUtils.*
-
-class TransformerGenerator extends AbstractTransformerGenerator {
- private static val LOG = LoggerFactory.getLogger(TransformerGenerator)
-
- public static val STRING = Types.typeForClass(String);
- public static val BOOLEAN = Types.typeForClass(Boolean);
- public static val INTEGER = Types.typeForClass(Integer);
- public static val INSTANCE_IDENTIFIER = Types.typeForClass(InstanceIdentifier);
- //public static val DECIMAL = Types.typeForClass(Decimal);
- public static val LONG = Types.typeForClass(Long);
- public static val CLASS_TYPE = Types.typeForClass(Class);
-
- @Property
- var File classFileCapturePath;
-
- val CtClass BINDING_CODEC
- val CtClass ctQName
-
- val SourceCodeGeneratorFactory sourceCodeGeneratorFactory = new SourceCodeGeneratorFactory();
-
- public new(TypeResolver typeResolver, ClassPool pool) {
- super(typeResolver, pool)
-
- BINDING_CODEC = BindingCodec.asCtClass;
- ctQName = QName.asCtClass
- }
-
- override transformerForImpl(Class inputType) {
- return runOnClassLoader(inputType.classLoader) [ |
- val ret = getGeneratedClass(inputType)
- if (ret !== null) {
- listener.onClassProcessed(inputType);
- return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- }
- val ref = Types.typeForClass(inputType)
- val node = getSchemaNode(ref)
- createMapping(inputType, node, null)
- val typeSpecBuilder = getDefinition(ref)
- checkState(typeSpecBuilder !== null, "Could not find typedefinition for %s", inputType.name);
- val typeSpec = typeSpecBuilder.toInstance();
- val newret = generateTransformerFor(inputType, typeSpec, node);
- listener.onClassProcessed(inputType);
- return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- ]
- }
-
- def Class<? extends BindingCodec<Map<QName, Object>, Object>> transformerFor(Class<?> inputType, DataSchemaNode node) {
- return runOnClassLoader(inputType.classLoader) [ |
- createMapping(inputType, node, null)
- val ret = getGeneratedClass(inputType)
- if (ret !== null) {
- listener.onClassProcessed(inputType);
- return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- }
- val ref = Types.typeForClass(inputType)
- var typeSpecBuilder = getDefinition(ref)
- if (typeSpecBuilder == null) {
- typeSpecBuilder = getTypeBuilder(node.path);
- }
-
- checkState(typeSpecBuilder !== null, "Could not find TypeDefinition for %s, $s", inputType.name, node);
- val typeSpec = typeSpecBuilder.toInstance();
- val newret = generateTransformerFor(inputType, typeSpec, node);
- listener.onClassProcessed(inputType);
- return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- ]
- }
-
- override augmentationTransformerForImpl(Class inputType) {
- return runOnClassLoader(inputType.classLoader) [ |
-
- val ret = getGeneratedClass(inputType)
- if (ret !== null) {
- return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- }
- val ref = Types.typeForClass(inputType)
- val node = getAugmentation(ref)
- val typeSpecBuilder = getDefinition(ref)
- val typeSpec = typeSpecBuilder.toInstance();
- //mappingForNodes(node.childNodes, typeSpec.allProperties, bindingId)
- val newret = generateAugmentationTransformerFor(inputType, typeSpec, node);
- listener.onClassProcessed(inputType);
- return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- ]
- }
-
- override caseCodecForImpl(Class inputType, ChoiceCaseNode node) {
- return runOnClassLoader(inputType.classLoader) [ |
- createMapping(inputType, node, null)
- val ret = getGeneratedClass(inputType)
- if (ret !== null) {
- return ret as Class<? extends BindingCodec<Object, Object>>;
- }
- val ref = Types.typeForClass(inputType)
- val typeSpecBuilder = getDefinition(ref)
- val typeSpec = typeSpecBuilder.toInstance();
- val newret = generateCaseCodec(inputType, typeSpec, node);
- return newret as Class<? extends BindingCodec<Object, Object>>;
- ]
- }
-
- override keyTransformerForIdentifiableImpl(Class parentType) {
- return runOnClassLoader(parentType.classLoader) [ |
- val inputName = parentType.name + "Key";
- val inputType = loadClass(inputName);
- val ret = getGeneratedClass(inputType)
- if (ret !== null) {
- return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- }
- val ref = Types.typeForClass(parentType)
- val node = getSchemaNode(ref) as ListSchemaNode
- val typeSpecBuilder = getDefinition(ref)
- val typeSpec = typeSpecBuilder.identifierDefinition;
- val newret = generateKeyTransformerFor(inputType, typeSpec, node);
- return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- ]
- }
-
- private def void createMapping(Class<?> inputType, SchemaNode node, InstanceIdentifier<?> parentId) {
- var ClassLoader cl = inputType.classLoader
- if (cl === null) {
- cl = Thread.currentThread.contextClassLoader
- }
-
- val Supplier<?> sup = [ |
- if (!(node instanceof DataNodeContainer)) {
- return null
- }
- var InstanceIdentifier<?> bindingId = getBindingIdentifierByPath(node.path)
- if (bindingId != null) {
- return null
- }
- val ref = Types.typeForClass(inputType)
- var typeSpecBuilder = getDefinition(ref)
- if (typeSpecBuilder == null) {
- typeSpecBuilder = getTypeBuilder(node.path);
- }
- checkState(typeSpecBuilder !== null, "Could not find type definition for %s, $s", inputType.name, node);
- val typeSpec = typeSpecBuilder.toInstance();
- var InstanceIdentifier<?> parent
- if (parentId == null) {
- bindingId = InstanceIdentifier.create(inputType as Class)
- parent = bindingId
- putPathToBindingIdentifier(node.path, bindingId)
- } else {
- parent = putPathToBindingIdentifier(node.path, parentId, inputType)
- }
- val Map<String, Type> properties = typeSpec.allProperties
- if (node instanceof DataNodeContainer) {
- mappingForNodes((node as DataNodeContainer).childNodes, properties, parent)
- } else if (node instanceof ChoiceNode) {
- mappingForNodes((node as ChoiceNode).cases, properties, parent)
- }
- return null ]
- ClassLoaderUtils.withClassLoader(cl, sup)
- }
-
- private def void mappingForNodes(Collection<? extends DataSchemaNode> childNodes, Map<String, Type> properties,
- InstanceIdentifier<?> parent) {
- for (DataSchemaNode child : childNodes) {
- val signature = properties.getFor(child)
- if (signature != null) {
- val Type childType = signature.value
- var Class<?> childTypeClass = null;
- if (child instanceof ListSchemaNode && childType instanceof ParameterizedType) {
- childTypeClass = loadClass((childType as ParameterizedType).actualTypeArguments.get(0))
- } else {
- childTypeClass = loadClass(childType)
- }
- createMapping(childTypeClass, child, parent)
- }
- }
- }
-
- def getIdentifierDefinition(GeneratedTypeBuilder builder) {
- val inst = builder.toInstance
- val keyMethod = inst.methodDefinitions.findFirst[name == "getKey"]
- return keyMethod.returnType as GeneratedTransferObject
- }
-
- override keyTransformerForIdentifierImpl(Class inputType) {
- return runOnClassLoader(inputType.classLoader) [ |
- val ret = getGeneratedClass(inputType)
- if (ret !== null) {
- return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- }
- val ref = Types.typeForClass(inputType)
- val node = getSchemaNode(ref) as ListSchemaNode
- val typeSpecBuilder = getDefinition(ref)
- val typeSpec = typeSpecBuilder.toInstance();
- val newret = generateKeyTransformerFor(inputType, typeSpec, node);
- return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- ]
- }
-
- private def Class<?> keyTransformerFor(Class<?> inputType, GeneratedType type, ListSchemaNode schema) {
- return runOnClassLoader(inputType.classLoader) [ |
- val transformer = getGeneratedClass(inputType)
- if (transformer != null) {
- return transformer;
- }
- val newret = generateKeyTransformerFor(inputType, type, schema);
- return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- ]
- }
-
- private def Class<?> getGeneratedClass(Class<? extends Object> cls) {
-
- try {
- return loadClass(cls.codecClassName)
- } catch (ClassNotFoundException e) {
- return null;
- }
- }
-
- private def Class<?> keyTransformer(GeneratedType type, ListSchemaNode node) {
- val cls = loadClass(type.resolvedName + "Key");
- keyTransformerFor(cls, type, node);
- }
-
- private def serializer(Type type, DataSchemaNode node) {
- val cls = loadClass(type.resolvedName);
- transformerFor(cls, node);
- }
-
- private def Class<?> valueSerializer(GeneratedTransferObject type, TypeDefinition<?> typeDefinition) {
- val cls = loadClass(type.resolvedName);
- val transformer = cls.generatedClass;
- if (transformer !== null) {
- return transformer;
- }
- var baseType = typeDefinition;
- while (baseType.baseType != null) {
- baseType = baseType.baseType;
- }
- val finalType = baseType;
- return runOnClassLoader(cls.classLoader) [ |
- val valueTransformer = generateValueTransformer(cls, type, finalType);
- return valueTransformer;
- ]
- }
-
- private def Class<?> valueSerializer(Enumeration type, TypeDefinition<?> typeDefinition) {
- val cls = loadClass(type.resolvedName);
- val transformer = cls.generatedClass;
- if (transformer !== null) {
- return transformer;
- }
-
- return runOnClassLoader(cls.classLoader) [ |
- val valueTransformer = generateValueTransformer(cls, type, typeDefinition);
- return valueTransformer;
- ]
- }
-
- private def generateKeyTransformerFor(Class<? extends Object> inputType, GeneratedType typeSpec, ListSchemaNode node) {
- try {
-
- val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
- //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
- val properties = typeSpec.allProperties;
- val ctCls = createClass(inputType.codecClassName) [
- //staticField(Map,"AUGMENTATION_SERIALIZERS");
- staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
- staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
- staticQNameField(node.QName, sourceGenerator);
- implementsType(BINDING_CODEC)
- method(Object, "toDomStatic", #[QName, Object]) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- «QName.name» _resultName;
- if($1 != null) {
- _resultName = «QName.name».create($1,QNAME.getLocalName());
- } else {
- _resultName = QNAME;
- }
- java.util.List _childNodes = new java.util.ArrayList();
- «inputType.resolvedName» value = («inputType.name») $2;
- «FOR key : node.keyDefinition»
- «val propertyName = key.getterName»
- «val keyDef = node.getDataChildByName(key)»
- «val property = properties.get(propertyName)»
- «serializeProperty(keyDef, property, propertyName)»;
- «ENDFOR»
- return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
- }
- '''
- setBodyChecked(body, sourceGenerator)
- ]
- method(Object, "fromDomStatic", #[QName, Object]) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- if($2 == null){
- return null;
- }
- «QName.name» _localQName = $1;
- java.util.Map _compositeNode = (java.util.Map) $2;
- boolean _is_empty = true;
- «FOR key : node.keyDefinition»
- «val propertyName = key.getterName»
- «val keyDef = node.getDataChildByName(key)»
- «val property = properties.get(propertyName)»
- «deserializeProperty(keyDef, property, propertyName)»;
- «ENDFOR»
- «inputType.resolvedName» _value = new «inputType.name»(«node.keyDefinition.
- keyConstructorList»);
- return _value;
- }
- '''
- setBodyChecked(body, sourceGenerator)
- ]
- method(Object, "serialize", Object) [
- val body = '''
- {
- java.util.Map.Entry _input = (java.util.Map.Entry) $1;
- «QName.name» _localQName = («QName.name») _input.getKey();
- «inputType.name» _keyValue = («inputType.name») _input.getValue();
- return toDomStatic(_localQName,_keyValue);
- }
- '''
- setBodyChecked(body, sourceGenerator)
- ]
- method(Object, "deserialize", Object) [
- val body = '''
- {
- «QName.name» _qname = QNAME;
- if($1 instanceof java.util.Map.Entry) {
- _qname = («QName.name») ((java.util.Map.Entry) $1).getKey();
- }
- return fromDomStatic(_qname,$1);
- }
- '''
- setBodyChecked(body, sourceGenerator)
- ]
- ]
- val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
- sourceGenerator.outputGeneratedSource( ctCls )
- LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
- return ret as Class<? extends BindingCodec<Map<QName,Object>, ?>>;
- } catch (Exception e) {
- processException(inputType, e);
- return null;
- }
- }
-
- private def Class<? extends BindingCodec<Object, Object>> generateCaseCodec(Class<?> inputType, GeneratedType type,
- ChoiceCaseNode node) {
- try {
- val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
- //log.info("Generating DOM Codec for {} with {}, TCCL is: {}", inputType, inputType.classLoader,Thread.currentThread.contextClassLoader)
- val ctCls = createClass(type.codecClassName) [
- //staticField(Map,"AUGMENTATION_SERIALIZERS");
- implementsType(BINDING_CODEC)
- staticQNameField(node.QName, sourceGenerator);
- staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
- staticField(it, AUGMENTATION_CODEC, BindingCodec, sourceGenerator)
- staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
- method(Object, "toDomStatic", #[QName, Object]) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- «QName.name» _resultName = «QName.name».create($1,QNAME.getLocalName());
- java.util.List _childNodes = new java.util.ArrayList();
- «type.resolvedName» value = («type.resolvedName») $2;
- «transformDataContainerBody(type, type.allProperties, node)»
- return ($r) _childNodes;
- }
- '''
- setBodyChecked( body, sourceGenerator)
- ]
- method(Object, "serialize", Object) [
- val body = '''
- {
- java.util.Map.Entry _input = (java.util.Map.Entry) $1;
- «QName.name» _localName = QNAME;
- if(_input.getKey() != null) {
- _localName = («QName.name») _input.getKey();
- }
- return toDomStatic(_localName,_input.getValue());
- }
- '''
- setBodyChecked( body, sourceGenerator)
- ]
- method(Object, "fromDomStatic", #[QName, Object, InstanceIdentifier]) [
- modifiers = PUBLIC + FINAL + STATIC
- setBodyChecked( deserializeBody(type, node, getBindingIdentifierByPath(node.path)),
- sourceGenerator )
- ]
- method(Object, "deserialize", #[Object, InstanceIdentifier]) [
- val body = '''
- {
- //System.out.println("«type.name»#deserialize: " +$1);
- java.util.Map.Entry _input = (java.util.Map.Entry) $1;
- return fromDomStatic((«QName.name»)_input.getKey(),_input.getValue(),$2);
- }
- '''
- setBodyChecked( body, sourceGenerator)
- ]
- ]
-
- val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain) as Class<? extends BindingCodec<Object, Object>>
- sourceGenerator.outputGeneratedSource( ctCls )
- listener?.onDataContainerCodecCreated(inputType, ret);
- LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
- return ret;
- } catch (Exception e) {
- processException(inputType, e);
- return null;
- }
- }
-
- private def dispatch Class<? extends BindingCodec<Map<QName, Object>, Object>> generateTransformerFor(
- Class<?> inputType, GeneratedType typeSpec, SchemaNode node) {
- try {
-
- val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
- //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
- val ctCls = createClass(typeSpec.codecClassName) [
-
- //staticField(Map,"AUGMENTATION_SERIALIZERS");
- staticQNameField(node.QName, sourceGenerator);
- staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
- staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
- staticField(it, AUGMENTATION_CODEC, BindingCodec, sourceGenerator)
- implementsType(BINDING_CODEC)
-
- method(Object, "toDomStatic", #[QName, Object]) [
- modifiers = PUBLIC + FINAL + STATIC
- setBodyChecked( serializeBodyFacade(typeSpec, node), sourceGenerator )
- ]
- method(Object, "serialize", Object) [
- val body = '''
- {
- java.util.Map.Entry _input = (java.util.Map.Entry) $1;
- «QName.name» _localName = QNAME;
- if(_input.getKey() != null) {
- _localName = («QName.name») _input.getKey();
- }
- return toDomStatic(_localName,_input.getValue());
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
-
- method(Object, "fromDomStatic", #[QName, Object, InstanceIdentifier]) [
- modifiers = PUBLIC + FINAL + STATIC
- setBodyChecked( deserializeBody(typeSpec, node, getBindingIdentifierByPath(node.path)),
- sourceGenerator )
- ]
-
- method(Object, "deserialize", #[Object, InstanceIdentifier]) [
- val body = '''
- {
- «QName.name» _qname = QNAME;
- if($1 instanceof java.util.Map.Entry) {
- _qname = («QName.name») ((java.util.Map.Entry) $1).getKey();
- }
- return fromDomStatic(_qname,$1,$2);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- ]
-
- val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain) as Class<? extends BindingCodec<Map<QName,Object>, Object>>
-
- sourceGenerator.outputGeneratedSource( ctCls )
-
- listener?.onDataContainerCodecCreated(inputType, ret);
- LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
- return ret;
- } catch (Exception e) {
- processException(inputType, e);
- return null;
- }
- }
-
- private def Class<? extends BindingCodec<Map<QName, Object>, Object>> generateAugmentationTransformerFor(
- Class<?> inputType, GeneratedType type, AugmentationSchema node) {
- try {
-
- val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
- //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
- val properties = type.allProperties
- val ctCls = createClass(type.codecClassName) [
- //staticField(Map,"AUGMENTATION_SERIALIZERS");
- staticQNameField(node.augmentationQName, sourceGenerator);
- staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
- staticField(it, AUGMENTATION_CODEC, BindingCodec, sourceGenerator)
- staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
- implementsType(BINDING_CODEC)
-
- method(Object, "toDomStatic", #[QName, Object]) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- ////System.out.println("Qname " + $1);
- ////System.out.println("Value " + $2);
- «QName.name» _resultName = «QName.name».create(QNAME,QNAME.getLocalName());
- java.util.List _childNodes = new java.util.ArrayList();
- «type.resolvedName» value = («type.resolvedName») $2;
- «FOR child : node.childNodes»
- «var signature = properties.getFor(child)»
- ////System.out.println("«signature.key»" + value.«signature.key»());
- «serializeProperty(child, signature.value, signature.key)»
- «ENDFOR»
- return ($r) _childNodes;
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "serialize", Object) [
- val body = '''
- {
- java.util.Map.Entry _input = (java.util.Map.Entry) $1;
- «QName.name» _localName = QNAME;
- if(_input.getKey() != null) {
- _localName = («QName.name») _input.getKey();
- }
- return toDomStatic(_localName,_input.getValue());
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
-
- method(Object, "fromDomStatic", #[QName, Object, InstanceIdentifier]) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- «QName.name» _localQName = QNAME;
-
- if($2 == null) {
- return null;
- }
- java.util.Map _compositeNode = (java.util.Map) $2;
- //System.out.println(_localQName + " " + _compositeNode);
- «type.builderName» _builder = new «type.builderName»();
- boolean _is_empty = true;
- «FOR child : node.childNodes»
- «val signature = properties.getFor(child)»
- «deserializeProperty(child, signature.value, signature.key)»
- _builder.«signature.key.toSetter»(«signature.key»);
- «ENDFOR»
- if(_is_empty) {
- return null;
- }
- return _builder.build();
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
-
- method(Object, "deserialize", #[Object, InstanceIdentifier]) [
- val body = '''
- {
- return fromDomStatic(QNAME,$1,$2);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- ]
-
- val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain) as Class<? extends BindingCodec<Map<QName,Object>, Object>>
- sourceGenerator.outputGeneratedSource( ctCls )
- listener?.onDataContainerCodecCreated(inputType, ret);
- return ret;
- } catch (Exception e) {
- processException(inputType, e);
- return null;
- }
- }
-
- private def dispatch Class<? extends BindingCodec<Map<QName, Object>, Object>> generateTransformerFor(
- Class<?> inputType, GeneratedType typeSpec, ChoiceNode node) {
- try {
-
- val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
- //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
- val ctCls = createClass(typeSpec.codecClassName) [
- //staticField(Map,"AUGMENTATION_SERIALIZERS");
- //staticQNameField(inputType);
- staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
- staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
- staticField(it, DISPATCH_CODEC, BindingCodec, sourceGenerator)
- //staticField(it,QNAME_TO_CASE_MAP,BindingCodec)
- implementsType(BINDING_CODEC)
- method(List, "toDomStatic", #[QName, Object]) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- if($2 == null) {
- return null;
- }
- if («DISPATCH_CODEC» == null) {
- throw new «IllegalStateException.name»("Implementation of codec was not initialized.");
- }
- java.util.Map.Entry _input = new «SimpleEntry.name»($1,$2);
- Object _ret = «DISPATCH_CODEC».serialize(_input);
- ////System.out.println("«typeSpec.name»#toDomStatic: " + _ret);
- return («List.name») _ret;
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "serialize", Object) [
- val body = '''
- {
- throw new «UnsupportedOperationException.name»("Direct invocation not supported.");
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "fromDomStatic", #[QName, Map, InstanceIdentifier]) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- if («DISPATCH_CODEC» == null) {
- throw new «IllegalStateException.name»("Implementation of codec was not initialized.");
- }
- return «DISPATCH_CODEC».deserialize($2,$3);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "deserialize", #[Object, InstanceIdentifier]) [
- val body = '''
- {
- throw new «UnsupportedOperationException.name»("Direct invocation not supported.");
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- ]
-
- val rawRet = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
- sourceGenerator.outputGeneratedSource( ctCls )
- val ret = rawRet as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- listener?.onChoiceCodecCreated(inputType, ret, node);
- LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
- return ret;
- } catch (Exception e) {
- processException(inputType, e);
- return null;
- }
- }
-
- private def keyConstructorList(List<QName> qnames) {
- val names = new TreeSet<String>()
- for (name : qnames) {
- val fieldName = name.getterName;
- names.add(fieldName);
- }
- return Joiner.on(",").join(names);
- }
-
- private def serializeBodyFacade(GeneratedType type, SchemaNode node) {
- val ret = serializeBody(type, node);
- return ret;
- }
-
- private def String deserializeBody(GeneratedType type, SchemaNode node, InstanceIdentifier<?> bindingId) {
- val ret = deserializeBodyImpl(type, node, bindingId);
- return ret;
- }
-
- private def deserializeKey(GeneratedType type, ListSchemaNode node) {
- if (node.keyDefinition != null && !node.keyDefinition.empty) {
- return '''
- «type.resolvedName»Key getKey = («type.resolvedName»Key) «keyTransformer(type, node).canonicalName».fromDomStatic(_localQName,_compositeNode);
- _builder.setKey(getKey);
- ''';
- }
- }
-
- private def String deserializeBodyWithAugmentations(GeneratedType type, DataNodeContainer node, InstanceIdentifier<?> bindingId) '''
- {
- «QName.name» _localQName = «QName.name».create($1,QNAME.getLocalName());
- if($2 == null) {
- return null;
- }
- java.util.Map _compositeNode = (java.util.Map) $2;
- //System.out.println(_localQName + " " + _compositeNode);
- «type.builderName» _builder = new «type.builderName»();
- «deserializeDataNodeContainerBody(type, node, bindingId)»
- «type.deserializeAugmentations»
- return _builder.build();
- }
- '''
-
- private def dispatch String deserializeBodyImpl(GeneratedType type, SchemaNode node, InstanceIdentifier<?> bindingId) '''
- {
- «QName.name» _localQName = «QName.name».create($1,QNAME.getLocalName());
-
- if($2 == null) {
- return null;
- }
- java.util.Map _compositeNode = (java.util.Map) $2;
- «type.builderName» _builder = new «type.builderName»();
- return _builder.build();
- }
- '''
-
- private def dispatch String deserializeBodyImpl(GeneratedType type, ListSchemaNode node, InstanceIdentifier<?> bindingId) '''
- {
- «QName.name» _localQName = «QName.name».create($1,QNAME.getLocalName());
- if($2 == null) {
- return null;
- }
- java.util.Map _compositeNode = (java.util.Map) $2;
- //System.out.println(_localQName + " " + _compositeNode);
- «type.builderName» _builder = new «type.builderName»();
- «deserializeKey(type, node)»
- «deserializeDataNodeContainerBody(type, node, bindingId)»
- «type.deserializeAugmentations»
- return _builder.build();
- }
- '''
-
- private def dispatch String deserializeBodyImpl(GeneratedType type, ContainerSchemaNode node, InstanceIdentifier<?> bindingId) {
- return deserializeBodyWithAugmentations(type, node, bindingId);
- }
-
- private def dispatch String deserializeBodyImpl(GeneratedType type, NotificationDefinition node, InstanceIdentifier<?> bindingId) {
- return deserializeBodyWithAugmentations(type, node, bindingId);
- }
-
- private def dispatch String deserializeBodyImpl(GeneratedType type, ChoiceCaseNode node, InstanceIdentifier<?> bindingId) {
- return deserializeBodyWithAugmentations(type, node, bindingId);
- }
-
- private def deserializeDataNodeContainerBody(GeneratedType type, DataNodeContainer node, InstanceIdentifier<?> bindingId) {
- deserializeNodeContainerBodyImpl(type, type.allProperties, node, bindingId);
- }
-
- private def deserializeNodeContainerBodyImpl(GeneratedType type, HashMap<String, Type> properties,
- DataNodeContainer node, InstanceIdentifier<?> bindingId) {
- val ret = '''
- boolean _is_empty = true;
- «FOR child : node.childNodes»
- «val signature = properties.getFor(child)»
- «IF signature !== null»
- «deserializeProperty(child, signature.value, signature.key)»
- _builder.«signature.key.toSetter»(«signature.key»);
- «ENDIF»
- «ENDFOR»
- '''
- return ret;
- }
-
- def deserializeAugmentations(GeneratedType type) '''
- «InstanceIdentifier.resolvedName» iid = $3.builder().child(«type.resolvedName».class).build();
- java.util.Map _augmentation = (java.util.Map) «AUGMENTATION_CODEC».deserialize(_compositeNode,$3);
- if(_augmentation != null) {
- «Iterator.name» _entries = _augmentation.entrySet().iterator();
- while(_entries.hasNext()) {
- java.util.Map.Entry _entry = (java.util.Map.Entry) _entries.next();
- ////System.out.println("Aug. key:" + _entry.getKey());
- Class _type = (Class) _entry.getKey();
- «Augmentation.resolvedName» _value = («Augmentation.name») _entry.getValue();
- if(_value != null) {
- _builder.addAugmentation(_type,_value);
- }
- }
- }
- '''
-
- private def dispatch CharSequence deserializeProperty(ListSchemaNode schema, ParameterizedType type,
- String propertyName) '''
- java.util.List _dom_«propertyName» = _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.
- localName»"));
- ////System.out.println("«propertyName»#deCode"+_dom_«propertyName»);
- java.util.List «propertyName» = new java.util.ArrayList();
- if(_dom_«propertyName» != null) {
- java.util.List _serialized = new java.util.ArrayList();
- java.util.Iterator _iterator = _dom_«propertyName».iterator();
- boolean _hasNext = _iterator.hasNext();
- while(_hasNext) {
- Object _listItem = _iterator.next();
- _is_empty = false;
- ////System.out.println(" item" + _listItem);
- «val param = type.actualTypeArguments.get(0)»
- «InstanceIdentifier.resolvedName» iid = $3.builder().child(«param.resolvedName».class).build();
- Object _value = «type.actualTypeArguments.get(0).serializer(schema).resolvedName».fromDomStatic(_localQName,_listItem,iid);
- ////System.out.println(" value" + _value);
- «propertyName».add(_value);
- _hasNext = _iterator.hasNext();
- }
- }
-
- ////System.out.println(" list" + «propertyName»);
- '''
-
- private def dispatch CharSequence deserializeProperty(LeafListSchemaNode schema, ParameterizedType type,
- String propertyName) '''
- java.util.List _dom_«propertyName» = _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.
- localName»"));
- java.util.List «propertyName» = new java.util.ArrayList();
- if(_dom_«propertyName» != null) {
- java.util.List _serialized = new java.util.ArrayList();
- java.util.Iterator _iterator = _dom_«propertyName».iterator();
- boolean _hasNext = _iterator.hasNext();
- while(_hasNext) {
- _is_empty = false;
- Object _listItem = _iterator.next();
- if(_listItem instanceof java.util.Map.Entry) {
- Object _innerValue = ((java.util.Map.Entry) _listItem).getValue();
- Object _value = «deserializeValue(type.actualTypeArguments.get(0), "_innerValue", schema.type)»;
- «propertyName».add(_value);
- }
- _hasNext = _iterator.hasNext();
- }
- }
- '''
-
- private def dispatch CharSequence deserializeProperty(LeafSchemaNode schema, Type type, String propertyName) '''
- java.util.List _dom_«propertyName»_list =
- _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.localName»"));
- «type.resolvedName» «propertyName» = null;
- if(_dom_«propertyName»_list != null && _dom_«propertyName»_list.size() > 0) {
- _is_empty = false;
- java.util.Map.Entry _dom_«propertyName» = (java.util.Map.Entry) _dom_«propertyName»_list.get(0);
- Object _inner_value = _dom_«propertyName».getValue();
- «propertyName» = «deserializeValue(type, "_inner_value", schema.type)»;
- }
- '''
-
- private def dispatch CharSequence deserializeProperty(ContainerSchemaNode schema, Type type,
- String propertyName) '''
- java.util.List _dom_«propertyName»_list =
- _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.localName»"));
- «type.resolvedName» «propertyName» = null;
- if(_dom_«propertyName»_list != null && _dom_«propertyName»_list.size() > 0) {
- _is_empty = false;
- java.util.Map _dom_«propertyName» = (java.util.Map) _dom_«propertyName»_list.get(0);
- «InstanceIdentifier.resolvedName» iid = $3.builder().child(«type.resolvedName».class).build();
- «propertyName» = «type.serializer(schema).resolvedName».fromDomStatic(_localQName,_dom_«propertyName»,iid);
- }
- '''
-
- private def dispatch CharSequence deserializeProperty(ChoiceNode schema, Type type, String propertyName) '''
- «type.resolvedName» «propertyName» = «type.serializer(schema).resolvedName».fromDomStatic(_localQName,_compositeNode,$3);
- if(«propertyName» != null) {
- _is_empty = false;
- }
- '''
-
- private def dispatch String deserializeValue(GeneratedTransferObject type, String domParameter,
- TypeDefinition<?> typeDefinition) '''
- («type.resolvedName») «type.valueSerializer(typeDefinition).resolvedName».fromDomValue(«domParameter»)
- '''
-
- private def dispatch String deserializeValue(Enumeration type, String domParameter, TypeDefinition<?> typeDefinition) '''
- («type.resolvedName») «type.valueSerializer(typeDefinition).resolvedName».fromDomValue(«domParameter»)
- '''
-
- private def dispatch String deserializeValue(Type type, String domParameter, TypeDefinition<?> typeDef) {
- if (INSTANCE_IDENTIFIER.equals(type)) {
- return '''(«InstanceIdentifier.name») «INSTANCE_IDENTIFIER_CODEC».deserialize(«domParameter»)'''
- } else if (CLASS_TYPE.equals(type)) {
- return '''(«Class.name») «IDENTITYREF_CODEC».deserialize(«domParameter»)'''
- } else if (typeDef!=null && typeDef instanceof EmptyTypeDefinition) {
- if(domParameter == null) {
- return ''' Boolean.FALSE '''
- } else {
- return ''' Boolean.TRUE '''
- }
- }
- return '''(«type.resolvedName») «domParameter»'''
- }
-
- private def dispatch Class<? extends BindingCodec<Map<QName, Object>, Object>> generateValueTransformer(
- Class<?> inputType, GeneratedTransferObject typeSpec, TypeDefinition<?> typeDef) {
- try {
-
- val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
- val returnType = typeSpec.valueReturnType;
- if (returnType == null) {
- val ctCls = createDummyImplementation(inputType, typeSpec, sourceGenerator);
- val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
- sourceGenerator.outputGeneratedSource( ctCls )
- return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- }
-
- val ctCls = createClass(typeSpec.codecClassName) [
- //staticField(Map,"AUGMENTATION_SERIALIZERS");
- if (inputType.isYangBindingAvailable) {
- implementsType(BINDING_CODEC)
- staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
- staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
- implementsType(BindingDeserializer.asCtClass)
- }
- method(Object, "toDomValue", Object) [
- modifiers = PUBLIC + FINAL + STATIC
- val ctSpec = typeSpec.asCtClass;
- val body = '''
- {
- ////System.out.println("«inputType.simpleName»#toDomValue: "+$1);
-
- if($1 == null) {
- return null;
- }
- «typeSpec.resolvedName» _encapsulatedValue = («typeSpec.resolvedName») $1;
- ////System.out.println("«inputType.simpleName»#toDomValue:Enc: "+_encapsulatedValue);
- «returnType.resolvedName» _value = _encapsulatedValue.getValue();
- ////System.out.println("«inputType.simpleName»#toDomValue:DeEnc: "+_value);
- Object _domValue = «serializeValue(returnType, "_value", null)»;
- return _domValue;
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "serialize", Object) [
- val body = '''
- {
- return toDomValue($1);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "fromDomValue", Object) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- ////System.out.println("«inputType.simpleName»#fromDomValue: "+$1);
-
- if($1 == null) {
- return null;
- }
- «returnType.resolvedName» _simpleValue = «deserializeValue(returnType, "$1", null)»;
- «typeSpec.resolvedName» _value = new «typeSpec.resolvedName»(_simpleValue);
- return _value;
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "deserialize", Object) [
- val body = '''
- {
- return fromDomValue($1);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- ]
-
- val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
- sourceGenerator.outputGeneratedSource( ctCls )
- LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
- return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- } catch (Exception e) {
- LOG.error("Cannot compile DOM Codec for {}", inputType, e);
- val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType);
- exception.addSuppressed(e);
- throw exception;
- }
- }
-
- private def dispatch Class<? extends BindingCodec<Map<QName, Object>, Object>> generateValueTransformer(
- Class<?> inputType, GeneratedTransferObject typeSpec, UnionTypeDefinition typeDef) {
- try {
- val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
- val ctCls = createClass(typeSpec.codecClassName) [
- val properties = typeSpec.allProperties;
- val getterToTypeDefinition = XtendHelper.getTypes(typeDef).toMap[type|type.QName.getterName];
- //staticField(Map,"AUGMENTATION_SERIALIZERS");
- if (inputType.isYangBindingAvailable) {
- implementsType(BINDING_CODEC)
- staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
- staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
- implementsType(BindingDeserializer.asCtClass)
- }
- method(Object, "toDomValue", Object) [
- modifiers = PUBLIC + FINAL + STATIC
- val ctSpec = inputType.asCtClass;
- val body = '''
- {
- ////System.out.println("«inputType.simpleName»#toDomValue: "+$1);
-
- if($1 == null) {
- return null;
- }
- «typeSpec.resolvedName» _value = («typeSpec.resolvedName») $1;
- «FOR property : properties.entrySet»
- «IF property.key != "getValue"»
- «property.value.resolvedName» «property.key» = («property.value.resolvedName») _value.«property.
- key»();
- if(«property.key» != null) {
- return «serializeValue(property.value, property.key,
- getterToTypeDefinition.get(property.key))»;
- }
- «ENDIF»
- «ENDFOR»
-
- return null;
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "serialize", Object) [
- val body = '''
- {
- return toDomValue($1);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "fromDomValue", Object) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- ////System.out.println("«inputType.simpleName»#fromDomValue: "+$1);
-
- if($1 == null) {
- return null;
- }
- if($1 instanceof String) {
- String _simpleValue = (String) $1;
- return new «typeSpec.resolvedName»(_simpleValue.toCharArray());
- }
- return null;
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "deserialize", Object) [
- val body = '''
- {
- return fromDomValue($1);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- ]
-
- val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
- sourceGenerator.outputGeneratedSource( ctCls )
- LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
- return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- } catch (Exception e) {
- LOG.error("Cannot compile DOM Codec for {}", inputType, e);
- val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType);
- exception.addSuppressed(e);
- throw exception;
- }
- }
-
- private def dispatch Class<? extends BindingCodec<Map<QName, Object>, Object>> generateValueTransformer(
- Class<?> inputType, GeneratedTransferObject typeSpec, BitsTypeDefinition typeDef) {
- try {
- val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
- val ctCls = createClass(typeSpec.codecClassName) [
- //staticField(Map,"AUGMENTATION_SERIALIZERS");
- if (inputType.isYangBindingAvailable) {
- implementsType(BINDING_CODEC)
- staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
- staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
- implementsType(BindingDeserializer.asCtClass)
- }
- method(Object, "toDomValue", Object) [
- modifiers = PUBLIC + FINAL + STATIC
- val ctSpec = typeSpec.asCtClass;
- val body = '''
- {
- ////System.out.println("«inputType.simpleName»#toDomValue: "+$1);
-
- if($1 == null) {
- return null;
- }
- «typeSpec.resolvedName» _encapsulatedValue = («typeSpec.resolvedName») $1;
- «HashSet.resolvedName» _value = new «HashSet.resolvedName»();
- //System.out.println("«inputType.simpleName»#toDomValue:Enc: "+_encapsulatedValue);
-
- «FOR bit : typeDef.bits»
- «val getter = bit.getterName()»
- if(Boolean.TRUE.equals(_encapsulatedValue.«getter»())) {
- _value.add("«bit.name»");
- }
- «ENDFOR»
- «Set.resolvedName» _domValue = «Collections.resolvedName».unmodifiableSet(_value);
- //System.out.println("«inputType.simpleName»#toDomValue:DeEnc: "+_domValue);
-
- return _domValue;
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "serialize", Object) [
- val body = '''
- {
- return toDomValue($1);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "fromDomValue", Object) [
- modifiers = PUBLIC + FINAL + STATIC
- val sortedBits = IterableExtensions.sort(typeDef.bits, [o1, o2|o1.propertyName.compareTo(o2.propertyName)])
- val body = '''
- {
- //System.out.println("«inputType.simpleName»#fromDomValue: "+$1);
-
- if($1 == null) {
- return null;
- }
- «Set.resolvedName» _domValue = («Set.resolvedName») $1;
- «FOR bit : sortedBits»
- Boolean «bit.propertyName» = Boolean.valueOf(_domValue.contains("«bit.name»"));
- «ENDFOR»
-
- return new «inputType.resolvedName»(«FOR bit : sortedBits SEPARATOR ","»«bit.propertyName»«ENDFOR»);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "deserialize", Object) [
- val body = '''
- {
- return fromDomValue($1);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- ]
-
- val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
- sourceGenerator.outputGeneratedSource( ctCls )
- LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
- return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
- } catch (Exception e) {
- LOG.error("Cannot compile DOM Codec for {}", inputType, e);
- val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType);
- exception.addSuppressed(e);
- throw exception;
- }
- }
-
- def String getPropertyName(Bit bit) {
- '''_«BindingMapping.getPropertyName(bit.name)»'''
- }
-
- def String getterName(Bit bit) {
-
- val paramName = BindingMapping.getPropertyName(bit.name);
- return '''is«paramName.toFirstUpper»''';
- }
-
- def boolean isYangBindingAvailable(Class<?> class1) {
- try {
- val bindingCodecClass = class1.classLoader.loadClass(BINDING_CODEC.name);
- return bindingCodecClass !== null;
- } catch (ClassNotFoundException e) {
- return false;
- }
- }
-
- private def createDummyImplementation(Class<?> object, GeneratedTransferObject typeSpec,
- SourceCodeGenerator sourceGenerator ) {
- LOG.trace("Generating Dummy DOM Codec for {} with {}", object, object.classLoader)
- return createClass(typeSpec.codecClassName) [
- if (object.isYangBindingAvailable) {
- implementsType(BINDING_CODEC)
- staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
- staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
- implementsType(BindingDeserializer.asCtClass)
- }
- //implementsType(BindingDeserializer.asCtClass)
- method(Object, "toDomValue", Object) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- if($1 == null) {
- return null;
- }
- return $1.toString();
- }'''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "serialize", Object) [
- val body = '''
- {
- return toDomValue($1);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "fromDomValue", Object) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''return null;'''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "deserialize", Object) [
- val body = '''
- {
- return fromDomValue($1);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- ]
- }
-
- private def Type getValueReturnType(GeneratedTransferObject object) {
- for (prop : object.properties) {
- if (prop.name == "value") {
- return prop.returnType;
- }
- }
- if (object.superType != null) {
- return getValueReturnType(object.superType);
- }
- return null;
- }
-
- private def dispatch Class<?> generateValueTransformer(Class<?> inputType, Enumeration typeSpec, TypeDefinition<?> type) {
- var EnumerationType enumSchemaType
- if (type instanceof EnumerationType) {
- enumSchemaType = type as EnumerationType
- } else {
- val typeRef = new ReferencedTypeImpl(typeSpec.packageName, typeSpec.name);
- val schema = getSchemaNode(typeRef) as ExtendedType;
- enumSchemaType = schema.baseType as EnumerationType;
- }
- val enumSchema = enumSchemaType;
- try {
- val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
- //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
- val ctCls = createClass(typeSpec.codecClassName) [
- //staticField(Map,"AUGMENTATION_SERIALIZERS");
- //implementsType(BINDING_CODEC)
- method(Object, "toDomValue", Object) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- if($1 == null) {
- return null;
- }
- «typeSpec.resolvedName» _value = («typeSpec.resolvedName») $1;
- «FOR en : enumSchema.values»
- if(«typeSpec.resolvedName».«BindingMapping.getClassName(en.name)».equals(_value)) {
- return "«en.name»";
- }
- «ENDFOR»
- return null;
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "serialize", Object) [
- val body = '''
- {
- return toDomValue($1);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "fromDomValue", Object) [
- modifiers = PUBLIC + FINAL + STATIC
- val body = '''
- {
- if($1 == null) {
- return null;
- }
- String _value = (String) $1;
- «FOR en : enumSchema.values»
- if("«en.name»".equals(_value)) {
- return «typeSpec.resolvedName».«BindingMapping.getClassName(en.name)»;
- }
- «ENDFOR»
- return null;
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- method(Object, "deserialize", Object) [
- val body = '''
- {
- return fromDomValue($1);
- }
- '''
- setBodyChecked( body, sourceGenerator )
- ]
- ]
-
- val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
- sourceGenerator.outputGeneratedSource( ctCls )
- LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
- return ret;
- } catch (CodeGenerationException e) {
- throw new CodeGenerationException("Cannot compile Transformator for " + inputType, e);
- } catch (Exception e) {
- LOG.error("Cannot compile DOM Codec for {}", inputType, e);
- val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType);
- exception.addSuppressed(e);
- throw exception;
- }
-
- }
-
- def Class<?> toClassImpl(CtClass newClass, ClassLoader loader, ProtectionDomain domain) {
- val cls = newClass.toClass(loader, domain);
- if (classFileCapturePath !== null) {
- newClass.writeFile(classFileCapturePath.absolutePath);
- }
- listener?.onCodecCreated(cls);
- return cls;
- }
-
- def debugWriteClass(CtClass class1) {
- val path = class1.name.replace(".", "/") + ".class"
-
- val captureFile = new File(classFileCapturePath, path);
- captureFile.createNewFile
-
- }
-
- /**
- * Default catch all
- *
- **/
- private def dispatch CharSequence deserializeProperty(DataSchemaNode container, Type type, String propertyName) '''
- «type.resolvedName» «propertyName» = null;
- '''
-
- private def dispatch CharSequence deserializeProperty(DataSchemaNode container, GeneratedTypeBuilder type,
- String propertyName) {
- _deserializeProperty(container, type.toInstance, propertyName)
- }
-
- static def toSetter(String it) {
-
- if (startsWith("is")) {
- return "set" + substring(2);
- } else if (startsWith("get")) {
- return "set" + substring(3);
- }
- return "set" + it;
- }
-
- /*
- private def dispatch CharSequence deserializeProperty(DataSchemaNode container,GeneratedType type, String propertyName) '''
- «type.resolvedName» «propertyName» = value.«propertyName»();
- if(«propertyName» != null) {
- Object domValue = «type.serializer».toDomStatic(QNAME,«propertyName»);
- _childNodes.add(domValue);
- }
- '''
- */
- private def getBuilderName(GeneratedType type) '''«type.resolvedName»Builder'''
-
- private def staticQNameField(CtClass it, QName node, SourceCodeGenerator sourceGenerator) {
- val field = new CtField(ctQName, "QNAME", it);
- field.modifiers = PUBLIC + FINAL + STATIC;
- val code = '''«QName.asCtClass.name».cachedReference(«QName.asCtClass.name».create("«node.namespace»","«node.formattedRevision»","«node.localName»"))'''
- addField(field, code )
-
- sourceGenerator.appendField( field, code );
- }
-
- private def String serializeBodyImpl(GeneratedType type, DataNodeContainer nodeContainer) '''
- {
- «QName.name» _resultName = «QName.name».create($1,QNAME.getLocalName());
- java.util.List _childNodes = new java.util.ArrayList();
- «type.resolvedName» value = («type.resolvedName») $2;
- «transformDataContainerBody(type, type.allProperties, nodeContainer)»
- «serializeAugmentations»
- return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
- }
- '''
-
- private def dispatch String serializeBody(GeneratedType type, ListSchemaNode node) {
- return serializeBodyImpl(type, node);
- }
-
- private def dispatch String serializeBody(GeneratedType type, NotificationDefinition node) {
- return serializeBodyImpl(type, node);
- }
-
- private def dispatch String serializeBody(GeneratedType type, ContainerSchemaNode node) {
- return serializeBodyImpl(type, node);
- }
-
- private def dispatch String serializeBody(GeneratedType type, ChoiceCaseNode node) {
- return serializeBodyImpl(type, node);
- }
-
- private def dispatch String serializeBody(GeneratedType type, SchemaNode node) '''
- {
- «QName.name» _resultName = «QName.name».create($1,QNAME.getLocalName());
- java.util.List _childNodes = new java.util.ArrayList();
- «type.resolvedName» value = («type.resolvedName») $2;
- return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
- }
- '''
-
- private def transformDataContainerBody(Type type, Map<String, Type> properties, DataNodeContainer node) {
- val ret = '''
- «FOR child : node.childNodes»
- «val signature = properties.getFor(child)»
- «IF signature !== null»
- ////System.out.println("«type.name»#«signature.key»" + value.«signature.key»());
- «serializeProperty(child, signature.value, signature.key)»
- «ENDIF»
- «ENDFOR»
- '''
- return ret;
- }
-
- private static def serializeAugmentations() '''
- java.util.List _augmentations = (java.util.List) «AUGMENTATION_CODEC».serialize(value);
- if(_augmentations != null) {
- _childNodes.addAll(_augmentations);
- }
- '''
-
- private static def Entry<String, Type> getFor(Map<String, Type> map, DataSchemaNode node) {
- var sig = map.get(node.getterName);
- if (sig != null) {
- return new SimpleEntry(node.getterName, sig);
- }
- sig = map.get(node.booleanGetterName);
- if (sig != null) {
- return new SimpleEntry(node.booleanGetterName, map.get(node.booleanGetterName));
- }
- return null;
- }
-
- private static def String getBooleanGetterName(DataSchemaNode node) {
- return "is" + BindingMapping.getPropertyName(node.QName.localName).toFirstUpper;
- }
-
- private static def String getGetterName(DataSchemaNode node) {
- return "get" + BindingMapping.getPropertyName(node.QName.localName).toFirstUpper;
- }
-
- private static def String getGetterName(QName node) {
- return "get" + BindingMapping.getPropertyName(node.localName).toFirstUpper;
- }
-
- private def dispatch CharSequence serializeProperty(ListSchemaNode schema, ParameterizedType type,
- String propertyName) '''
- «type.resolvedName» «propertyName» = value.«propertyName»();
- ////System.out.println("«propertyName»:" + «propertyName»);
- if(«propertyName» != null) {
- java.util.Iterator _iterator = «propertyName».iterator();
- boolean _hasNext = _iterator.hasNext();
- while(_hasNext) {
- Object _listItem = _iterator.next();
- Object _domValue = «type.actualTypeArguments.get(0).serializer(schema).resolvedName».toDomStatic(_resultName,_listItem);
- _childNodes.add(_domValue);
- _hasNext = _iterator.hasNext();
- }
- }
- '''
-
- private def dispatch CharSequence serializeProperty(LeafSchemaNode schema, Type type, String propertyName) '''
- «type.resolvedName» «propertyName» = value.«propertyName»();
-
- if(«propertyName» != null) {
- «QName.name» _qname = «QName.name».create(_resultName,"«schema.QName.localName»");
- Object _propValue = «serializeValue(type, propertyName, schema.type)»;
- if(_propValue != null) {
- Object _domValue = java.util.Collections.singletonMap(_qname,_propValue);
- _childNodes.add(_domValue);
- }
- }
- '''
-
- private def dispatch serializeValue(GeneratedTransferObject type, String parameter, TypeDefinition<?> typeDefinition) {
- '''«type.valueSerializer(typeDefinition).resolvedName».toDomValue(«parameter»)'''
- }
-
- private def dispatch serializeValue(Enumeration type, String parameter, TypeDefinition<?> typeDefinition) {
- '''«type.valueSerializer(typeDefinition).resolvedName».toDomValue(«parameter»)'''
- }
-
- private def dispatch serializeValue(Type type, String parameter, EmptyTypeDefinition typeDefinition) {
- '''(«parameter».booleanValue() ? "" : null)'''
- }
-
- private def dispatch serializeValue(Type signature, String property, TypeDefinition<?> typeDefinition) {
- serializeValue(signature,property)
- }
-
- private def dispatch serializeValue(Type signature, String property, Void typeDefinition) {
- serializeValue(signature,property)
- }
-
- private def dispatch serializeValue(Type signature, String property) {
- if (INSTANCE_IDENTIFIER == signature) {
- return '''«INSTANCE_IDENTIFIER_CODEC».serialize(«property»)'''
- } else if (CLASS_TYPE.equals(signature)) {
- return '''(«QName.resolvedName») «IDENTITYREF_CODEC».serialize(«property»)'''
- }
- if ("char[]" == signature.name) {
- return '''new String(«property»)''';
- }
- return '''«property»''';
- }
-
- private def dispatch CharSequence serializeProperty(LeafListSchemaNode schema, ParameterizedType type,
- String propertyName) '''
- «type.resolvedName» «propertyName» = value.«propertyName»();
- if(«propertyName» != null) {
- «QName.name» _qname = «QName.name».create(_resultName,"«schema.QName.localName»");
- java.util.Iterator _iterator = «propertyName».iterator();
- boolean _hasNext = _iterator.hasNext();
- while(_hasNext) {
- Object _listItem = _iterator.next();
- Object _propValue = «serializeValue(type.actualTypeArguments.get(0), "_listItem", schema.type)»;
- Object _domValue = java.util.Collections.singletonMap(_qname,_propValue);
- _childNodes.add(_domValue);
- _hasNext = _iterator.hasNext();
- }
- }
- '''
-
- private def dispatch CharSequence serializeProperty(ChoiceNode container, GeneratedType type,
- String propertyName) '''
- «type.resolvedName» «propertyName» = value.«propertyName»();
- if(«propertyName» != null) {
- java.util.List domValue = «type.serializer(container).resolvedName».toDomStatic(_resultName,«propertyName»);
- _childNodes.addAll(domValue);
- }
- '''
-
- /**
- * Default catch all
- *
- **/
- private def dispatch CharSequence serializeProperty(DataSchemaNode container, Type type, String propertyName) '''
- «type.resolvedName» «propertyName» = value.«propertyName»();
- if(«propertyName» != null) {
- Object domValue = «propertyName»;
- _childNodes.add(domValue);
- }
- '''
-
- private def dispatch CharSequence serializeProperty(DataSchemaNode container, GeneratedTypeBuilder type,
- String propertyName) {
- serializeProperty(container, type.toInstance, propertyName)
- }
-
- private def dispatch CharSequence serializeProperty(DataSchemaNode container, GeneratedType type,
- String propertyName) '''
- «type.resolvedName» «propertyName» = value.«propertyName»();
- if(«propertyName» != null) {
- Object domValue = «type.serializer(container).resolvedName».toDomStatic(_resultName,«propertyName»);
- _childNodes.add(domValue);
- }
- '''
-
- private def codecClassName(GeneratedType typeSpec) {
- return '''«typeSpec.resolvedName»$Broker$Codec$DOM'''
- }
-
- private def codecClassName(Class<?> typeSpec) {
- return '''«typeSpec.name»$Broker$Codec$DOM'''
- }
-
- private def HashMap<String, Type> getAllProperties(GeneratedType type) {
- val ret = new HashMap<String, Type>();
- type.collectAllProperties(ret);
- return ret;
- }
-
- private def dispatch void collectAllProperties(GeneratedType type, Map<String, Type> set) {
- for (definition : type.methodDefinitions) {
- set.put(definition.name, definition.returnType);
- }
- for (property : type.properties) {
- set.put(property.getterName, property.returnType);
- }
- for (parent : type.implements) {
- parent.collectAllProperties(set);
- }
- }
-
- def String getGetterName(GeneratedProperty property) {
- return "get" + property.name.toFirstUpper
- }
-
- private def dispatch void collectAllProperties(Type type, Map<String, Type> set) {
- // NOOP for generic type.
- }
-
- def String getResolvedName(Type type) {
- return type.asCtClass.name;
- }
-
- def String getResolvedName(Class<?> type) {
- return type.asCtClass.name;
- }
-
- def CtClass asCtClass(Type type) {
- val cls = loadClass(type.fullyQualifiedName)
- return cls.asCtClass;
- }
-
- private def dispatch processException(Class<?> inputType, CodeGenerationException e) {
- LOG.error("Cannot compile DOM Codec for {}. One of it's prerequisites was not generated.", inputType);
- throw e;
- }
-
- private def dispatch processException(Class<?> inputType, Exception e) {
- LOG.error("Cannot compile DOM Codec for {}", inputType, e);
- val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType, e);
- throw exception;
- }
-
- private def setBodyChecked(CtMethod method, String body, SourceCodeGenerator sourceGenerator ) {
- try {
- method.setBody(body);
-
- sourceGenerator.appendMethod( method, body );
- } catch (CannotCompileException e) {
- LOG.error("Cannot compile method: {}#{} {}, Reason: {} Body: {}", method.declaringClass, method.name,
- method.signature, e.message, body)
- throw e;
- }
- }
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import org.opendaylight.yangtools.sal.binding.model.api.Type;
-import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-
-/**
- * Internal interface exposed to TransformerGenerator
- */
-interface TypeResolver {
- AugmentationSchema getAugmentation(Type type);
- GeneratedTypeBuilder getDefinition(Type type);
- SchemaNode getSchemaNode(Type type);
- GeneratedTypeBuilder getTypeBuilder(SchemaPath path);
-}
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
import org.opendaylight.yangtools.yang.model.api.Deviation
'''
«IF schemaNode instanceof DataSchemaNode»
- «writeDataSchemaNode(schemaNode as DataSchemaNode)»
+ «writeDataSchemaNode(schemaNode)»
«ENDIF»
«IF schemaNode instanceof EnumTypeDefinition.EnumPair»
- «writeEnumPair(schemaNode as EnumTypeDefinition.EnumPair)»
+ «writeEnumPair(schemaNode)»
«ENDIF»
«IF schemaNode instanceof ExtensionDefinition»
- «writeExtension(schemaNode as ExtensionDefinition)»
+ «writeExtension(schemaNode)»
«ENDIF»
«IF schemaNode instanceof FeatureDefinition»
- «writeFeature(schemaNode as FeatureDefinition)»
+ «writeFeature(schemaNode)»
«ENDIF»
«IF schemaNode instanceof GroupingDefinition»
- «writeGroupingDef(schemaNode as GroupingDefinition)»
+ «writeGroupingDef(schemaNode)»
«ENDIF»
«IF schemaNode instanceof IdentitySchemaNode»
- «writeIdentity(schemaNode as IdentitySchemaNode)»
+ «writeIdentity(schemaNode)»
«ENDIF»
«IF schemaNode instanceof NotificationDefinition»
- «writeNotification(schemaNode as NotificationDefinition)»
+ «writeNotification(schemaNode)»
«ENDIF»
«IF schemaNode instanceof RpcDefinition»
- «writeRPC(schemaNode as RpcDefinition)»
+ «writeRPC(schemaNode)»
«ENDIF»
«IF schemaNode instanceof TypeDefinition<?>»
- «writeTypeDefinition(schemaNode as TypeDefinition<?>)»
+ «writeTypeDefinition(schemaNode)»
«ENDIF»
«IF schemaNode instanceof UnknownSchemaNode»
- «writeUnknownSchemaNode(schemaNode as UnknownSchemaNode)»
+ «writeUnknownSchemaNode(schemaNode)»
«ENDIF»
'''
}
'''
«FOR node : nodes»
«IF node instanceof NotificationDefinition»
- «writeNotification(node as NotificationDefinition)»
+ «writeNotification(node)»
«ELSEIF node instanceof RpcDefinition»
«writeRPC(node as RpcDefinition)»
«ENDIF»
'''
refine «path.pathFromRoot.last» {
«IF schemaNode instanceof DataSchemaNode»
- «writeDataSchemaNode(schemaNode as DataSchemaNode)»
+ «writeDataSchemaNode(schemaNode)»
«ENDIF»
}
'''
'''
}
- def static writeChoiceNode(ChoiceNode choiceNode) {
+ def static writeChoiceNode(ChoiceSchemaNode choiceNode) {
'''
choice «choiceNode.getQName.localName» {
«FOR child : choiceNode.cases»
def static CharSequence writeDataSchemaNode(DataSchemaNode child) {
'''
«IF child instanceof ContainerSchemaNode»
- «writeContSchemaNode(child as ContainerSchemaNode)»
+ «writeContSchemaNode(child)»
«ENDIF»
«IF child instanceof AnyXmlSchemaNode»
- «writeAnyXmlSchemaNode(child as AnyXmlSchemaNode)»
+ «writeAnyXmlSchemaNode(child)»
«ENDIF»
«IF child instanceof LeafSchemaNode»
- «writeLeafSchemaNode(child as LeafSchemaNode)»
+ «writeLeafSchemaNode(child)»
«ENDIF»
«IF child instanceof LeafListSchemaNode»
- «writeLeafListSchemaNode(child as LeafListSchemaNode)»
+ «writeLeafListSchemaNode(child)»
«ENDIF»
«IF child instanceof ChoiceCaseNode»
- «writeChoiceCaseNode(child as ChoiceCaseNode)»
+ «writeChoiceCaseNode(child)»
«ENDIF»
- «IF child instanceof ChoiceNode»
- «writeChoiceNode(child as ChoiceNode)»
+ «IF child instanceof ChoiceSchemaNode»
+ «writeChoiceNode(child)»
«ENDIF»
«IF child instanceof ListSchemaNode»
- «writeListSchemaNode(child as ListSchemaNode)»
+ «writeListSchemaNode(child)»
«ENDIF»
'''
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
\ No newline at end of file
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
* the given context.
* @throws IllegalArgumentException If supplied class does not represent case.
*/
- public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceNode schema, final Class<?> childClass) throws IllegalArgumentException {
+ public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
final DataSchemaNode origSchema = getSchemaDefinition(childClass);
Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "Supplied schema %s is not case.", origSchema);
public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
final Map<Type,Entry<Type,Type>> childToCase = new HashMap<>();;
- for (final ChoiceNode choice : FluentIterable.from(schema.getChildNodes()).filter(ChoiceNode.class)) {
- final ChoiceNode originalChoice = getOriginalSchema(choice);
+ for (final ChoiceSchemaNode choice : FluentIterable.from(schema.getChildNodes()).filter(ChoiceSchemaNode.class)) {
+ final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
final Type choiceType = referencedType(typeToDefiningSchema.inverse().get(originalChoice));
final Collection<Type> cases = choiceToCases.get(choiceType);
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
-
import com.google.common.base.Preconditions;
import java.net.URI;
import java.util.Date;
import javax.annotation.Nullable;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
final DataSchemaNode child = currentNode.getDataChildByName(currentArg);
if(child instanceof DataNodeContainer) {
currentNode = (DataNodeContainer) child;
- } else if (child instanceof ChoiceNode) {
+ } else if (child instanceof ChoiceSchemaNode) {
final QName caseQName = arguments.next();
Preconditions.checkArgument(arguments.hasNext(), "Path must not refer case only.");
- currentNode = ((ChoiceNode) child).getCaseNodeByName(caseQName);
+ currentNode = ((ChoiceSchemaNode) child).getCaseNodeByName(caseQName);
} else {
// Search in grouping
for( final GroupingDefinition grouping : currentNode.getGroupings()) {
*/
package org.opendaylight.yangtools.binding.generator.util;
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Splitter;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
+import com.google.common.collect.Iterables;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
+import javax.annotation.Nullable;
import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
public static final ConcreteType VOID = typeForClass(Void.class);
public static final ConcreteType BYTE_ARRAY = primitiveType("byte[]", null);
public static final ConcreteType CHAR_ARRAY = primitiveType("char[]", null);
+ private static final Splitter DOT_SPLITTER = Splitter.on('.');
/**
* It is not desirable to create instance of this class
return parameterizedTypeFor(augmentation, valueType);
}
+
+ public static @Nullable String getOuterClassName(final Type valueType) {
+ final String pkgName = valueType.getPackageName();
+ if(CharMatcher.JAVA_UPPER_CASE.indexIn(pkgName) >= 0) {
+ // It is inner class.
+ return Iterables.getLast(DOT_SPLITTER.split(pkgName));
+ }
+ return null;
+ }
+
/**
*
* Represents concrete JAVA type.
'''.toString
}
- protected def imports() '''
+ protected def imports() '''
«IF !importMap.empty»
«FOR entry : importMap.entrySet»
- «IF entry.value != fullyQualifiedName»
+ «IF !hasSamePackage(entry.value)»
import «entry.value».«entry.key»;
«ENDIF»
«ENDFOR»
'''
+ /**
+ * Checks if packages of generated type and imported type is the same
+ *
+ * @param importedTypePackageNam
+ * the package name of imported type
+ * @return true if the packages are the same false otherwise
+ */
+ final private def boolean hasSamePackage(String importedTypePackageName) {
+ return type.packageName.equals(importedTypePackageName);
+ }
+
protected abstract def CharSequence body();
// Helper patterns
/**
* Template method which generates the getter method for <code>field</code>
- *
- * @param field
+ *
+ * @param field
* generated property with data about field which is generated as the getter method
- * @return string with the getter method source code in JAVA format
+ * @return string with the getter method source code in JAVA format
*/
final protected def getterMethod(GeneratedProperty field) {
'''
/**
* Template method which generates the setter method for <code>field</code>
- *
- * @param field
+ *
+ * @param field
* generated property with data about field which is generated as the setter method
- * @return string with the setter method source code in JAVA format
+ * @return string with the setter method source code in JAVA format
*/
final protected def setterMethod(GeneratedProperty field) '''
«val returnType = field.returnType.importedName»
/**
* Template method which generates method parameters with their types from <code>parameters</code>.
- *
+ *
* @param parameters
* group of generated property instances which are transformed to the method parameters
* @return string with the list of the method parameters with their types in JAVA format
/**
* Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
- *
- * @param parameters
+ *
+ * @param parameters
* group of generated property instances which are transformed to the sequence of parameter names
- * @return string with the list of the parameter names of the <code>parameters</code>
+ * @return string with the list of the parameter names of the <code>parameters</code>
*/
def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
fieldName»«ENDFOR»«ENDIF»'''
/**
* Template method which generates JAVA comments.
- *
+ *
* @param comment string with the comment for whole JAVA class
* @return string with comment in JAVA format
*/
sb.append(NEW_LINE)
for (String t : NL_SPLITTER.split(text)) {
- sb.append(" * ")
- sb.append(t)
+ sb.append(" *")
+ if (!t.isEmpty()) {
+ sb.append(' ');
+ sb.append(t)
+ }
sb.append(NEW_LINE)
}
sb.append(" */")
def getRestrictions(Type type) {
var Restrictions restrictions = null
if (type instanceof ConcreteType) {
- restrictions = (type as ConcreteType).restrictions
+ restrictions = type.restrictions
} else if (type instanceof GeneratedTransferObject) {
- restrictions = (type as GeneratedTransferObject).restrictions
+ restrictions = type.restrictions
}
return restrictions
}
/**
* Template method which generates method parameters with their types from <code>parameters</code>.
- *
+ *
* @param parameters
* list of parameter instances which are transformed to the method parameters
* @return string with the list of the method parameters with their types in JAVA format
import org.opendaylight.yangtools.concepts.Builder
/**
- * Template for generating JAVA builder classes.
+ * Template for generating JAVA builder classes.
*/
class BuilderTemplate extends BaseTemplate {
/**
* Returns set of method signature instances which contains all the methods of the <code>genType</code>
* and all the methods of the implemented interfaces.
- *
+ *
* @returns set of method signature instances
*/
def private Set<MethodSignature> createMethods() {
}
/**
- * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
+ * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
* and recursively their implemented interfaces.
- *
+ *
* @param methods set of method signatures
* @param implementedIfcs list of implemented interfaces
*/
/**
* Returns the first element of the list <code>elements</code>.
- *
+ *
* @param list of elements
*/
def private <E> first(List<E> elements) {
/**
* Returns the name of the package from <code>fullyQualifiedName</code>.
- *
+ *
* @param fullyQualifiedName string with fully qualified type name (package + type)
* @return string with the package name
*/
/**
* Creates set of generated property instances from getter <code>methods</code>.
- *
- * @param set of method signature instances which should be transformed to list of properties
+ *
+ * @param set of method signature instances which should be transformed to list of properties
* @return set of generated property instances which represents the getter <code>methods</code>
*/
def private propertiesFromMethods(Collection<MethodSignature> methods) {
/**
* Creates generated property instance from the getter <code>method</code> name and return type.
- *
+ *
* @param method method signature from which is the method name and return type obtained
* @return generated property instance for the getter <code>method</code>
* @throws IllegalArgumentException<ul>
var prefix = "get";
if(Types.BOOLEAN.equals(method.returnType)) {
prefix = "is";
- }
+ }
if (method.name.startsWith(prefix)) {
val fieldName = method.getName().substring(prefix.length()).toFirstLower
val tmpGenTO = new GeneratedTOBuilderImpl("foo", "foo")
}
/**
- * Template method which generates JAVA class body for builder class and for IMPL class.
- *
+ * Template method which generates JAVA class body for builder class and for IMPL class.
+ *
* @return string with JAVA source code
*/
override body() '''
«generateHashCode()»
«generateEquals()»
-
+
«generateToString(properties)»
}
*/
def private generateConstructorsFromIfcs(Type type) '''
public «type.name»«BUILDER»() {
- }
+ }
«IF (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject))»
«val ifc = type as GeneratedType»
«FOR impl : ifc.implements»
*/
def private Object generateConstructorFromIfc(Type impl) '''
«IF (impl instanceof GeneratedType)»
- «val implType = impl as GeneratedType»
-
- «IF !(implType.methodDefinitions.empty)»
- public «type.name»«BUILDER»(«implType.fullyQualifiedName» arg) {
- «printConstructorPropertySetter(implType)»
+ «IF !(impl.methodDefinitions.empty)»
+ public «type.name»«BUILDER»(«impl.fullyQualifiedName» arg) {
+ «printConstructorPropertySetter(impl)»
}
«ENDIF»
- «FOR implTypeImplement : implType.implements»
+ «FOR implTypeImplement : impl.implements»
«generateConstructorFromIfc(implTypeImplement)»
«ENDFOR»
«ENDIF»
baseIfcs.add(ifc)
}
}
- return baseIfcs
+ return baseIfcs
}
private def Set<Type> getAllIfcs(Type type) {
baseIfcs.addAll(impl.getAllIfcs)
}
}
- return baseIfcs
+ return baseIfcs
}
private def List<String> toListOfNames(Collection<Type> types) {
break;
case 1:
final «Map.importedName».Entry<«Class.importedName»<? extends «augmentField.returnType.importedName»>, «augmentField.returnType.importedName»> e = «prop».«augmentField.name».entrySet().iterator().next();
- this.«augmentField.name» = «Collections.importedName».<«Class.importedName»<? extends «augmentField.returnType.importedName»>, «augmentField.returnType.importedName»>singletonMap(e.getKey(), e.getValue());
+ this.«augmentField.name» = «Collections.importedName».<«Class.importedName»<? extends «augmentField.returnType.importedName»>, «augmentField.returnType.importedName»>singletonMap(e.getKey(), e.getValue());
break;
default :
this.«augmentField.name» = new «HashMap.importedName»<>(«prop».«augmentField.name»);
/**
* Template method which generate getter methods for IMPL class.
- *
+ *
* @return string with getter methods
*/
def private generateGetters(boolean addOverride) '''
/**
* Template method which generates the method <code>hashCode()</code>.
- *
+ *
* @return string with the <code>hashCode()</code> method definition in JAVA format
*/
def protected generateHashCode() '''
/**
* Template method which generates the method <code>equals()</code>.
- *
- * @return string with the <code>equals()</code> method definition in JAVA format
+ *
+ * @return string with the <code>equals()</code> method definition in JAVA format
*/
def protected generateEquals() '''
«IF !properties.empty || augmentField != null»
return «type.importedName».class;
}
'''
-
+
private def createDescription(GeneratedType type) {
return '''
Class that builds {@link «type.importedName»} instances.
-
+
@see «type.importedName»
'''
}
-
+
override def protected String formatDataForJavaDoc(GeneratedType type) {
val typeDescription = createDescription(type)
«IF !enclosedGeneratedTypes.empty»
«FOR innerClass : enclosedGeneratedTypes SEPARATOR "\n"»
«IF (innerClass instanceof GeneratedTransferObject)»
- «val classTemplate = new ClassTemplate(innerClass as GeneratedTransferObject)»
+ «val classTemplate = new ClassTemplate(innerClass)»
«classTemplate.generateAsInnerClass»
«ENDIF»
«IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
«val cValue = c.value»
«IF cValue instanceof List<?>»
- «val cValues = cValue as List<?>»
private static final «List.importedName»<«Pattern.importedName»> «Constants.MEMBER_PATTERN_LIST»;
public static final «List.importedName»<String> «TypeConstants.PATTERN_CONSTANT_NAME» = «ImmutableList.importedName».of(«
- FOR v : cValues SEPARATOR ", "»«
+ FOR v : cValue SEPARATOR ", "»«
IF v instanceof String»"«
- v as String»"«
+ v»"«
ENDIF»«
ENDFOR»);
import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
/**
- * Template for generating JAVA enumeration type.
+ * Template for generating JAVA enumeration type.
*/
class EnumTemplate extends BaseTemplate {
-
+
/**
* Enumeration which will be transformed to JAVA source code for enumeration
*/
val Enumeration enums
-
+
/**
* Constructs instance of this class with concrete <code>enums</code>.
- *
- * @param enums enumeration which will be transformed to JAVA source code
+ *
+ * @param enums enumeration which will be transformed to JAVA source code
*/
new(Enumeration enums) {
super(enums as GeneratedType )
this.enums = enums
}
-
-
+
+
/**
* Generates only JAVA enumeration source code.
- *
+ *
* @return string with JAVA enumeration source code
*/
def generateAsInnerClass() {
return body
}
-
+
def writeEnumItem(String name, int value, String description) '''
«asJavadoc(formatToParagraph(description))»
«name»(«value»)
/**
* Template method which generates enumeration body (declaration + enumeration items).
- *
- * @return string with the enumeration body
+ *
+ * @return string with the enumeration body
*/
override body() '''
«wrapToDocumentation(formatDataForJavaDoc(enums))»
VALUE_MAP = b.build();
}
-
+
private «enums.name»(int value) {
this.value = value;
}
-
+
/**
* @return integer value
*/
import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature\rimport org.opendaylight.yangtools.sal.binding.model.api.AnnotationType
/**
- * Template for generating JAVA interfaces.
+ * Template for generating JAVA interfaces.
*/
class InterfaceTemplate extends BaseTemplate {
-
+
/**
* List of constant instances which are generated as JAVA public static final attributes.
*/
val List<Constant> consts
-
+
/**
* List of method signatures which are generated as method declarations.
*/
val List<MethodSignature> methods
-
+
/**
* List of enumeration which are generated as JAVA enum type.
*/
val List<Enumeration> enums
-
+
/**
* List of generated types which are enclosed inside <code>genType</code>
*/
val List<GeneratedType> enclosedGeneratedTypes
-
+
/**
- * Creates the instance of this class which is used for generating the interface file source
+ * Creates the instance of this class which is used for generating the interface file source
* code from <code>genType</code>.
- *
+ *
* @throws IllegalArgumentException if <code>genType</code> equals <code>null</code>
*/
new(GeneratedType genType) {
if (genType == null) {
throw new IllegalArgumentException("Generated type reference cannot be NULL!")
}
-
+
consts = genType.constantDefinitions
methods = genType.methodDefinitions
enums = genType.enumerations
enclosedGeneratedTypes = genType.enclosedTypes
}
-
+
/**
* Template method which generate the whole body of the interface.
- *
+ *
* @return string with code for interface body in JAVA format
*/
override body() '''
public interface «type.name»
«superInterfaces»
{
-
+
«generateInnerClasses»
-
+
«generateEnums»
-
+
«generateConstants»
-
+
«generateMethods»
-
+
}
-
+
'''
-
+
def private generateAnnotations(List<AnnotationType> annotations) '''
«IF annotations != null && !annotations.empty»
/**
* Template method which generates the interface name declaration.
- *
+ *
* @return string with the code for the interface declaration in JAVA format
*/
- def private superInterfaces()
+ def private superInterfaces()
'''
«IF (!type.implements.empty)»
extends
/**
* Template method which generates inner classes inside this interface.
- *
+ *
* @return string with the source code for inner classes in JAVA format
*/
def private generateInnerClasses() '''
«IF !enclosedGeneratedTypes.empty»
«FOR innerClass : enclosedGeneratedTypes SEPARATOR "\n"»
«IF (innerClass instanceof GeneratedTransferObject)»
- «IF (innerClass as GeneratedTransferObject).unionType»
- «val unionTemplate = new UnionTemplate(innerClass as GeneratedTransferObject)»
+ «IF innerClass.unionType»
+ «val unionTemplate = new UnionTemplate(innerClass)»
«unionTemplate.generateAsInnerClass»
«this.importMap.putAll(unionTemplate.importMap)»
«ELSE»
- «val classTemplate = new ClassTemplate(innerClass as GeneratedTransferObject)»
+ «val classTemplate = new ClassTemplate(innerClass)»
«classTemplate.generateAsInnerClass»
«this.importMap.putAll(classTemplate.importMap)»
«ENDIF»
/**
* Template method which generates JAVA enum type.
- *
+ *
* @return string with inner enum source code in JAVA format
- */
+ */
def private generateEnums() '''
«IF !enums.empty»
«FOR e : enums SEPARATOR "\n"»
«ENDFOR»
«ENDIF»
'''
-
+
/**
* Template method wich generates JAVA constants.
- *
- * @return string with constants in JAVA format
- */
+ *
+ * @return string with constants in JAVA format
+ */
def private generateConstants() '''
«IF !consts.empty»
«FOR c : consts»
/**
* Template method which generates the declaration of the methods.
- *
- * @return string with the declaration of methods source code in JAVA format
- */
+ *
+ * @return string with the declaration of methods source code in JAVA format
+ */
def private generateMethods() '''
«IF !methods.empty»
«FOR m : methods SEPARATOR "\n"»
import static org.opendaylight.yangtools.binding.generator.util.Types.*
/**
- * Template for generating JAVA class.
+ * Template for generating JAVA class.
*/
class UnionTemplate extends ClassTemplate {
/**
* Creates instance of this class with concrete <code>genType</code>.
- *
+ *
* @param genType generated transfer object which will be transformed to JAVA class source code
*/
new(GeneratedTransferObject genType) {
«IF isCharArray»
/**
* Constructor provided only for using in JMX. Don't use it for
- * construction new object of this union type.
+ * construction new object of this union type.
*/
@«ConstructorProperties.importedName»("«property.name»")
public «type.name»(«propRet.importedName» «property.fieldName») {
«String.importedName» defVal = new «String.importedName»(«property.fieldName»);
- «type.name» defInst = «type.name»Builder.getDefaultInstance(defVal);
+ «type.name» defInst = «typeBuilder()».getDefaultInstance(defVal);
«FOR other : finalProperties»
«IF other.name.equals("value")»
«IF other.returnType.importedName.contains("[]")»
this.«other.fieldName» = «property.fieldName».getValue();
«ELSEIF propRet instanceof GeneratedTransferObject // Is it a GeneratedTransferObject
&& (propRet as GeneratedTransferObject).typedef // Is it a typedef
- && (propRet as GeneratedTransferObject).properties != null
- && !(propRet as GeneratedTransferObject).properties.empty
- && ((propRet as GeneratedTransferObject).properties.size == 1)
- && (propRet as GeneratedTransferObject).properties.get(0).name.equals("value")
+ && (propRet as GeneratedTransferObject).properties != null
+ && !(propRet as GeneratedTransferObject).properties.empty
+ && ((propRet as GeneratedTransferObject).properties.size == 1)
+ && (propRet as GeneratedTransferObject).properties.get(0).name.equals("value")
&& BOOLEAN.equals((propRet as GeneratedTransferObject).properties.get(0).returnType)» // And the property value is of type boolean
««« generated boolean typedef
this.«other.fieldName» = «property.fieldName».isValue().toString().toCharArray();
«ENDIF»
«ENDFOR»
'''
+
+ def typeBuilder() {
+ val outerCls = getOuterClassName(type);
+ if(outerCls !== null) {
+ return outerCls + type.name + "Builder"
+ }
+ return type.name + "Builder"
+ }
private def unionConstructorsParentProperties() '''
«FOR property : parentProperties SEPARATOR "\n"»
import java.util.Set
import java.util.TreeMap
-import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil
import org.opendaylight.yangtools.binding.generator.util.Types
import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType
import org.opendaylight.yangtools.sal.binding.model.api.Type
import static org.opendaylight.yangtools.yang.binding.BindingMapping.*
import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider
import com.google.common.base.Preconditions
-import org.opendaylight.yangtools.yang.binding.BindingMapping
class YangModuleInfoTemplate {
Preconditions.checkArgument(module != null, "Module must not be null.");
this.module = module
this.ctx = ctx
- _packageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
+ _packageName = getRootPackageName(module.getQNameModule());
_modelBindingProviderName = '''«packageName».«MODEL_BINDING_PROVIDER_CLASS_NAME»''';
}
«val DateFormat df = new SimpleDateFormat("yyyy-MM-dd")»
private final «String.importedName» revision = "«df.format(module.revision)»";
private final «String.importedName» resourcePath = "«sourcePath»";
-
+
private final «Set.importedName»<YangModuleInfo> importedModules;
public static «YangModuleInfo.importedName» getInstance() {
«sorted.put(module.revision, module)»
«ENDIF»
«ENDFOR»
- set.add(«BindingGeneratorUtil.moduleNamespaceToPackageName(sorted.lastEntry().value)».«MODULE_INFO_CLASS_NAME».getInstance());
+ set.add(«getRootPackageName(sorted.lastEntry().value.QNameModule)».«MODULE_INFO_CLASS_NAME».getInstance());
«ELSE»
- set.add(«BindingGeneratorUtil.moduleNamespaceToPackageName(ctx.findModuleByName(name, rev))».«MODULE_INFO_CLASS_NAME».getInstance());
+ set.add(«getRootPackageName((ctx.findModuleByName(name, rev).QNameModule))».«MODULE_INFO_CLASS_NAME».getInstance());
«ENDIF»
«ENDFOR»
«ENDIF»
«IF !m.submodules.empty»
«FOR submodule : m.submodules»
- set.add(«BindingMapping.getClassName(submodule.name)»Info.getInstance());
+ set.add(«getClassName(submodule.name)»Info.getInstance());
«ENDFOR»
«ENDIF»
«IF m.imports.empty && m.submodules.empty»
return "/" + module.moduleSourcePath.replace(java.io.File.separatorChar, '/')
}
- private def imports() '''
+ private def imports() '''
«IF !importMap.empty»
«FOR entry : importMap.entrySet»
- «IF entry.value != BindingGeneratorUtil.moduleNamespaceToPackageName(module)»
+ «IF entry.value != getRootPackageName(module.QNameModule)»
import «entry.value».«entry.key»;
«ENDIF»
«ENDFOR»
importMap.put(typeName, typePackageName);
}
if (type instanceof ParameterizedType) {
- val ParameterizedType paramType = (type as ParameterizedType)
- val Type[] params = paramType.getActualTypeArguments()
+ val Type[] params = type.getActualTypeArguments()
if (params != null) {
for (Type param : params) {
putTypeIntoImports(param);
final def StringBuilder addActualTypeParameters(StringBuilder builder, Type type) {
if (type instanceof ParameterizedType) {
- val ParameterizedType pType = (type as ParameterizedType)
- val Type[] pTypes = pType.getActualTypeArguments();
- builder.append("<");
+ val Type[] pTypes = type.getActualTypeArguments();
+ builder.append('<');
builder.append(getParameters(pTypes));
- builder.append(">");
+ builder.append('>');
}
return builder;
}
private def generateSubInfo(Module module) '''
«FOR submodule : module.submodules»
- private static final class «BindingMapping.getClassName(submodule.name)»Info implements «YangModuleInfo.importedName» {
+ private static final class «getClassName(submodule.name)»Info implements «YangModuleInfo.importedName» {
- private static final «YangModuleInfo.importedName» INSTANCE = new «BindingMapping.getClassName(submodule.name)»Info();
+ private static final «YangModuleInfo.importedName» INSTANCE = new «getClassName(submodule.name)»Info();
private final «String.importedName» name = "«submodule.name»";
private final «String.importedName» namespace = "«submodule.namespace.toString»";
return INSTANCE;
}
- «classBody(submodule, BindingMapping.getClassName(submodule.name + "Info"))»
+ «classBody(submodule, getClassName(submodule.name + "Info"))»
}
«ENDFOR»
'''
import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.cleanUp;
import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.getSourceFiles;
import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.testCompilation;
+
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableSet;
// Test if all sources are generated
File parent = new File(sourcesOutputDir, NS_TEST);
- File keyArgs = new File(parent, "KeyArgs.java");
- File links = new File(parent, "Links.java");
- File linksBuilder = new File(parent, "LinksBuilder.java");
- File linksKey = new File(parent, "LinksKey.java");
- File testData = new File(parent, "TestData.java");
+ final File keyArgs = new File(parent, "KeyArgs.java");
+ final File links = new File(parent, "Links.java");
+ final File linksBuilder = new File(parent, "LinksBuilder.java");
+ final File linksKey = new File(parent, "LinksKey.java");
+ final File testData = new File(parent, "TestData.java");
assertTrue(keyArgs.exists());
assertTrue(links.exists());
assertTrue(linksBuilder.exists());
assertFilesCount(parent, 6);
parent = new File(sourcesOutputDir, NS_TEST + FS + "links");
- File level = new File(parent, "Level.java");
- File linkGroup = new File(parent, "LinkGroup.java");
- File node = new File(parent, "Node.java");
- File nodeBuilder = new File(parent, "NodeBuilder.java");
- File nodeList = new File(parent, "NodeList.java");
- File nodeListBuilder = new File(parent, "NodeListBuilder.java");
- File nodesType = new File(parent, "NodesType.java");
+ final File level = new File(parent, "Level.java");
+ final File linkGroup = new File(parent, "LinkGroup.java");
+ final File node = new File(parent, "Node.java");
+ final File nodeBuilder = new File(parent, "NodeBuilder.java");
+ final File nodeList = new File(parent, "NodeList.java");
+ final File nodeListBuilder = new File(parent, "NodeListBuilder.java");
+ final File nodesType = new File(parent, "NodesType.java");
assertTrue(level.exists());
assertTrue(linkGroup.exists());
assertTrue(node.exists());
// Test if sources are compilable
testCompilation(sourcesOutputDir, compiledOutputDir);
- ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
- Class<?> keyArgsClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.KeyArgs", true, loader);
- Class<?> linksClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.Links", true, loader);
- Class<?> linksKeyClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.LinksKey", true, loader);
+ final ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
+ final Class<?> keyArgsClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.KeyArgs", true, loader);
+ final Class<?> linksClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.Links", true, loader);
+ final Class<?> linksKeyClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.LinksKey", true, loader);
// Test generated 'grouping key-args'
assertTrue(keyArgsClass.isInterface());
// Test list key constructor arguments ordering
assertContainsConstructor(linksKeyClass, Byte.class, String.class, Integer.class);
// Test serialVersionUID generation
- Field suid = assertContainsField(linksKeyClass, "serialVersionUID", Long.TYPE);
+ final Field suid = assertContainsField(linksKeyClass, "serialVersionUID", Long.TYPE);
suid.setAccessible(true);
assertEquals(-8829501012356283881L, suid.getLong(null));
// Test if all sources were generated from 'module foo'
File parent = new File(sourcesOutputDir, NS_FOO);
- File fooListener = new File(parent, "FooListener.java");
+ final File fooListener = new File(parent, "FooListener.java");
File pathAttributes = new File(parent, "PathAttributes.java");
- File update = new File(parent, "Update.java");
- File updateBuilder = new File(parent, "UpdateBuilder.java");
+ final File update = new File(parent, "Update.java");
+ final File updateBuilder = new File(parent, "UpdateBuilder.java");
assertTrue(fooListener.exists());
assertTrue(pathAttributes.exists());
assertTrue(update.exists());
assertFilesCount(parent, 1);
parent = new File(parent, "attributes");
assertFilesCount(parent, 2);
- File origin = new File(parent, "Origin.java");
- File originBuilder = new File(parent, "OriginBuilder.java");
+ final File origin = new File(parent, "Origin.java");
+ final File originBuilder = new File(parent, "OriginBuilder.java");
assertTrue(origin.exists());
assertTrue(originBuilder.exists());
parent = new File(sourcesOutputDir, NS_FOO + FS + "update");
assertFilesCount(parent, 2);
pathAttributes = new File(parent, "PathAttributes.java");
- File pathAttributesBuilder = new File(parent, "PathAttributesBuilder.java");
+ final File pathAttributesBuilder = new File(parent, "PathAttributesBuilder.java");
assertTrue(pathAttributes.exists());
assertTrue(pathAttributesBuilder.exists());
// Test if all sources were generated from 'module bar'
parent = new File(sourcesOutputDir, NS_BAR);
- File destination = new File(parent, "Destination.java");
- File pathAttributes1 = new File(parent, "PathAttributes1.java");
- File pathAttributes1Builder = new File(parent, "PathAttributes1Builder.java");
+ final File destination = new File(parent, "Destination.java");
+ final File pathAttributes1 = new File(parent, "PathAttributes1.java");
+ final File pathAttributes1Builder = new File(parent, "PathAttributes1Builder.java");
assertTrue(destination.exists());
assertTrue(pathAttributes1.exists());
assertTrue(pathAttributes1Builder.exists());
parent = new File(sourcesOutputDir, NS_BAR + FS + "destination");
assertFilesCount(parent, 2);
- File destinationType = new File(parent, "DestinationType.java");
+ final File destinationType = new File(parent, "DestinationType.java");
assertTrue(destinationType.exists());
parent = new File(parent, "destination");
assertFilesCount(parent, 1);
parent = new File(parent, "type");
assertFilesCount(parent, 2);
- File destinationIpv4 = new File(parent, "DestinationIp.java");
- File destinationIpv4Builder = new File(parent, "DestinationIpBuilder.java");
+ final File destinationIpv4 = new File(parent, "DestinationIp.java");
+ final File destinationIpv4Builder = new File(parent, "DestinationIpBuilder.java");
assertTrue(destinationIpv4.exists());
assertTrue(destinationIpv4Builder.exists());
parent = new File(parent, "path");
assertFilesCount(parent, 1);
parent = new File(parent, "attributes");
- File mpUnreachNlri = new File(parent, "MpUnreachNlri.java");
- File mpUnreachNlriBuilder = new File(parent, "MpUnreachNlriBuilder.java");
+ final File mpUnreachNlri = new File(parent, "MpUnreachNlri.java");
+ final File mpUnreachNlriBuilder = new File(parent, "MpUnreachNlriBuilder.java");
assertTrue(mpUnreachNlri.exists());
assertTrue(mpUnreachNlriBuilder.exists());
assertFilesCount(parent, 3);
parent = new File(parent, "unreach");
assertFilesCount(parent, 1);
parent = new File(parent, "nlri");
- File withdrawnRoutes = new File(parent, "WithdrawnRoutes.java");
- File withdrawnRoutesBuilder = new File(parent, "WithdrawnRoutesBuilder.java");
+ final File withdrawnRoutes = new File(parent, "WithdrawnRoutes.java");
+ final File withdrawnRoutesBuilder = new File(parent, "WithdrawnRoutesBuilder.java");
assertTrue(withdrawnRoutes.exists());
assertTrue(withdrawnRoutesBuilder.exists());
assertFilesCount(parent, 2);
// Test if all sources were generated from 'module baz'
parent = new File(sourcesOutputDir, NS_BAZ);
assertFilesCount(parent, 2);
- File linkstateDestination = new File(parent, "LinkstateDestination.java");
+ final File linkstateDestination = new File(parent, "LinkstateDestination.java");
assertTrue(linkstateDestination.exists());
parent = new File(sourcesOutputDir, NS_BAZ + FS + "update");
parent = new File(parent, "destination");
assertFilesCount(parent, 1);
parent = new File(parent, "type");
- File destinationLinkstate = new File(parent, "DestinationLinkstate.java");
- File destinationLinkstateBuilder = new File(parent, "DestinationLinkstateBuilder.java");
+ final File destinationLinkstate = new File(parent, "DestinationLinkstate.java");
+ final File destinationLinkstateBuilder = new File(parent, "DestinationLinkstateBuilder.java");
assertTrue(destinationLinkstate.exists());
assertTrue(destinationLinkstateBuilder.exists());
assertFilesCount(parent, 3);
parent = new File(parent, "destination");
assertFilesCount(parent, 1);
parent = new File(parent, "linkstate");
- File links = new File(parent, "Links.java");
- File linksBuilder = new File(parent, "LinksBuilder.java");
+ final File links = new File(parent, "Links.java");
+ final File linksBuilder = new File(parent, "LinksBuilder.java");
assertTrue(links.exists());
assertTrue(linksBuilder.exists());
assertFilesCount(parent, 3);
parent = new File(parent, "links");
- File source = new File(parent, "Source.java");
- File sourceBuilder = new File(parent, "SourceBuilder.java");
+ final File source = new File(parent, "Source.java");
+ final File sourceBuilder = new File(parent, "SourceBuilder.java");
assertTrue(source.exists());
assertTrue(sourceBuilder.exists());
assertFilesCount(parent, 3);
parent = new File(parent, "source");
- File address = new File(parent, "Address.java");
- File addressBuilder = new File(parent, "AddressBuilder.java");
+ final File address = new File(parent, "Address.java");
+ final File addressBuilder = new File(parent, "AddressBuilder.java");
assertTrue(address.exists());
assertTrue(addressBuilder.exists());
assertFilesCount(parent, 2);
generateTestSources("/compilation/leaf-return-types", sourcesOutputDir);
- File parent = new File(sourcesOutputDir, NS_TEST);
+ final File parent = new File(sourcesOutputDir, NS_TEST);
assertTrue(new File(parent, "TestData.java").exists());
assertTrue(new File(parent, "Nodes.java").exists());
assertTrue(new File(parent, "NodesBuilder.java").exists());
assertTrue(new File(parent, "Alg.java").exists());
- assertTrue(new File(parent, "IdUnionBuilder.java").exists());
+ assertTrue(new File(parent, "NodesIdUnionBuilder.java").exists());
assertFilesCount(parent, 5);
// Test if sources are compilable
testCompilation(sourcesOutputDir, compiledOutputDir);
- String pkg = BASE_PKG + ".urn.opendaylight.test.rev131008";
- ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
- Class<?> nodesClass = Class.forName(pkg + ".Nodes", true, loader);
- Class<?> builderClass = Class.forName(pkg + ".NodesBuilder", true, loader);
+ final String pkg = BASE_PKG + ".urn.opendaylight.test.rev131008";
+ final ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
+ final Class<?> nodesClass = Class.forName(pkg + ".Nodes", true, loader);
+ final Class<?> builderClass = Class.forName(pkg + ".NodesBuilder", true, loader);
// Test methods return type
- byte[] b = new byte[] {};
+ final byte[] b = new byte[] {};
assertContainsMethod(nodesClass, b.getClass(), "getIdBinary");
assertContainsMethod(nodesClass, pkg + ".Nodes$IdBits", "getIdBits", loader);
assertContainsMethod(nodesClass, Boolean.class, "isIdBoolean");
assertContainsMethod(nodesClass, BigInteger.class, "getIdU64");
assertContainsMethod(nodesClass, pkg + ".Nodes$IdUnion", "getIdUnion", loader);
- Object builderObj = builderClass.newInstance();
+ final Object builderObj = builderClass.newInstance();
Method m = assertContainsMethod(builderClass, builderClass, "setIdBinary", b.getClass());
- List<Range<Integer>> lengthConstraints = new ArrayList<>();
+ final List<Range<Integer>> lengthConstraints = new ArrayList<>();
lengthConstraints.add(Range.closed(1, 10));
Object arg = new byte[] {};
String expectedMsg = String.format("Invalid length: %s, expected: %s.", arg, lengthConstraints);
assertContainsRestrictionCheck(builderObj, m, expectedMsg, arg);
m = assertContainsMethod(builderClass, builderClass, "setIdDecimal64", BigDecimal.class);
- List<Range<BigDecimal>> rangeConstraints = new ArrayList<>();
+ final List<Range<BigDecimal>> rangeConstraints = new ArrayList<>();
rangeConstraints.add(Range.closed(new BigDecimal("1.5"), new BigDecimal("5.5")));
arg = new BigDecimal("1.4");
expectedMsg = String.format("Invalid range: %s, expected: %s.", arg, rangeConstraints);
generateTestSources("/compilation/context-reference", sourcesOutputDir);
// Test if all sources are generated
- File fooParent = new File(sourcesOutputDir, NS_FOO);
+ final File fooParent = new File(sourcesOutputDir, NS_FOO);
assertFilesCount(fooParent, 3);
assertTrue(new File(fooParent, "FooData.java").exists());
assertTrue(new File(fooParent, "Nodes.java").exists());
assertTrue(new File(fooParent, "NodesBuilder.java").exists());
- File barParent = new File(sourcesOutputDir, NS_BAR);
+ final File barParent = new File(sourcesOutputDir, NS_BAR);
assertFilesCount(barParent, 1);
assertTrue(new File(barParent, "IdentityClass.java").exists());
// Test if sources are compilable
testCompilation(sourcesOutputDir, compiledOutputDir);
- ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
- Class<?> nodesClass = Class.forName(BASE_PKG + ".urn.opendaylight.foo.rev131008.Nodes", true, loader);
- Class<?> identityClass = Class
+ final ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
+ final Class<?> nodesClass = Class.forName(BASE_PKG + ".urn.opendaylight.foo.rev131008.Nodes", true, loader);
+ final Class<?> identityClass = Class
.forName(BASE_PKG + ".urn.opendaylight.bar.rev131008.IdentityClass", true, loader);
// test identity
try {
identityClass.getConstructor();
- Class<?> baseIdentity = Class.forName("org.opendaylight.yangtools.yang.binding.BaseIdentity", true, loader);
+ final Class<?> baseIdentity = Class.forName("org.opendaylight.yangtools.yang.binding.BaseIdentity", true, loader);
assertEquals(baseIdentity, identityClass.getSuperclass());
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
throw new AssertionError("IdentityClass must have no-arg constructor");
}
// Test annotation
try {
- Method getId = nodesClass.getMethod("getId");
- Annotation[] annotations = getId.getAnnotations();
+ final Method getId = nodesClass.getMethod("getId");
+ final Annotation[] annotations = getId.getAnnotations();
assertEquals(1, annotations.length);
- Annotation routingContext = annotations[0];
+ final Annotation routingContext = annotations[0];
assertEquals(RoutingContext.class, routingContext.annotationType());
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
throw new AssertionError("Method getId() not found");
}
// Test if sources are compilable
testCompilation(sourcesOutputDir, compiledOutputDir);
- ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
- Class<?> outputActionClass = Class.forName(BASE_PKG
+ final ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
+ final Class<?> outputActionClass = Class.forName(BASE_PKG
+ ".urn.test.foo.rev140717.action.action.output.action._case.OutputAction", true, loader);
- Class<?> actionClass = Class.forName(BASE_PKG + ".urn.test.foo.rev140717.Action", true, loader);
+ final Class<?> actionClass = Class.forName(BASE_PKG + ".urn.test.foo.rev140717.Action", true, loader);
// Test generated 'container output-action'
assertTrue(outputActionClass.isInterface());
assertEquals(java.lang.Class.class, method.getReturnType());
returnType = method.getGenericReturnType();
assertTrue(returnType instanceof ParameterizedType);
- ParameterizedType pt = (ParameterizedType) returnType;
- java.lang.reflect.Type[] parameters = pt.getActualTypeArguments();
+ final ParameterizedType pt = (ParameterizedType) returnType;
+ final java.lang.reflect.Type[] parameters = pt.getActualTypeArguments();
assertEquals(1, parameters.length);
- java.lang.reflect.Type parameter = parameters[0];
+ final java.lang.reflect.Type parameter = parameters[0];
assertTrue(parameter instanceof WildcardType);
- WildcardType wildcardType = (WildcardType) parameter;
+ final WildcardType wildcardType = (WildcardType) parameter;
assertEquals("? extends " + returnTypeStr, wildcardType.toString());
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
throw new AssertionError("Method '" + methodName + "' not found");
}
}
assertEquals(rawReturnType, method.getReturnType());
returnType = method.getGenericReturnType();
assertTrue(returnType instanceof ParameterizedType);
- ParameterizedType pt = (ParameterizedType) returnType;
- java.lang.reflect.Type[] parameters = pt.getActualTypeArguments();
+ final ParameterizedType pt = (ParameterizedType) returnType;
+ final java.lang.reflect.Type[] parameters = pt.getActualTypeArguments();
assertEquals(1, parameters.length);
- java.lang.reflect.Type parameter = parameters[0];
+ final java.lang.reflect.Type parameter = parameters[0];
assertTrue(parameter instanceof WildcardType);
- WildcardType wildcardType = (WildcardType) parameter;
+ final WildcardType wildcardType = (WildcardType) parameter;
assertEquals("?", wildcardType.toString());
- } catch (NoSuchMethodException e) {
+ } catch (final NoSuchMethodException e) {
throw new AssertionError("Method '" + methodName + "' not found");
}
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.sal.java.api.generator.test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.COMPILER_OUTPUT_PATH;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.FS;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.GENERATOR_OUTPUT_PATH;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.cleanUp;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.getSourceFiles;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.testCompilation;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.HashSet;
+import java.util.List;
+import org.junit.Test;
+import org.opendaylight.yangtools.sal.binding.model.api.Type;
+import org.opendaylight.yangtools.sal.java.api.generator.GeneratorJavaFile;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class UnionTypedefUnusedImportTest extends BaseCompilationTest {
+
+ @Test
+ public void testUnionTypedefUnusedImport() throws Exception {
+ final File sourcesOutputDir = new File(GENERATOR_OUTPUT_PATH + FS + "union-typedef");
+ assertTrue("Failed to create test file '" + sourcesOutputDir + "'", sourcesOutputDir.mkdir());
+ final File compiledOutputDir = new File(COMPILER_OUTPUT_PATH + FS + "union-typedef");
+ assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdir());
+
+ final List<File> sourceFiles = getSourceFiles("/compilation/union-typedef");
+ final SchemaContext context = parser.parseFiles(sourceFiles);
+ final List<Type> types = bindingGenerator.generateTypes(context);
+ final GeneratorJavaFile generator = new GeneratorJavaFile(new HashSet<>(types));
+ generator.generateToFile(sourcesOutputDir);
+ final boolean isUsedImport = containsImport("org.opendaylight.yang.gen.v1.org.opendaylight.yangtools.union.typedef.rev130208.TypedefUnion");
+ assertFalse(String.format("Class shouldn't contain import for this type '%s'", types.get(1).getName()),
+ isUsedImport);
+
+ testCompilation(sourcesOutputDir, compiledOutputDir);
+ cleanUp(sourcesOutputDir, compiledOutputDir);
+ }
+
+ private String readFile(String path, Charset encoding) throws IOException {
+ byte[] encoded = Files.readAllBytes(Paths.get(path));
+ return new String(encoded, encoding);
+ }
+
+ private boolean containsImport(final String fullImport) throws URISyntaxException, IOException {
+ final String filePath = GENERATOR_OUTPUT_PATH + FS + "union-typedef" + FS + "org" + FS + "opendaylight" + FS + "yang" + FS + "gen" + FS + "v1" + FS + "org" + FS + "opendaylight" + FS + "yangtools" + FS + "union" + FS + "typedef" + FS + "rev141124" + FS + "TypedefUnionBuilder.java";
+ final String fileContent = readFile(filePath, StandardCharsets.UTF_8);
+
+ if (fileContent.contains(fullImport)) {
+ return true;
+ }
+ return false;
+ }
+}
--- /dev/null
+module union-typedef-test {
+ yang-version 1;
+ namespace "org:opendaylight:yangtools:union:typedef";
+ prefix "tp";
+
+ description
+ "Test unused import";
+
+ revision "2014-11-24" {
+ reference "WILL BE DEFINED LATER";
+ }
+
+ typedef typedef-union {
+ type union {
+ type int32;
+ type string;
+ }
+ }
+}
\ No newline at end of file
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
for (DataSchemaNode childNode : container.getChildNodes()) {
if (childNode instanceof DataNodeContainer) {
ret.addAll(getAllUsesNodes((DataNodeContainer) childNode));
- } else if (childNode instanceof ChoiceNode) {
- Set<ChoiceCaseNode> cases = ((ChoiceNode) childNode).getCases();
+ } else if (childNode instanceof ChoiceSchemaNode) {
+ Set<ChoiceCaseNode> cases = ((ChoiceSchemaNode) childNode).getCases();
for (ChoiceCaseNode choiceCaseNode : cases) {
ret.addAll(getAllUsesNodes(choiceCaseNode));
}
*/
package org.opendaylight.yangtools.sal.binding.yang.types;
-import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.moduleNamespaceToPackageName;
import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
-
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import com.google.common.io.BaseEncoding;
if (r != null && returnType instanceof GeneratedTransferObject) {
GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
Module module = findParentModule(schemaContext, parentNode);
- String basePackageName = moduleNamespaceToPackageName(module);
+ String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
String packageName = packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
String genTOName = BindingMapping.getClassName(typedefName);
String name = packageName + "." + genTOName;
}
Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
- final String basePackageName = moduleNamespaceToPackageName(module);
+ final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
final String genTypeName = BindingMapping.getClassName(identity.getQName());
final String enumerationName = BindingMapping.getClassName(enumName);
Module module = findParentModule(schemaContext, parentNode);
- final String basePackageName = moduleNamespaceToPackageName(module);
+ final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
enumBuilder.setDescription(enumTypeDef.getDescription());
*/
private void resolveTypeDefsFromContext() {
final Set<Module> modules = schemaContext.getModules();
- Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
+ Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
final Module[] modulesArray = new Module[modules.size()];
int i = 0;
for (Module modul : modules) {
if (dateTypeMap == null) {
dateTypeMap = new HashMap<>();
}
- final Map<String, Type> typeMap = new HashMap<>();
- dateTypeMap.put(module.getRevision(), typeMap);
+ dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
genTypeDefsContextMap.put(module.getName(), dateTypeMap);
}
if (module == null) {
continue;
}
- final String basePackageName = moduleNamespaceToPackageName(module);
+ final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
final DataNodeIterator it = new DataNodeIterator(module);
final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
}
if (returnType != null) {
final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
- final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
+ Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
if (typeMap != null) {
+ if (typeMap.isEmpty()) {
+ typeMap = new HashMap<>(4);
+ modulesByDate.put(moduleRevision, typeMap);
+ }
typeMap.put(typedefName, returnType);
}
return returnType;
path.next();
if (!(path.hasNext())) {
parentName = BindingMapping.getClassName(parent.getName()) + "Data";
- String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
+ String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
} else {
- String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
+ String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
parentName = BindingMapping.getClassName(parent.getName());
className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
String className;
if (type instanceof ExtendedType) {
Module m = getParentModule(type);
- String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
+ String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
className = packageName + "." + BindingMapping.getClassName(typeQName);
} else {
Module parentModule = getParentModule(node);
- String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
+ String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
className = packageName + "." + BindingMapping.getClassName(node.getQName());
}
if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
&& !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
Module m = getParentModule(type);
- String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
+ String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
String className = packageName + "." + BindingMapping.getClassName(typeQName);
sb.insert(0, "new " + className + "(");
module = modules.iterator().next();
}
- String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
+ String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
className = basePackageName + "." + BindingMapping.getClassName(typeQName);
} else {
Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
Date revision = first.getRevision();
Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
parentName = BindingMapping.getClassName((parent).getName()) + "Data";
- String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
+ String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
} else {
URI namespace = first.getNamespace();
Date revision = first.getRevision();
Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
- String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
+ String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
className = packageName + "." + BindingMapping.getClassName(node.getQName());
}
<artifactId>yang-data-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>org.sonatype.plexus</groupId>
<artifactId>plexus-build-api</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
// find recursively
for(child : childNodes) {
if(child instanceof ContainerSchemaNode) {
- val contChild = child as ContainerSchemaNode
- val foundChild = findNodeInChildNodes(findingNode, contChild.childNodes)
+ val foundChild = findNodeInChildNodes(findingNode, child.childNodes)
if (foundChild != null)
return foundChild;
}
else if(child instanceof ListSchemaNode) {
- val listChild = child as ListSchemaNode
- val foundChild = findNodeInChildNodes(findingNode, listChild.childNodes)
+ val foundChild = findNodeInChildNodes(findingNode, child.childNodes)
if (foundChild != null)
return foundChild;
}
return
'''
«IF child instanceof ContainerSchemaNode»
- «printContainerNode(child as ContainerSchemaNode)»
+ «printContainerNode(child)»
«ENDIF»
«IF child instanceof AnyXmlSchemaNode»
- «printAnyXmlNode(child as AnyXmlSchemaNode)»
+ «printAnyXmlNode(child)»
«ENDIF»
«IF child instanceof LeafSchemaNode»
- «printLeafNode(child as LeafSchemaNode)»
+ «printLeafNode(child)»
«ENDIF»
«IF child instanceof LeafListSchemaNode»
- «printLeafListNode(child as LeafListSchemaNode)»
+ «printLeafListNode(child)»
«ENDIF»
«IF child instanceof ListSchemaNode»
- «printListNode(child as ListSchemaNode)»
+ «printListNode(child)»
«ENDIF»
- «IF child instanceof ChoiceNode»
- «printChoiceNode(child as ChoiceNode)»
+ «IF child instanceof ChoiceSchemaNode»
+ «printChoiceNode(child)»
«ENDIF»
'''
}
- private def printChoiceNode(ChoiceNode child) {
+ private def printChoiceNode(ChoiceSchemaNode child) {
val List<ChoiceCaseNode> cases = new ArrayList(child.cases);
if(!cases.empty) {
val ChoiceCaseNode aCase = cases.get(0)
«module.childNodes.treeSet(YangInstanceIdentifier.builder.build())»
'''
- private def dispatch CharSequence tree(ChoiceNode node,YangInstanceIdentifier path) '''
+ private def dispatch CharSequence tree(ChoiceSchemaNode node,YangInstanceIdentifier path) '''
«node.nodeName» (choice)
«casesTree(node.cases,path)»
'''
def CharSequence printBaseInfo(SchemaNode node) {
if(node instanceof LeafSchemaNode) {
- val LeafSchemaNode leafNode = (node as LeafSchemaNode)
return '''
«printInfo(node, "leaf")»
- «listItem("type", typeAnchorLink(leafNode.type?.path, leafNode.type.QName.localName))»
- «listItem("units", leafNode.units)»
- «listItem("default", leafNode.^default)»
+ «listItem("type", typeAnchorLink(node.type?.path, node.type.QName.localName))»
+ «listItem("units", node.units)»
+ «listItem("default", node.^default)»
</ul>
'''
} else if(node instanceof LeafListSchemaNode) {
- val LeafListSchemaNode leafListNode = (node as LeafListSchemaNode)
return '''
«printInfo(node, "leaf-list")»
- «listItem("type", leafListNode.type?.QName.localName)»
+ «listItem("type", node.type?.QName.localName)»
</ul>
'''
} else if(node instanceof ListSchemaNode) {
- val ListSchemaNode listNode = (node as ListSchemaNode)
return '''
«printInfo(node, "list")»
- «FOR keyDef : listNode.keyDefinition»
+ «FOR keyDef : node.keyDefinition»
«listItem("key definition", keyDef.localName)»
«ENDFOR»
</ul>
'''
- } else if(node instanceof ChoiceNode) {
- val ChoiceNode choiceNode = (node as ChoiceNode)
+ } else if(node instanceof ChoiceSchemaNode) {
return '''
«printInfo(node, "choice")»
- «listItem("default case", choiceNode.defaultCase)»
- «FOR caseNode : choiceNode.cases»
+ «listItem("default case", node.defaultCase)»
+ «FOR caseNode : node.cases»
«caseNode.printSchemaNodeInfo»
«ENDFOR»
</ul>
«listItem("description", node.description)»
«listItem("reference", node.reference)»
«IF node instanceof DataSchemaNode»
- «listItem("when condition", (node as DataSchemaNode).constraints.whenCondition?.toString)»
- «listItem("min elements", (node as DataSchemaNode).constraints.minElements?.toString)»
- «listItem("max elements", (node as DataSchemaNode).constraints.maxElements?.toString)»
+ «listItem("when condition", node.constraints.whenCondition?.toString)»
+ «listItem("min elements", node.constraints.minElements?.toString)»
+ «listItem("max elements", node.constraints.maxElements?.toString)»
«ENDIF»
'''
}
val anyxmlNodes = nodes.filter(AnyXmlSchemaNode)
val leafNodes = nodes.filter(LeafSchemaNode)
val leafListNodes = nodes.filter(LeafListSchemaNode)
- val choices = nodes.filter(ChoiceNode)
+ val choices = nodes.filter(ChoiceSchemaNode)
val cases = nodes.filter(ChoiceCaseNode)
val containers = nodes.filter(ContainerSchemaNode)
val lists = nodes.filter(ListSchemaNode)
«node.childNodes.printChildren(level,newPath)»
'''
- private def dispatch CharSequence printInfo(ChoiceNode node, int level, YangInstanceIdentifier path) '''
+ private def dispatch CharSequence printInfo(ChoiceSchemaNode node, int level, YangInstanceIdentifier path) '''
«val Set<DataSchemaNode> choiceCases = new HashSet(node.cases)»
«choiceCases.printChildren(level,path)»
'''
def asRestconfPath(YangInstanceIdentifier identifier) {
val it = new StringBuilder();
append(currentModule.name)
- append(":")
+ append(':')
var previous = false;
for(arg : identifier.pathArguments) {
- if(previous) append("/")
+ if(previous) append('/')
append(arg.nodeType.localName);
previous = true;
if(arg instanceof NodeIdentifierWithPredicates) {
- val nodeIdentifier = arg as NodeIdentifierWithPredicates;
- for(qname : nodeIdentifier.getKeyValues.keySet) {
+ for(qname : arg.getKeyValues.keySet) {
append("/{");
append(qname.localName)
- append("}")
+ append('}')
}
}
}
for (name : path) {
if (parent instanceof DataNodeContainer) {
- var SchemaNode node = (parent as DataNodeContainer).getDataChildByName(name)
+ var SchemaNode node = parent.getDataChildByName(name)
if (node == null && (parent instanceof Module)) {
val notifications = (parent as Module).notifications;
for (notification : notifications) {
pathString.append(':')
pathString.append(name.localName)
pathString.append('/')
- if(node instanceof ChoiceNode && dataNode !== null) {
+ if(node instanceof ChoiceSchemaNode && dataNode !== null) {
val DataSchemaNode caseNode = dataNode.childNodes.findFirst[DataSchemaNode e | e instanceof ChoiceCaseNode];
if(caseNode !== null) {
pathString.append("(case)");
'''
private def String nodeSchemaPathToPath(DataSchemaNode node, Map<SchemaPath, DataSchemaNode> childNodes) {
- if (node instanceof ChoiceNode || node instanceof ChoiceCaseNode) {
+ if (node instanceof ChoiceSchemaNode || node instanceof ChoiceCaseNode) {
return null
}
for (pathElement : path) {
actual.add(pathElement)
val DataSchemaNode nodeByPath = childNodes.get(SchemaPath.create(actual, absolute))
- if (!(nodeByPath instanceof ChoiceNode) && !(nodeByPath instanceof ChoiceCaseNode)) {
+ if (!(nodeByPath instanceof ChoiceSchemaNode) && !(nodeByPath instanceof ChoiceCaseNode)) {
result.append(pathElement.localName)
if (i != path.size - 1) {
result.append("/")
if (node instanceof DataNodeContainer) {
collectChildNodes((node as DataNodeContainer).childNodes, destination)
}
- if (node instanceof ChoiceNode) {
+ if (node instanceof ChoiceSchemaNode) {
val List<DataSchemaNode> choiceCases = new ArrayList()
- for (caseNode : (node as ChoiceNode).cases) {
+ for (caseNode : node.cases) {
choiceCases.add(caseNode)
}
collectChildNodes(choiceCases, destination)
File path
static val BuildContext CTX = new DefaultBuildContext();
+ static val PATH_DELIMETER = '/'
var SchemaContext context;
var List<DataSchemaNode> configData;
var List<DataSchemaNode> operationalData;
var Module module;
var List<LeafSchemaNode> pathListParams;
- val PATH_DELIMETER = "/"
new(File targetPath) {
if (!targetPath.exists) targetPath.mkdirs
var StringBuilder path = new StringBuilder
path.append(schemaNode.QName.localName)
if (schemaNode instanceof ListSchemaNode) {
- val listKeys = (schemaNode as ListSchemaNode).keyDefinition
- for (listKey : listKeys) {
+ for (listKey : schemaNode.keyDefinition) {
pathListParams.add((schemaNode as DataNodeContainer).getDataChildByName(listKey) as LeafSchemaNode)
path.append(PATH_DELIMETER)
path.append('{')
<artifactId>yang-maven-plugin-spi</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>iana-if-type-2014-05-08</artifactId>
+ <version>2014.05.08.7-SNAPSHOT</version>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools.model</groupId>
<artifactId>ietf-inet-types</artifactId>
<artifactId>ietf-yang-types-20130715</artifactId>
<version>2013.07.15.7-SNAPSHOT</version>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-interfaces</artifactId>
+ <version>2014.05.08.7-SNAPSHOT</version>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools.model</groupId>
<artifactId>ietf-restconf</artifactId>
<artifactId>ietf-topology-l3-unicast</artifactId>
<version>${ietf.topology.version}</version>
</dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-composite-node</artifactId>
- <version>${project.version}</version>
- </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>restconf-client-api</artifactId>
<version>0.7.0-SNAPSHOT</version>
<packaging>jar</packaging>
- <build>
- <plugins>
- <!-- generate dependencies versions -->
- <plugin>
- <artifactId>maven-dependency-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>com.alexecollins.maven.plugin</groupId>
- <artifactId>script-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.karaf.tooling</groupId>
- <artifactId>karaf-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-resources-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <dependenciesToScan>
- <dependency>org.opendaylight.yangtools:features-test</dependency>
- </dependenciesToScan>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
<dependencyManagement>
<dependencies>
<dependency>
</dependencyManagement>
<dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>iana-if-type-2014-05-08</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools.model</groupId>
<artifactId>ietf-inet-types</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-interfaces</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools.model</groupId>
<artifactId>ietf-restconf</artifactId>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-data-api</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-composite-node</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-data-impl</artifactId>
<feature name='odl-yangtools-models' version='${project.version}' description='OpenDaylight :: Yangtools :: Models'>
<feature version='${project.version}'>odl-yangtools-binding</feature>
+ <bundle>mvn:org.opendaylight.yangtools.model/iana-if-type-2014-05-08/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.yangtools.model/ietf-inet-types/{{VERSION}}</bundle>
+ <bundle>mvn:org.opendaylight.yangtools.model/ietf-interfaces/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.yangtools.model/ietf-yang-types/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.yangtools.model/ietf-yang-types-20130715/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.yangtools.model/ietf-restconf/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.yangtools.thirdparty/antlr4-runtime-osgi-nohead/{{VERSION}}</bundle>
<bundle>mvn:commons-io/commons-io/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-data-api/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.yangtools/yang-data-composite-node/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-data-impl/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-data-operations/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-data-util/{{VERSION}}</bundle>
</goals>
</pluginExecutionFilter>
<action>
- <ignore />
+ <execute/>
</action>
</pluginExecution>
<pluginExecution>
*/
package org.opendaylight.yangtools.util;
+import com.google.common.collect.ImmutableSet;
import java.math.BigDecimal;
import java.math.BigInteger;
-import java.util.Collections;
-import java.util.HashSet;
import java.util.Set;
-
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.concepts.Mutable;
throw new UnsupportedOperationException("Helper class");
}
- public static final Set<Class<?>> KNOWN_IMMUTABLES = Immutables.<Class<?>> asHashSet(
- //
+ public static final Set<Class<?>> KNOWN_IMMUTABLES = ImmutableSet.<Class<?>>of(
Integer.class, Short.class, BigDecimal.class, BigInteger.class, Byte.class, Character.class, Double.class,
- Float.class, String.class);
+ Float.class, String.class, Boolean.class, Void.class);
/**
* Determines if object is known to be immutable
}
return false;
}
-
- @SafeVarargs
- private static <E> Set<E> asHashSet(final E... list) {
- HashSet<E> ret = new HashSet<>();
- for (E e : list) {
- ret.add(e);
- }
- return Collections.unmodifiableSet(ret);
- }
}
case 0:
return Collections.singletonList(obj);
case 1:
- ret = new ArrayList<>();
+ ret = new ArrayList<>(2);
ret.addAll(list);
break;
default:
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.util;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableCollection;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSet.Builder;
+import com.google.common.collect.Iterators;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import javax.annotation.Nonnull;
+
+/**
+ * An unmodifiable view over a {@link Collection}. Unlike the view returned via
+ * {@link Collections#unmodifiableCollection(Collection)}, this class checks its
+ * argument to ensure multiple encapsulation does not occur.
+ *
+ * this class checks
+ * the argument so it prevents multiple encapsulation. Subclasses of
+ * {@link ImmutableCollection} are also recognized and not encapsulated.
+ * An attempt is also made to identi
+ *
+ * @param <E> the type of elements in this collection
+ */
+public final class UnmodifiableCollection<E> implements Collection<E>, Serializable {
+ private static final long serialVersionUID = 1L;
+ private static final Class<?> UNMODIFIABLE_COLLECTION_CLASS;
+ private static final Collection<Class<?>> SINGLETON_CLASSES;
+
+ static {
+ UNMODIFIABLE_COLLECTION_CLASS = Collections.unmodifiableCollection(new ArrayList<Object>()).getClass();
+
+ final Builder<Class<?>> b = ImmutableSet.builder();
+ b.add(Collections.singleton(null).getClass());
+ b.add(Collections.singletonList(null).getClass());
+ SINGLETON_CLASSES = b.build();
+ }
+
+ private final Collection<E> delegate;
+
+ private UnmodifiableCollection(final Collection<E> delegate) {
+ this.delegate = Preconditions.checkNotNull(delegate);
+ }
+
+ /**
+ * Create an unmodifiable view of the target collection. If the instance is known
+ * to be unmodifiable, that instance is returned.
+ *
+ * @param collection Target collection
+ * @return An unmodifiable view of the collection
+ */
+ public static <T> Collection<T> create(final @Nonnull Collection<T> collection) {
+ if (collection instanceof UnmodifiableCollection || collection instanceof ImmutableCollection ||
+ Collections.EMPTY_LIST == collection || Collections.EMPTY_SET == collection ||
+ UNMODIFIABLE_COLLECTION_CLASS.isInstance(collection) || SINGLETON_CLASSES.contains(collection.getClass())) {
+ return collection;
+ }
+
+ return new UnmodifiableCollection<>(collection);
+ }
+
+ @Override
+ public Iterator<E> iterator() {
+ return Iterators.unmodifiableIterator(delegate.iterator());
+ }
+
+ @Override
+ public int size() {
+ return delegate.size();
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return delegate.isEmpty();
+ }
+
+ @Override
+ public boolean contains(final Object o) {
+ return delegate.contains(o);
+ }
+
+ @Override
+ public Object[] toArray() {
+ return delegate.toArray();
+ }
+
+ @Override
+ public <T> T[] toArray(final T[] a) {
+ return delegate.toArray(a);
+ }
+
+ @Override
+ public boolean containsAll(final Collection<?> c) {
+ return delegate.containsAll(c);
+ }
+
+ @Override
+ public boolean add(final E e) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean addAll(final Collection<? extends E> c) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean remove(final Object o) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean removeAll(final Collection<?> c) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean retainAll(final Collection<?> c) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void clear() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String toString() {
+ final StringBuffer sb = new StringBuffer("UnmodifiableCollection{");
+ sb.append(delegate);
+ return sb.toString();
+ }
+}
options.add(mavenBundle("ch.qos.logback", "logback-core").versionAsInProject());
options.add(mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject());
options.add(mavenBundle("com.google.guava", "guava").versionAsInProject());
- options.add(mavenBundle("commons-io", "commons-io").versionAsInProject());
options.add(mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject());
options.add(mavenBundle("org.opendaylight.yangtools.thirdparty", "antlr4-runtime-osgi-nohead")
.versionAsInProject());
+++ /dev/null
-package org.opendaylight.yangtools.it.yang.runtime.tests;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import javassist.ClassPool;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.bug466.augmentation.empty.rev140226.Bug4661;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.bug466.base.rev140226.Bug466;
-import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.data.impl.codec.DataContainerCodec;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-
-import com.google.common.base.Optional;
-
-public class Bug466EmptyAugmentationCodecs {
-
-
-
- private YangModuleInfo baseModuleInfo;
- private YangModuleInfo augmentationModuleInfo;
- private ModuleInfoBackedContext moduleInfoContext;
- private RuntimeGeneratedMappingServiceImpl mappingService;
- private Optional<SchemaContext> schemaContext;
-
-
- @Before
- public void setup()throws Exception {
- baseModuleInfo = BindingReflections.getModuleInfo(Bug466.class);
- augmentationModuleInfo = BindingReflections.getModuleInfo(Bug4661.class);
-
- moduleInfoContext = ModuleInfoBackedContext.create();
- moduleInfoContext.registerModuleInfo(baseModuleInfo);
- moduleInfoContext.registerModuleInfo(augmentationModuleInfo);
- schemaContext = moduleInfoContext.tryToCreateSchemaContext();
- assertNotNull(schemaContext);
- assertTrue(schemaContext.isPresent());
-
- mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault(), moduleInfoContext);
- mappingService.onGlobalContextUpdated(schemaContext.get());
-
- }
-
-
- @Test
- public void proactiveGenerationOfAugmentationCodecs() {
- DataContainerCodec<Bug466> codec = mappingService.getCodecRegistry().getCodecForDataObject(Bug466.class);
- assertNotNull(codec);
- }
-
-}
import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
assertDeepRevision(revision, child);
}
- } else if (node instanceof ChoiceNode) {
- for (DataSchemaNode child : ((ChoiceNode) node).getCases()) {
+ } else if (node instanceof ChoiceSchemaNode) {
+ for (DataSchemaNode child : ((ChoiceSchemaNode) node).getCases()) {
assertDeepRevision(revision, child);
}
}
+++ /dev/null
-package org.opendaylight.yangtools.it.yang.runtime.tests;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import com.google.common.base.Optional;
-
-import java.util.AbstractMap.SimpleEntry;
-import java.util.Map.Entry;
-
-import javassist.ClassPool;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.extension.yang.ext.rev130709.RpcContextRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.base.rev140424.Choices;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.base.rev140424.grouping.GroupingDataBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.ext.rev140424.choices.augmentable.choice.ext.with.grouping.augmentations.ExtWithGroupingAugmentations;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.ext.rev140424.choices.augmentable.choice.ext.with.grouping.augmentations.ExtWithGroupingAugmentationsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.ext.rev140424.choices.augmentable.choice.ext.with.grouping.augmentations.ext.with.grouping.augmentations.InUsesAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.ext.rev140424.choices.augmentable.choice.ext.with.grouping.augmentations.ext.with.grouping.augmentations.InUsesAugmentBuilder;
-import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-
-public class RuntimeCodecAugmentationWithGroupingsAndCasesTest {
-
- private static final InstanceIdentifier<ExtWithGroupingAugmentations> GROUPING_AUGMENTATIONS_PATH = InstanceIdentifier
- .builder(Choices.class).child(ExtWithGroupingAugmentations.class).build();
-
- private ModuleInfoBackedContext moduleInfoContext;
-
- private Optional<SchemaContext> schemaContext;
-
- private RuntimeGeneratedMappingServiceImpl mappingService;
-
-
- @Before
- public void setUp() throws Exception {
- YangModuleInfo yangExtInfo = BindingReflections.getModuleInfo(RpcContextRef.class);
- YangModuleInfo baseModuleInfo = BindingReflections.getModuleInfo(Choices.class);
- YangModuleInfo augmentationModuleInfo = BindingReflections.getModuleInfo(org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.ext.rev140424.choices.augmentable.choice.ext.with.grouping.augmentations.ExtWithGroupingAugmentations.class);
-
- moduleInfoContext = ModuleInfoBackedContext.create();
- moduleInfoContext.registerModuleInfo(yangExtInfo);
- moduleInfoContext.registerModuleInfo(baseModuleInfo);
- moduleInfoContext.registerModuleInfo(augmentationModuleInfo);
-
- schemaContext = moduleInfoContext.tryToCreateSchemaContext();
- assertNotNull(schemaContext);
- assertTrue(schemaContext.isPresent());
-
- mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault(), moduleInfoContext);
- mappingService.onGlobalContextUpdated(schemaContext.get());
-
- }
-
- @Test
- public void testSerialization() {
-
- ExtWithGroupingAugmentations caseData = new ExtWithGroupingAugmentationsBuilder() //
- .setGroupingData(new GroupingDataBuilder() //
- .addAugmentation(InUsesAugment.class, new InUsesAugmentBuilder() //
- .setExtAumentation("InUses") //
- .build()) //
- .build()) //
- .build();
-
- Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> result = mappingService
- .toDataDom(new SimpleEntry(GROUPING_AUGMENTATIONS_PATH, caseData));
- assertNotNull(result);
- }
-}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
+
+ This program and the accompanying materials are made available under the
+ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ and is available at http://www.eclipse.org/legal/epl-v10.html
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <parent>
+ <artifactId>model-iana</artifactId>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <version>0.7.0-SNAPSHOT</version>
+ </parent>
+
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>iana-if-type-2014-05-08</artifactId>
+ <version>2014.05.08.7-SNAPSHOT</version>
+ <name>${project.artifactId}</name>
+ <description>${project.artifactId}</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-interfaces</artifactId>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
+ </instructions>
+ </configuration>
+ </plugin>
+
+ </plugins>
+ </build>
+
+</project>
--- /dev/null
+module iana-if-type {
+ namespace "urn:ietf:params:xml:ns:yang:iana-if-type";
+ prefix ianaift;
+
+ import ietf-interfaces {
+ prefix if;
+ }
+
+ organization "IANA";
+ contact
+ " Internet Assigned Numbers Authority
+
+ Postal: ICANN
+ 4676 Admiralty Way, Suite 330
+ Marina del Rey, CA 90292
+
+ Tel: +1 310 823 9358
+ <mailto:iana@iana.org>";
+ description
+ "This YANG module defines YANG identities for IANA-registered
+ interface types.
+
+ This YANG module is maintained by IANA and reflects the
+ 'ifType definitions' registry.
+
+ The latest revision of this YANG module can be obtained from
+ the IANA web site.
+
+ Requests for new values should be made to IANA via
+ email (iana@iana.org).
+
+ Copyright (c) 2014 IETF Trust and the persons identified as
+ authors of the code. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or
+ without modification, is permitted pursuant to, and subject
+ to the license terms contained in, the Simplified BSD License
+ set forth in Section 4.c of the IETF Trust's Legal Provisions
+ Relating to IETF Documents
+ (http://trustee.ietf.org/license-info).
+
+ The initial version of this YANG module is part of RFC 7224;
+ see the RFC itself for full legal notices.";
+ reference
+ "IANA 'ifType definitions' registry.
+ <http://www.iana.org/assignments/smi-numbers>";
+
+ revision 2014-05-08 {
+ description
+ "Initial revision.";
+ reference
+ "RFC 7224: IANA Interface Type YANG Module";
+ }
+
+ identity iana-interface-type {
+ base if:interface-type;
+ description
+ "This identity is used as a base for all interface types
+ defined in the 'ifType definitions' registry.";
+ }
+
+
+
+
+
+
+ identity other {
+ base iana-interface-type;
+ }
+ identity regular1822 {
+ base iana-interface-type;
+ }
+ identity hdh1822 {
+ base iana-interface-type;
+ }
+ identity ddnX25 {
+ base iana-interface-type;
+ }
+ identity rfc877x25 {
+ base iana-interface-type;
+ reference
+ "RFC 1382 - SNMP MIB Extension for the X.25 Packet Layer";
+ }
+ identity ethernetCsmacd {
+ base iana-interface-type;
+ description
+ "For all Ethernet-like interfaces, regardless of speed,
+ as per RFC 3635.";
+ reference
+ "RFC 3635 - Definitions of Managed Objects for the
+ Ethernet-like Interface Types";
+ }
+ identity iso88023Csmacd {
+ base iana-interface-type;
+ status deprecated;
+ description
+ "Deprecated via RFC 3635.
+ Use ethernetCsmacd(6) instead.";
+ reference
+ "RFC 3635 - Definitions of Managed Objects for the
+ Ethernet-like Interface Types";
+ }
+ identity iso88024TokenBus {
+ base iana-interface-type;
+ }
+ identity iso88025TokenRing {
+ base iana-interface-type;
+ }
+ identity iso88026Man {
+ base iana-interface-type;
+ }
+ identity starLan {
+ base iana-interface-type;
+ status deprecated;
+ description
+ "Deprecated via RFC 3635.
+ Use ethernetCsmacd(6) instead.";
+ reference
+ "RFC 3635 - Definitions of Managed Objects for the
+ Ethernet-like Interface Types";
+ }
+ identity proteon10Mbit {
+ base iana-interface-type;
+ }
+ identity proteon80Mbit {
+ base iana-interface-type;
+ }
+ identity hyperchannel {
+ base iana-interface-type;
+ }
+ identity fddi {
+ base iana-interface-type;
+ reference
+ "RFC 1512 - FDDI Management Information Base";
+ }
+ identity lapb {
+ base iana-interface-type;
+ reference
+ "RFC 1381 - SNMP MIB Extension for X.25 LAPB";
+ }
+ identity sdlc {
+ base iana-interface-type;
+ }
+ identity ds1 {
+ base iana-interface-type;
+ description
+ "DS1-MIB.";
+ reference
+ "RFC 4805 - Definitions of Managed Objects for the
+ DS1, J1, E1, DS2, and E2 Interface Types";
+ }
+ identity e1 {
+ base iana-interface-type;
+ status obsolete;
+ description
+ "Obsolete; see DS1-MIB.";
+ reference
+ "RFC 4805 - Definitions of Managed Objects for the
+ DS1, J1, E1, DS2, and E2 Interface Types";
+ }
+
+
+ identity basicISDN {
+ base iana-interface-type;
+ description
+ "No longer used. See also RFC 2127.";
+ }
+ identity primaryISDN {
+ base iana-interface-type;
+ description
+ "No longer used. See also RFC 2127.";
+ }
+ identity propPointToPointSerial {
+ base iana-interface-type;
+ description
+ "Proprietary serial.";
+ }
+ identity ppp {
+ base iana-interface-type;
+ }
+ identity softwareLoopback {
+ base iana-interface-type;
+ }
+ identity eon {
+ base iana-interface-type;
+ description
+ "CLNP over IP.";
+ }
+ identity ethernet3Mbit {
+ base iana-interface-type;
+ }
+ identity nsip {
+ base iana-interface-type;
+ description
+ "XNS over IP.";
+ }
+ identity slip {
+ base iana-interface-type;
+ description
+ "Generic SLIP.";
+ }
+ identity ultra {
+ base iana-interface-type;
+ description
+ "Ultra Technologies.";
+ }
+ identity ds3 {
+ base iana-interface-type;
+ description
+ "DS3-MIB.";
+ reference
+ "RFC 3896 - Definitions of Managed Objects for the
+ DS3/E3 Interface Type";
+ }
+ identity sip {
+ base iana-interface-type;
+ description
+ "SMDS, coffee.";
+ reference
+ "RFC 1694 - Definitions of Managed Objects for SMDS
+ Interfaces using SMIv2";
+ }
+ identity frameRelay {
+ base iana-interface-type;
+ description
+ "DTE only.";
+ reference
+ "RFC 2115 - Management Information Base for Frame Relay
+ DTEs Using SMIv2";
+ }
+ identity rs232 {
+ base iana-interface-type;
+ reference
+ "RFC 1659 - Definitions of Managed Objects for RS-232-like
+ Hardware Devices using SMIv2";
+ }
+ identity para {
+ base iana-interface-type;
+ description
+ "Parallel-port.";
+ reference
+ "RFC 1660 - Definitions of Managed Objects for
+ Parallel-printer-like Hardware Devices using
+ SMIv2";
+ }
+ identity arcnet {
+ base iana-interface-type;
+ description
+ "ARCnet.";
+ }
+ identity arcnetPlus {
+ base iana-interface-type;
+ description
+ "ARCnet Plus.";
+ }
+
+
+
+ identity atm {
+ base iana-interface-type;
+ description
+ "ATM cells.";
+ }
+ identity miox25 {
+ base iana-interface-type;
+ reference
+ "RFC 1461 - SNMP MIB extension for Multiprotocol
+ Interconnect over X.25";
+ }
+ identity sonet {
+ base iana-interface-type;
+ description
+ "SONET or SDH.";
+ }
+ identity x25ple {
+ base iana-interface-type;
+ reference
+ "RFC 2127 - ISDN Management Information Base using SMIv2";
+ }
+ identity iso88022llc {
+ base iana-interface-type;
+ }
+ identity localTalk {
+ base iana-interface-type;
+ }
+ identity smdsDxi {
+ base iana-interface-type;
+ }
+ identity frameRelayService {
+ base iana-interface-type;
+ description
+ "FRNETSERV-MIB.";
+ reference
+ "RFC 2954 - Definitions of Managed Objects for Frame
+ Relay Service";
+ }
+ identity v35 {
+ base iana-interface-type;
+ }
+ identity hssi {
+ base iana-interface-type;
+ }
+ identity hippi {
+ base iana-interface-type;
+ }
+
+ identity modem {
+ base iana-interface-type;
+ description
+ "Generic modem.";
+ }
+ identity aal5 {
+ base iana-interface-type;
+ description
+ "AAL5 over ATM.";
+ }
+ identity sonetPath {
+ base iana-interface-type;
+ }
+ identity sonetVT {
+ base iana-interface-type;
+ }
+ identity smdsIcip {
+ base iana-interface-type;
+ description
+ "SMDS InterCarrier Interface.";
+ }
+ identity propVirtual {
+ base iana-interface-type;
+ description
+ "Proprietary virtual/internal.";
+ reference
+ "RFC 2863 - The Interfaces Group MIB";
+ }
+ identity propMultiplexor {
+ base iana-interface-type;
+ description
+ "Proprietary multiplexing.";
+ reference
+ "RFC 2863 - The Interfaces Group MIB";
+ }
+ identity ieee80212 {
+ base iana-interface-type;
+ description
+ "100BaseVG.";
+ }
+ identity fibreChannel {
+ base iana-interface-type;
+ description
+ "Fibre Channel.";
+ }
+
+
+
+ identity hippiInterface {
+ base iana-interface-type;
+ description
+ "HIPPI interfaces.";
+ }
+ identity frameRelayInterconnect {
+ base iana-interface-type;
+ status obsolete;
+ description
+ "Obsolete; use either
+ frameRelay(32) or frameRelayService(44).";
+ }
+ identity aflane8023 {
+ base iana-interface-type;
+ description
+ "ATM Emulated LAN for 802.3.";
+ }
+ identity aflane8025 {
+ base iana-interface-type;
+ description
+ "ATM Emulated LAN for 802.5.";
+ }
+ identity cctEmul {
+ base iana-interface-type;
+ description
+ "ATM Emulated circuit.";
+ }
+ identity fastEther {
+ base iana-interface-type;
+ status deprecated;
+ description
+ "Obsoleted via RFC 3635.
+ ethernetCsmacd(6) should be used instead.";
+ reference
+ "RFC 3635 - Definitions of Managed Objects for the
+ Ethernet-like Interface Types";
+ }
+ identity isdn {
+ base iana-interface-type;
+ description
+ "ISDN and X.25.";
+ reference
+ "RFC 1356 - Multiprotocol Interconnect on X.25 and ISDN
+ in the Packet Mode";
+ }
+
+
+
+ identity v11 {
+ base iana-interface-type;
+ description
+ "CCITT V.11/X.21.";
+ }
+ identity v36 {
+ base iana-interface-type;
+ description
+ "CCITT V.36.";
+ }
+ identity g703at64k {
+ base iana-interface-type;
+ description
+ "CCITT G703 at 64Kbps.";
+ }
+ identity g703at2mb {
+ base iana-interface-type;
+ status obsolete;
+ description
+ "Obsolete; see DS1-MIB.";
+ }
+ identity qllc {
+ base iana-interface-type;
+ description
+ "SNA QLLC.";
+ }
+ identity fastEtherFX {
+ base iana-interface-type;
+ status deprecated;
+ description
+ "Obsoleted via RFC 3635.
+ ethernetCsmacd(6) should be used instead.";
+ reference
+ "RFC 3635 - Definitions of Managed Objects for the
+ Ethernet-like Interface Types";
+ }
+ identity channel {
+ base iana-interface-type;
+ description
+ "Channel.";
+ }
+ identity ieee80211 {
+ base iana-interface-type;
+ description
+ "Radio spread spectrum.";
+ }
+ identity ibm370parChan {
+ base iana-interface-type;
+ description
+ "IBM System 360/370 OEMI Channel.";
+ }
+ identity escon {
+ base iana-interface-type;
+ description
+ "IBM Enterprise Systems Connection.";
+ }
+ identity dlsw {
+ base iana-interface-type;
+ description
+ "Data Link Switching.";
+ }
+ identity isdns {
+ base iana-interface-type;
+ description
+ "ISDN S/T interface.";
+ }
+ identity isdnu {
+ base iana-interface-type;
+ description
+ "ISDN U interface.";
+ }
+ identity lapd {
+ base iana-interface-type;
+ description
+ "Link Access Protocol D.";
+ }
+ identity ipSwitch {
+ base iana-interface-type;
+ description
+ "IP Switching Objects.";
+ }
+ identity rsrb {
+ base iana-interface-type;
+ description
+ "Remote Source Route Bridging.";
+ }
+ identity atmLogical {
+ base iana-interface-type;
+ description
+ "ATM Logical Port.";
+ reference
+ "RFC 3606 - Definitions of Supplemental Managed Objects
+ for ATM Interface";
+ }
+ identity ds0 {
+ base iana-interface-type;
+ description
+ "Digital Signal Level 0.";
+ reference
+ "RFC 2494 - Definitions of Managed Objects for the DS0
+ and DS0 Bundle Interface Type";
+ }
+ identity ds0Bundle {
+ base iana-interface-type;
+ description
+ "Group of ds0s on the same ds1.";
+ reference
+ "RFC 2494 - Definitions of Managed Objects for the DS0
+ and DS0 Bundle Interface Type";
+ }
+ identity bsc {
+ base iana-interface-type;
+ description
+ "Bisynchronous Protocol.";
+ }
+ identity async {
+ base iana-interface-type;
+ description
+ "Asynchronous Protocol.";
+ }
+ identity cnr {
+ base iana-interface-type;
+ description
+ "Combat Net Radio.";
+ }
+ identity iso88025Dtr {
+ base iana-interface-type;
+ description
+ "ISO 802.5r DTR.";
+ }
+ identity eplrs {
+ base iana-interface-type;
+ description
+ "Ext Pos Loc Report Sys.";
+ }
+ identity arap {
+ base iana-interface-type;
+ description
+ "Appletalk Remote Access Protocol.";
+ }
+ identity propCnls {
+ base iana-interface-type;
+ description
+ "Proprietary Connectionless Protocol.";
+ }
+ identity hostPad {
+ base iana-interface-type;
+ description
+ "CCITT-ITU X.29 PAD Protocol.";
+ }
+ identity termPad {
+ base iana-interface-type;
+ description
+ "CCITT-ITU X.3 PAD Facility.";
+ }
+ identity frameRelayMPI {
+ base iana-interface-type;
+ description
+ "Multiproto Interconnect over FR.";
+ }
+ identity x213 {
+ base iana-interface-type;
+ description
+ "CCITT-ITU X213.";
+ }
+ identity adsl {
+ base iana-interface-type;
+ description
+ "Asymmetric Digital Subscriber Loop.";
+ }
+ identity radsl {
+ base iana-interface-type;
+ description
+ "Rate-Adapt. Digital Subscriber Loop.";
+ }
+ identity sdsl {
+ base iana-interface-type;
+ description
+ "Symmetric Digital Subscriber Loop.";
+ }
+ identity vdsl {
+ base iana-interface-type;
+ description
+ "Very H-Speed Digital Subscrib. Loop.";
+ }
+ identity iso88025CRFPInt {
+ base iana-interface-type;
+ description
+ "ISO 802.5 CRFP.";
+ }
+ identity myrinet {
+ base iana-interface-type;
+ description
+ "Myricom Myrinet.";
+ }
+ identity voiceEM {
+ base iana-interface-type;
+ description
+ "Voice recEive and transMit.";
+ }
+ identity voiceFXO {
+ base iana-interface-type;
+ description
+ "Voice Foreign Exchange Office.";
+ }
+ identity voiceFXS {
+ base iana-interface-type;
+ description
+ "Voice Foreign Exchange Station.";
+ }
+ identity voiceEncap {
+ base iana-interface-type;
+ description
+ "Voice encapsulation.";
+ }
+ identity voiceOverIp {
+ base iana-interface-type;
+ description
+ "Voice over IP encapsulation.";
+ }
+ identity atmDxi {
+ base iana-interface-type;
+ description
+ "ATM DXI.";
+ }
+ identity atmFuni {
+ base iana-interface-type;
+ description
+ "ATM FUNI.";
+ }
+ identity atmIma {
+ base iana-interface-type;
+ description
+ "ATM IMA.";
+ }
+ identity pppMultilinkBundle {
+ base iana-interface-type;
+ description
+ "PPP Multilink Bundle.";
+ }
+ identity ipOverCdlc {
+ base iana-interface-type;
+ description
+ "IBM ipOverCdlc.";
+ }
+ identity ipOverClaw {
+ base iana-interface-type;
+ description
+ "IBM Common Link Access to Workstn.";
+ }
+ identity stackToStack {
+ base iana-interface-type;
+ description
+ "IBM stackToStack.";
+ }
+ identity virtualIpAddress {
+ base iana-interface-type;
+ description
+ "IBM VIPA.";
+ }
+ identity mpc {
+ base iana-interface-type;
+ description
+ "IBM multi-protocol channel support.";
+ }
+ identity ipOverAtm {
+ base iana-interface-type;
+ description
+ "IBM ipOverAtm.";
+ reference
+ "RFC 2320 - Definitions of Managed Objects for Classical IP
+ and ARP Over ATM Using SMIv2 (IPOA-MIB)";
+ }
+ identity iso88025Fiber {
+ base iana-interface-type;
+ description
+ "ISO 802.5j Fiber Token Ring.";
+ }
+ identity tdlc {
+ base iana-interface-type;
+ description
+ "IBM twinaxial data link control.";
+ }
+ identity gigabitEthernet {
+ base iana-interface-type;
+ status deprecated;
+
+
+ description
+ "Obsoleted via RFC 3635.
+ ethernetCsmacd(6) should be used instead.";
+ reference
+ "RFC 3635 - Definitions of Managed Objects for the
+ Ethernet-like Interface Types";
+ }
+ identity hdlc {
+ base iana-interface-type;
+ description
+ "HDLC.";
+ }
+ identity lapf {
+ base iana-interface-type;
+ description
+ "LAP F.";
+ }
+ identity v37 {
+ base iana-interface-type;
+ description
+ "V.37.";
+ }
+ identity x25mlp {
+ base iana-interface-type;
+ description
+ "Multi-Link Protocol.";
+ }
+ identity x25huntGroup {
+ base iana-interface-type;
+ description
+ "X25 Hunt Group.";
+ }
+ identity transpHdlc {
+ base iana-interface-type;
+ description
+ "Transp HDLC.";
+ }
+ identity interleave {
+ base iana-interface-type;
+ description
+ "Interleave channel.";
+ }
+ identity fast {
+ base iana-interface-type;
+ description
+ "Fast channel.";
+ }
+
+ identity ip {
+ base iana-interface-type;
+ description
+ "IP (for APPN HPR in IP networks).";
+ }
+ identity docsCableMaclayer {
+ base iana-interface-type;
+ description
+ "CATV Mac Layer.";
+ }
+ identity docsCableDownstream {
+ base iana-interface-type;
+ description
+ "CATV Downstream interface.";
+ }
+ identity docsCableUpstream {
+ base iana-interface-type;
+ description
+ "CATV Upstream interface.";
+ }
+ identity a12MppSwitch {
+ base iana-interface-type;
+ description
+ "Avalon Parallel Processor.";
+ }
+ identity tunnel {
+ base iana-interface-type;
+ description
+ "Encapsulation interface.";
+ }
+ identity coffee {
+ base iana-interface-type;
+ description
+ "Coffee pot.";
+ reference
+ "RFC 2325 - Coffee MIB";
+ }
+ identity ces {
+ base iana-interface-type;
+ description
+ "Circuit Emulation Service.";
+ }
+ identity atmSubInterface {
+ base iana-interface-type;
+ description
+ "ATM Sub Interface.";
+ }
+
+ identity l2vlan {
+ base iana-interface-type;
+ description
+ "Layer 2 Virtual LAN using 802.1Q.";
+ }
+ identity l3ipvlan {
+ base iana-interface-type;
+ description
+ "Layer 3 Virtual LAN using IP.";
+ }
+ identity l3ipxvlan {
+ base iana-interface-type;
+ description
+ "Layer 3 Virtual LAN using IPX.";
+ }
+ identity digitalPowerline {
+ base iana-interface-type;
+ description
+ "IP over Power Lines.";
+ }
+ identity mediaMailOverIp {
+ base iana-interface-type;
+ description
+ "Multimedia Mail over IP.";
+ }
+ identity dtm {
+ base iana-interface-type;
+ description
+ "Dynamic synchronous Transfer Mode.";
+ }
+ identity dcn {
+ base iana-interface-type;
+ description
+ "Data Communications Network.";
+ }
+ identity ipForward {
+ base iana-interface-type;
+ description
+ "IP Forwarding Interface.";
+ }
+ identity msdsl {
+ base iana-interface-type;
+ description
+ "Multi-rate Symmetric DSL.";
+ }
+ identity ieee1394 {
+ base iana-interface-type;
+
+ description
+ "IEEE1394 High Performance Serial Bus.";
+ }
+ identity if-gsn {
+ base iana-interface-type;
+ description
+ "HIPPI-6400.";
+ }
+ identity dvbRccMacLayer {
+ base iana-interface-type;
+ description
+ "DVB-RCC MAC Layer.";
+ }
+ identity dvbRccDownstream {
+ base iana-interface-type;
+ description
+ "DVB-RCC Downstream Channel.";
+ }
+ identity dvbRccUpstream {
+ base iana-interface-type;
+ description
+ "DVB-RCC Upstream Channel.";
+ }
+ identity atmVirtual {
+ base iana-interface-type;
+ description
+ "ATM Virtual Interface.";
+ }
+ identity mplsTunnel {
+ base iana-interface-type;
+ description
+ "MPLS Tunnel Virtual Interface.";
+ }
+ identity srp {
+ base iana-interface-type;
+ description
+ "Spatial Reuse Protocol.";
+ }
+ identity voiceOverAtm {
+ base iana-interface-type;
+ description
+ "Voice over ATM.";
+ }
+ identity voiceOverFrameRelay {
+ base iana-interface-type;
+ description
+ "Voice Over Frame Relay.";
+ }
+ identity idsl {
+ base iana-interface-type;
+ description
+ "Digital Subscriber Loop over ISDN.";
+ }
+ identity compositeLink {
+ base iana-interface-type;
+ description
+ "Avici Composite Link Interface.";
+ }
+ identity ss7SigLink {
+ base iana-interface-type;
+ description
+ "SS7 Signaling Link.";
+ }
+ identity propWirelessP2P {
+ base iana-interface-type;
+ description
+ "Prop. P2P wireless interface.";
+ }
+ identity frForward {
+ base iana-interface-type;
+ description
+ "Frame Forward Interface.";
+ }
+ identity rfc1483 {
+ base iana-interface-type;
+ description
+ "Multiprotocol over ATM AAL5.";
+ reference
+ "RFC 1483 - Multiprotocol Encapsulation over ATM
+ Adaptation Layer 5";
+ }
+ identity usb {
+ base iana-interface-type;
+ description
+ "USB Interface.";
+ }
+ identity ieee8023adLag {
+ base iana-interface-type;
+ description
+ "IEEE 802.3ad Link Aggregate.";
+ }
+ identity bgppolicyaccounting {
+ base iana-interface-type;
+ description
+ "BGP Policy Accounting.";
+ }
+ identity frf16MfrBundle {
+ base iana-interface-type;
+ description
+ "FRF.16 Multilink Frame Relay.";
+ }
+ identity h323Gatekeeper {
+ base iana-interface-type;
+ description
+ "H323 Gatekeeper.";
+ }
+ identity h323Proxy {
+ base iana-interface-type;
+ description
+ "H323 Voice and Video Proxy.";
+ }
+ identity mpls {
+ base iana-interface-type;
+ description
+ "MPLS.";
+ }
+ identity mfSigLink {
+ base iana-interface-type;
+ description
+ "Multi-frequency signaling link.";
+ }
+ identity hdsl2 {
+ base iana-interface-type;
+ description
+ "High Bit-Rate DSL - 2nd generation.";
+ }
+ identity shdsl {
+ base iana-interface-type;
+ description
+ "Multirate HDSL2.";
+ }
+ identity ds1FDL {
+ base iana-interface-type;
+ description
+ "Facility Data Link (4Kbps) on a DS1.";
+ }
+ identity pos {
+ base iana-interface-type;
+ description
+ "Packet over SONET/SDH Interface.";
+ }
+
+
+
+ identity dvbAsiIn {
+ base iana-interface-type;
+ description
+ "DVB-ASI Input.";
+ }
+ identity dvbAsiOut {
+ base iana-interface-type;
+ description
+ "DVB-ASI Output.";
+ }
+ identity plc {
+ base iana-interface-type;
+ description
+ "Power Line Communications.";
+ }
+ identity nfas {
+ base iana-interface-type;
+ description
+ "Non-Facility Associated Signaling.";
+ }
+ identity tr008 {
+ base iana-interface-type;
+ description
+ "TR008.";
+ }
+ identity gr303RDT {
+ base iana-interface-type;
+ description
+ "Remote Digital Terminal.";
+ }
+ identity gr303IDT {
+ base iana-interface-type;
+ description
+ "Integrated Digital Terminal.";
+ }
+ identity isup {
+ base iana-interface-type;
+ description
+ "ISUP.";
+ }
+ identity propDocsWirelessMaclayer {
+ base iana-interface-type;
+ description
+ "Cisco proprietary Maclayer.";
+ }
+
+
+
+ identity propDocsWirelessDownstream {
+ base iana-interface-type;
+ description
+ "Cisco proprietary Downstream.";
+ }
+ identity propDocsWirelessUpstream {
+ base iana-interface-type;
+ description
+ "Cisco proprietary Upstream.";
+ }
+ identity hiperlan2 {
+ base iana-interface-type;
+ description
+ "HIPERLAN Type 2 Radio Interface.";
+ }
+ identity propBWAp2Mp {
+ base iana-interface-type;
+ description
+ "PropBroadbandWirelessAccesspt2Multipt (use of this value
+ for IEEE 802.16 WMAN interfaces as per IEEE Std 802.16f
+ is deprecated, and ieee80216WMAN(237) should be used
+ instead).";
+ }
+ identity sonetOverheadChannel {
+ base iana-interface-type;
+ description
+ "SONET Overhead Channel.";
+ }
+ identity digitalWrapperOverheadChannel {
+ base iana-interface-type;
+ description
+ "Digital Wrapper.";
+ }
+ identity aal2 {
+ base iana-interface-type;
+ description
+ "ATM adaptation layer 2.";
+ }
+ identity radioMAC {
+ base iana-interface-type;
+ description
+ "MAC layer over radio links.";
+ }
+ identity atmRadio {
+ base iana-interface-type;
+ description
+ "ATM over radio links.";
+ }
+ identity imt {
+ base iana-interface-type;
+ description
+ "Inter-Machine Trunks.";
+ }
+ identity mvl {
+ base iana-interface-type;
+ description
+ "Multiple Virtual Lines DSL.";
+ }
+ identity reachDSL {
+ base iana-interface-type;
+ description
+ "Long Reach DSL.";
+ }
+ identity frDlciEndPt {
+ base iana-interface-type;
+ description
+ "Frame Relay DLCI End Point.";
+ }
+ identity atmVciEndPt {
+ base iana-interface-type;
+ description
+ "ATM VCI End Point.";
+ }
+ identity opticalChannel {
+ base iana-interface-type;
+ description
+ "Optical Channel.";
+ }
+ identity opticalTransport {
+ base iana-interface-type;
+ description
+ "Optical Transport.";
+ }
+ identity propAtm {
+ base iana-interface-type;
+ description
+ "Proprietary ATM.";
+ }
+ identity voiceOverCable {
+ base iana-interface-type;
+ description
+ "Voice Over Cable Interface.";
+ }
+
+
+
+ identity infiniband {
+ base iana-interface-type;
+ description
+ "Infiniband.";
+ }
+ identity teLink {
+ base iana-interface-type;
+ description
+ "TE Link.";
+ }
+ identity q2931 {
+ base iana-interface-type;
+ description
+ "Q.2931.";
+ }
+ identity virtualTg {
+ base iana-interface-type;
+ description
+ "Virtual Trunk Group.";
+ }
+ identity sipTg {
+ base iana-interface-type;
+ description
+ "SIP Trunk Group.";
+ }
+ identity sipSig {
+ base iana-interface-type;
+ description
+ "SIP Signaling.";
+ }
+ identity docsCableUpstreamChannel {
+ base iana-interface-type;
+ description
+ "CATV Upstream Channel.";
+ }
+ identity econet {
+ base iana-interface-type;
+ description
+ "Acorn Econet.";
+ }
+ identity pon155 {
+ base iana-interface-type;
+ description
+ "FSAN 155Mb Symetrical PON interface.";
+ }
+
+
+
+ identity pon622 {
+ base iana-interface-type;
+ description
+ "FSAN 622Mb Symetrical PON interface.";
+ }
+ identity bridge {
+ base iana-interface-type;
+ description
+ "Transparent bridge interface.";
+ }
+ identity linegroup {
+ base iana-interface-type;
+ description
+ "Interface common to multiple lines.";
+ }
+ identity voiceEMFGD {
+ base iana-interface-type;
+ description
+ "Voice E&M Feature Group D.";
+ }
+ identity voiceFGDEANA {
+ base iana-interface-type;
+ description
+ "Voice FGD Exchange Access North American.";
+ }
+ identity voiceDID {
+ base iana-interface-type;
+ description
+ "Voice Direct Inward Dialing.";
+ }
+ identity mpegTransport {
+ base iana-interface-type;
+ description
+ "MPEG transport interface.";
+ }
+ identity sixToFour {
+ base iana-interface-type;
+ status deprecated;
+ description
+ "6to4 interface (DEPRECATED).";
+ reference
+ "RFC 4087 - IP Tunnel MIB";
+ }
+ identity gtp {
+ base iana-interface-type;
+ description
+ "GTP (GPRS Tunneling Protocol).";
+ }
+ identity pdnEtherLoop1 {
+ base iana-interface-type;
+ description
+ "Paradyne EtherLoop 1.";
+ }
+ identity pdnEtherLoop2 {
+ base iana-interface-type;
+ description
+ "Paradyne EtherLoop 2.";
+ }
+ identity opticalChannelGroup {
+ base iana-interface-type;
+ description
+ "Optical Channel Group.";
+ }
+ identity homepna {
+ base iana-interface-type;
+ description
+ "HomePNA ITU-T G.989.";
+ }
+ identity gfp {
+ base iana-interface-type;
+ description
+ "Generic Framing Procedure (GFP).";
+ }
+ identity ciscoISLvlan {
+ base iana-interface-type;
+ description
+ "Layer 2 Virtual LAN using Cisco ISL.";
+ }
+ identity actelisMetaLOOP {
+ base iana-interface-type;
+ description
+ "Acteleis proprietary MetaLOOP High Speed Link.";
+ }
+ identity fcipLink {
+ base iana-interface-type;
+ description
+ "FCIP Link.";
+ }
+ identity rpr {
+ base iana-interface-type;
+ description
+ "Resilient Packet Ring Interface Type.";
+ }
+
+
+
+ identity qam {
+ base iana-interface-type;
+ description
+ "RF Qam Interface.";
+ }
+ identity lmp {
+ base iana-interface-type;
+ description
+ "Link Management Protocol.";
+ reference
+ "RFC 4327 - Link Management Protocol (LMP) Management
+ Information Base (MIB)";
+ }
+ identity cblVectaStar {
+ base iana-interface-type;
+ description
+ "Cambridge Broadband Networks Limited VectaStar.";
+ }
+ identity docsCableMCmtsDownstream {
+ base iana-interface-type;
+ description
+ "CATV Modular CMTS Downstream Interface.";
+ }
+ identity adsl2 {
+ base iana-interface-type;
+ status deprecated;
+ description
+ "Asymmetric Digital Subscriber Loop Version 2
+ (DEPRECATED/OBSOLETED - please use adsl2plus(238)
+ instead).";
+ reference
+ "RFC 4706 - Definitions of Managed Objects for Asymmetric
+ Digital Subscriber Line 2 (ADSL2)";
+ }
+ identity macSecControlledIF {
+ base iana-interface-type;
+ description
+ "MACSecControlled.";
+ }
+ identity macSecUncontrolledIF {
+ base iana-interface-type;
+ description
+ "MACSecUncontrolled.";
+ }
+ identity aviciOpticalEther {
+ base iana-interface-type;
+ description
+ "Avici Optical Ethernet Aggregate.";
+ }
+ identity atmbond {
+ base iana-interface-type;
+ description
+ "atmbond.";
+ }
+ identity voiceFGDOS {
+ base iana-interface-type;
+ description
+ "Voice FGD Operator Services.";
+ }
+ identity mocaVersion1 {
+ base iana-interface-type;
+ description
+ "MultiMedia over Coax Alliance (MoCA) Interface
+ as documented in information provided privately to IANA.";
+ }
+ identity ieee80216WMAN {
+ base iana-interface-type;
+ description
+ "IEEE 802.16 WMAN interface.";
+ }
+ identity adsl2plus {
+ base iana-interface-type;
+ description
+ "Asymmetric Digital Subscriber Loop Version 2 -
+ Version 2 Plus and all variants.";
+ }
+ identity dvbRcsMacLayer {
+ base iana-interface-type;
+ description
+ "DVB-RCS MAC Layer.";
+ reference
+ "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+ }
+ identity dvbTdm {
+ base iana-interface-type;
+ description
+ "DVB Satellite TDM.";
+ reference
+ "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+ }
+ identity dvbRcsTdma {
+ base iana-interface-type;
+ description
+ "DVB-RCS TDMA.";
+ reference
+ "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+ }
+ identity x86Laps {
+ base iana-interface-type;
+ description
+ "LAPS based on ITU-T X.86/Y.1323.";
+ }
+ identity wwanPP {
+ base iana-interface-type;
+ description
+ "3GPP WWAN.";
+ }
+ identity wwanPP2 {
+ base iana-interface-type;
+ description
+ "3GPP2 WWAN.";
+ }
+ identity voiceEBS {
+ base iana-interface-type;
+ description
+ "Voice P-phone EBS physical interface.";
+ }
+ identity ifPwType {
+ base iana-interface-type;
+ description
+ "Pseudowire interface type.";
+ reference
+ "RFC 5601 - Pseudowire (PW) Management Information Base (MIB)";
+ }
+ identity ilan {
+ base iana-interface-type;
+ description
+ "Internal LAN on a bridge per IEEE 802.1ap.";
+ }
+ identity pip {
+ base iana-interface-type;
+ description
+ "Provider Instance Port on a bridge per IEEE 802.1ah PBB.";
+ }
+ identity aluELP {
+ base iana-interface-type;
+ description
+ "Alcatel-Lucent Ethernet Link Protection.";
+ }
+ identity gpon {
+ base iana-interface-type;
+ description
+ "Gigabit-capable passive optical networks (G-PON) as per
+ ITU-T G.948.";
+ }
+ identity vdsl2 {
+ base iana-interface-type;
+ description
+ "Very high speed digital subscriber line Version 2
+ (as per ITU-T Recommendation G.993.2).";
+ reference
+ "RFC 5650 - Definitions of Managed Objects for Very High
+ Speed Digital Subscriber Line 2 (VDSL2)";
+ }
+ identity capwapDot11Profile {
+ base iana-interface-type;
+ description
+ "WLAN Profile Interface.";
+ reference
+ "RFC 5834 - Control and Provisioning of Wireless Access
+ Points (CAPWAP) Protocol Binding MIB for
+ IEEE 802.11";
+ }
+ identity capwapDot11Bss {
+ base iana-interface-type;
+ description
+ "WLAN BSS Interface.";
+ reference
+ "RFC 5834 - Control and Provisioning of Wireless Access
+ Points (CAPWAP) Protocol Binding MIB for
+ IEEE 802.11";
+ }
+ identity capwapWtpVirtualRadio {
+ base iana-interface-type;
+ description
+ "WTP Virtual Radio Interface.";
+ reference
+ "RFC 5833 - Control and Provisioning of Wireless Access
+ Points (CAPWAP) Protocol Base MIB";
+ }
+ identity bits {
+ base iana-interface-type;
+ description
+ "bitsport.";
+ }
+ identity docsCableUpstreamRfPort {
+ base iana-interface-type;
+ description
+ "DOCSIS CATV Upstream RF Port.";
+ }
+
+
+ identity cableDownstreamRfPort {
+ base iana-interface-type;
+ description
+ "CATV downstream RF Port.";
+ }
+ identity vmwareVirtualNic {
+ base iana-interface-type;
+ description
+ "VMware Virtual Network Interface.";
+ }
+ identity ieee802154 {
+ base iana-interface-type;
+ description
+ "IEEE 802.15.4 WPAN interface.";
+ reference
+ "IEEE 802.15.4-2006";
+ }
+ identity otnOdu {
+ base iana-interface-type;
+ description
+ "OTN Optical Data Unit.";
+ }
+ identity otnOtu {
+ base iana-interface-type;
+ description
+ "OTN Optical channel Transport Unit.";
+ }
+ identity ifVfiType {
+ base iana-interface-type;
+ description
+ "VPLS Forwarding Instance Interface Type.";
+ }
+ identity g9981 {
+ base iana-interface-type;
+ description
+ "G.998.1 bonded interface.";
+ }
+ identity g9982 {
+ base iana-interface-type;
+ description
+ "G.998.2 bonded interface.";
+ }
+ identity g9983 {
+ base iana-interface-type;
+ description
+ "G.998.3 bonded interface.";
+ }
+
+ identity aluEpon {
+ base iana-interface-type;
+ description
+ "Ethernet Passive Optical Networks (E-PON).";
+ }
+ identity aluEponOnu {
+ base iana-interface-type;
+ description
+ "EPON Optical Network Unit.";
+ }
+ identity aluEponPhysicalUni {
+ base iana-interface-type;
+ description
+ "EPON physical User to Network interface.";
+ }
+ identity aluEponLogicalLink {
+ base iana-interface-type;
+ description
+ "The emulation of a point-to-point link over the EPON
+ layer.";
+ }
+ identity aluGponOnu {
+ base iana-interface-type;
+ description
+ "GPON Optical Network Unit.";
+ reference
+ "ITU-T G.984.2";
+ }
+ identity aluGponPhysicalUni {
+ base iana-interface-type;
+ description
+ "GPON physical User to Network interface.";
+ reference
+ "ITU-T G.984.2";
+ }
+ identity vmwareNicTeam {
+ base iana-interface-type;
+ description
+ "VMware NIC Team.";
+ }
+}
<modules>
<module>iana-afn-safi</module>
<module>iana-if-type</module>
+ <module>iana-if-type-2014-05-08</module>
<!--
<module>ietf-topology-l3-unicast-igp</module>
<module>ietf-topology-isis</module>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+
+ This program and the accompanying materials are made available under the
+ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ and is available at http://www.eclipse.org/legal/epl-v10.html
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <parent>
+ <artifactId>model-ietf</artifactId>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <version>0.7.0-SNAPSHOT</version>
+ </parent>
+
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>ietf-interfaces</artifactId>
+ <version>2014.05.08.7-SNAPSHOT</version>
+ <name>${project.artifactId}</name>
+ <description>${project.artifactId}</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-inet-types</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-yang-types</artifactId>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
+ </instructions>
+ </configuration>
+ </plugin>
+
+ </plugins>
+ </build>
+
+</project>
--- /dev/null
+module ietf-interfaces {
+
+ namespace "urn:ietf:params:xml:ns:yang:ietf-interfaces";
+ prefix if;
+
+ import ietf-yang-types {
+ prefix yang;
+ }
+
+ organization
+ "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+ contact
+ "WG Web: <http://tools.ietf.org/wg/netmod/>
+ WG List: <mailto:netmod@ietf.org>
+
+ WG Chair: Thomas Nadeau
+ <mailto:tnadeau@lucidvision.com>
+
+ WG Chair: Juergen Schoenwaelder
+ <mailto:j.schoenwaelder@jacobs-university.de>
+
+ Editor: Martin Bjorklund
+ <mailto:mbj@tail-f.com>";
+
+ description
+ "This module contains a collection of YANG definitions for
+ managing network interfaces.
+
+ Copyright (c) 2014 IETF Trust and the persons identified as
+ authors of the code. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or
+ without modification, is permitted pursuant to, and subject
+ to the license terms contained in, the Simplified BSD License
+ set forth in Section 4.c of the IETF Trust's Legal Provisions
+ Relating to IETF Documents
+ (http://trustee.ietf.org/license-info).
+
+ This version of this YANG module is part of RFC 7223; see
+ the RFC itself for full legal notices.";
+
+ revision 2014-05-08 {
+ description
+ "Initial revision.";
+ reference
+ "RFC 7223: A YANG Data Model for Interface Management";
+ }
+
+ /*
+ * Typedefs
+ */
+
+ typedef interface-ref {
+ type leafref {
+ path "/if:interfaces/if:interface/if:name";
+ }
+ description
+ "This type is used by data models that need to reference
+ configured interfaces.";
+ }
+
+ typedef interface-state-ref {
+ type leafref {
+ path "/if:interfaces-state/if:interface/if:name";
+ }
+ description
+ "This type is used by data models that need to reference
+ the operationally present interfaces.";
+ }
+
+ /*
+ * Identities
+ */
+
+ identity interface-type {
+ description
+ "Base identity from which specific interface types are
+ derived.";
+ }
+
+ /*
+ * Features
+ */
+
+ feature arbitrary-names {
+ description
+ "This feature indicates that the device allows user-controlled
+ interfaces to be named arbitrarily.";
+ }
+ feature pre-provisioning {
+ description
+ "This feature indicates that the device supports
+ pre-provisioning of interface configuration, i.e., it is
+ possible to configure an interface whose physical interface
+ hardware is not present on the device.";
+ }
+
+ feature if-mib {
+ description
+ "This feature indicates that the device implements
+ the IF-MIB.";
+ reference
+ "RFC 2863: The Interfaces Group MIB";
+ }
+
+ /*
+ * Configuration data nodes
+ */
+
+ container interfaces {
+ description
+ "Interface configuration parameters.";
+
+ list interface {
+ key "name";
+
+ description
+ "The list of configured interfaces on the device.
+
+ The operational state of an interface is available in the
+ /interfaces-state/interface list. If the configuration of a
+ system-controlled interface cannot be used by the system
+ (e.g., the interface hardware present does not match the
+ interface type), then the configuration is not applied to
+ the system-controlled interface shown in the
+ /interfaces-state/interface list. If the configuration
+ of a user-controlled interface cannot be used by the system,
+ the configured interface is not instantiated in the
+ /interfaces-state/interface list.";
+
+ leaf name {
+ type string;
+ description
+ "The name of the interface.
+
+ A device MAY restrict the allowed values for this leaf,
+ possibly depending on the type of the interface.
+ For system-controlled interfaces, this leaf is the
+ device-specific name of the interface. The 'config false'
+ list /interfaces-state/interface contains the currently
+ existing interfaces on the device.
+
+ If a client tries to create configuration for a
+ system-controlled interface that is not present in the
+ /interfaces-state/interface list, the server MAY reject
+ the request if the implementation does not support
+ pre-provisioning of interfaces or if the name refers to
+ an interface that can never exist in the system. A
+ NETCONF server MUST reply with an rpc-error with the
+ error-tag 'invalid-value' in this case.
+
+ If the device supports pre-provisioning of interface
+ configuration, the 'pre-provisioning' feature is
+ advertised.
+
+ If the device allows arbitrarily named user-controlled
+ interfaces, the 'arbitrary-names' feature is advertised.
+
+ When a configured user-controlled interface is created by
+ the system, it is instantiated with the same name in the
+ /interface-state/interface list.";
+ }
+
+ leaf description {
+ type string;
+ description
+ "A textual description of the interface.
+
+ A server implementation MAY map this leaf to the ifAlias
+ MIB object. Such an implementation needs to use some
+ mechanism to handle the differences in size and characters
+ allowed between this leaf and ifAlias. The definition of
+ such a mechanism is outside the scope of this document.
+
+ Since ifAlias is defined to be stored in non-volatile
+ storage, the MIB implementation MUST map ifAlias to the
+ value of 'description' in the persistently stored
+ datastore.
+
+ Specifically, if the device supports ':startup', when
+ ifAlias is read the device MUST return the value of
+ 'description' in the 'startup' datastore, and when it is
+ written, it MUST be written to the 'running' and 'startup'
+ datastores. Note that it is up to the implementation to
+
+ decide whether to modify this single leaf in 'startup' or
+ perform an implicit copy-config from 'running' to
+ 'startup'.
+
+ If the device does not support ':startup', ifAlias MUST
+ be mapped to the 'description' leaf in the 'running'
+ datastore.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifAlias";
+ }
+
+ leaf type {
+ type identityref {
+ base interface-type;
+ }
+ mandatory true;
+ description
+ "The type of the interface.
+
+ When an interface entry is created, a server MAY
+ initialize the type leaf with a valid value, e.g., if it
+ is possible to derive the type from the name of the
+ interface.
+
+ If a client tries to set the type of an interface to a
+ value that can never be used by the system, e.g., if the
+ type is not supported or if the type does not match the
+ name of the interface, the server MUST reject the request.
+ A NETCONF server MUST reply with an rpc-error with the
+ error-tag 'invalid-value' in this case.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifType";
+ }
+
+ leaf enabled {
+ type boolean;
+ default "true";
+ description
+ "This leaf contains the configured, desired state of the
+ interface.
+
+ Systems that implement the IF-MIB use the value of this
+ leaf in the 'running' datastore to set
+ IF-MIB.ifAdminStatus to 'up' or 'down' after an ifEntry
+ has been initialized, as described in RFC 2863.
+
+
+
+ Changes in this leaf in the 'running' datastore are
+ reflected in ifAdminStatus, but if ifAdminStatus is
+ changed over SNMP, this leaf is not affected.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifAdminStatus";
+ }
+
+ leaf link-up-down-trap-enable {
+ if-feature if-mib;
+ type enumeration {
+ enum enabled {
+ value 1;
+ }
+ enum disabled {
+ value 2;
+ }
+ }
+ description
+ "Controls whether linkUp/linkDown SNMP notifications
+ should be generated for this interface.
+
+ If this node is not configured, the value 'enabled' is
+ operationally used by the server for interfaces that do
+ not operate on top of any other interface (i.e., there are
+ no 'lower-layer-if' entries), and 'disabled' otherwise.";
+ reference
+ "RFC 2863: The Interfaces Group MIB -
+ ifLinkUpDownTrapEnable";
+ }
+ }
+ }
+
+ /*
+ * Operational state data nodes
+ */
+
+ container interfaces-state {
+ config false;
+ description
+ "Data nodes for the operational state of interfaces.";
+
+ list interface {
+ key "name";
+
+
+
+
+
+ description
+ "The list of interfaces on the device.
+
+ System-controlled interfaces created by the system are
+ always present in this list, whether they are configured or
+ not.";
+
+ leaf name {
+ type string;
+ description
+ "The name of the interface.
+
+ A server implementation MAY map this leaf to the ifName
+ MIB object. Such an implementation needs to use some
+ mechanism to handle the differences in size and characters
+ allowed between this leaf and ifName. The definition of
+ such a mechanism is outside the scope of this document.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifName";
+ }
+
+ leaf type {
+ type identityref {
+ base interface-type;
+ }
+ mandatory true;
+ description
+ "The type of the interface.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifType";
+ }
+
+ leaf admin-status {
+ if-feature if-mib;
+ type enumeration {
+ enum up {
+ value 1;
+ description
+ "Ready to pass packets.";
+ }
+ enum down {
+ value 2;
+ description
+ "Not ready to pass packets and not in some test mode.";
+ }
+
+
+
+ enum testing {
+ value 3;
+ description
+ "In some test mode.";
+ }
+ }
+ mandatory true;
+ description
+ "The desired state of the interface.
+
+ This leaf has the same read semantics as ifAdminStatus.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifAdminStatus";
+ }
+
+ leaf oper-status {
+ type enumeration {
+ enum up {
+ value 1;
+ description
+ "Ready to pass packets.";
+ }
+ enum down {
+ value 2;
+ description
+ "The interface does not pass any packets.";
+ }
+ enum testing {
+ value 3;
+ description
+ "In some test mode. No operational packets can
+ be passed.";
+ }
+ enum unknown {
+ value 4;
+ description
+ "Status cannot be determined for some reason.";
+ }
+ enum dormant {
+ value 5;
+ description
+ "Waiting for some external event.";
+ }
+ enum not-present {
+ value 6;
+ description
+ "Some component (typically hardware) is missing.";
+ }
+ enum lower-layer-down {
+ value 7;
+ description
+ "Down due to state of lower-layer interface(s).";
+ }
+ }
+ mandatory true;
+ description
+ "The current operational state of the interface.
+
+ This leaf has the same semantics as ifOperStatus.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifOperStatus";
+ }
+
+ leaf last-change {
+ type yang:date-and-time;
+ description
+ "The time the interface entered its current operational
+ state. If the current state was entered prior to the
+ last re-initialization of the local network management
+ subsystem, then this node is not present.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifLastChange";
+ }
+
+ leaf if-index {
+ if-feature if-mib;
+ type int32 {
+ range "1..2147483647";
+ }
+ mandatory true;
+ description
+ "The ifIndex value for the ifEntry represented by this
+ interface.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifIndex";
+ }
+
+ leaf phys-address {
+ type yang:phys-address;
+ description
+ "The interface's address at its protocol sub-layer. For
+ example, for an 802.x interface, this object normally
+ contains a Media Access Control (MAC) address. The
+ interface's media-specific modules must define the bit
+
+
+ and byte ordering and the format of the value of this
+ object. For interfaces that do not have such an address
+ (e.g., a serial line), this node is not present.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifPhysAddress";
+ }
+
+ leaf-list higher-layer-if {
+ type interface-state-ref;
+ description
+ "A list of references to interfaces layered on top of this
+ interface.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifStackTable";
+ }
+
+ leaf-list lower-layer-if {
+ type interface-state-ref;
+ description
+ "A list of references to interfaces layered underneath this
+ interface.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifStackTable";
+ }
+
+ leaf speed {
+ type yang:gauge64;
+ units "bits/second";
+ description
+ "An estimate of the interface's current bandwidth in bits
+ per second. For interfaces that do not vary in
+ bandwidth or for those where no accurate estimation can
+ be made, this node should contain the nominal bandwidth.
+ For interfaces that have no concept of bandwidth, this
+ node is not present.";
+ reference
+ "RFC 2863: The Interfaces Group MIB -
+ ifSpeed, ifHighSpeed";
+ }
+
+
+
+
+
+
+
+
+
+ container statistics {
+ description
+ "A collection of interface-related statistics objects.";
+
+ leaf discontinuity-time {
+ type yang:date-and-time;
+ mandatory true;
+ description
+ "The time on the most recent occasion at which any one or
+ more of this interface's counters suffered a
+ discontinuity. If no such discontinuities have occurred
+ since the last re-initialization of the local management
+ subsystem, then this node contains the time the local
+ management subsystem re-initialized itself.";
+ }
+
+ leaf in-octets {
+ type yang:counter64;
+ description
+ "The total number of octets received on the interface,
+ including framing characters.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifHCInOctets";
+ }
+
+ leaf in-unicast-pkts {
+ type yang:counter64;
+ description
+ "The number of packets, delivered by this sub-layer to a
+ higher (sub-)layer, that were not addressed to a
+ multicast or broadcast address at this sub-layer.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifHCInUcastPkts";
+ }
+
+
+
+
+ leaf in-broadcast-pkts {
+ type yang:counter64;
+ description
+ "The number of packets, delivered by this sub-layer to a
+ higher (sub-)layer, that were addressed to a broadcast
+ address at this sub-layer.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB -
+ ifHCInBroadcastPkts";
+ }
+
+ leaf in-multicast-pkts {
+ type yang:counter64;
+ description
+ "The number of packets, delivered by this sub-layer to a
+ higher (sub-)layer, that were addressed to a multicast
+ address at this sub-layer. For a MAC-layer protocol,
+ this includes both Group and Functional addresses.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB -
+ ifHCInMulticastPkts";
+ }
+
+ leaf in-discards {
+ type yang:counter32;
+ description
+ "The number of inbound packets that were chosen to be
+ discarded even though no errors had been detected to
+ prevent their being deliverable to a higher-layer
+ protocol. One possible reason for discarding such a
+ packet could be to free up buffer space.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+
+
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifInDiscards";
+ }
+
+ leaf in-errors {
+ type yang:counter32;
+ description
+ "For packet-oriented interfaces, the number of inbound
+ packets that contained errors preventing them from being
+ deliverable to a higher-layer protocol. For character-
+ oriented or fixed-length interfaces, the number of
+ inbound transmission units that contained errors
+ preventing them from being deliverable to a higher-layer
+ protocol.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifInErrors";
+ }
+
+ leaf in-unknown-protos {
+ type yang:counter32;
+ description
+ "For packet-oriented interfaces, the number of packets
+ received via the interface that were discarded because
+ of an unknown or unsupported protocol. For
+ character-oriented or fixed-length interfaces that
+ support protocol multiplexing, the number of
+ transmission units received via the interface that were
+ discarded because of an unknown or unsupported protocol.
+ For any interface that does not support protocol
+ multiplexing, this counter is not present.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifInUnknownProtos";
+ }
+
+
+
+
+
+ leaf out-octets {
+ type yang:counter64;
+ description
+ "The total number of octets transmitted out of the
+ interface, including framing characters.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifHCOutOctets";
+ }
+
+ leaf out-unicast-pkts {
+ type yang:counter64;
+ description
+ "The total number of packets that higher-level protocols
+ requested be transmitted, and that were not addressed
+ to a multicast or broadcast address at this sub-layer,
+ including those that were discarded or not sent.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifHCOutUcastPkts";
+ }
+
+ leaf out-broadcast-pkts {
+ type yang:counter64;
+ description
+ "The total number of packets that higher-level protocols
+ requested be transmitted, and that were addressed to a
+ broadcast address at this sub-layer, including those
+ that were discarded or not sent.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB -
+ ifHCOutBroadcastPkts";
+ }
+
+
+ leaf out-multicast-pkts {
+ type yang:counter64;
+ description
+ "The total number of packets that higher-level protocols
+ requested be transmitted, and that were addressed to a
+ multicast address at this sub-layer, including those
+ that were discarded or not sent. For a MAC-layer
+ protocol, this includes both Group and Functional
+ addresses.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB -
+ ifHCOutMulticastPkts";
+ }
+
+ leaf out-discards {
+ type yang:counter32;
+ description
+ "The number of outbound packets that were chosen to be
+ discarded even though no errors had been detected to
+ prevent their being transmitted. One possible reason
+ for discarding such a packet could be to free up buffer
+ space.
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifOutDiscards";
+ }
+
+ leaf out-errors {
+ type yang:counter32;
+ description
+ "For packet-oriented interfaces, the number of outbound
+ packets that could not be transmitted because of errors.
+ For character-oriented or fixed-length interfaces, the
+ number of outbound transmission units that could not be
+ transmitted because of errors.
+
+
+
+
+ Discontinuities in the value of this counter can occur
+ at re-initialization of the management system, and at
+ other times as indicated by the value of
+ 'discontinuity-time'.";
+ reference
+ "RFC 2863: The Interfaces Group MIB - ifOutErrors";
+ }
+ }
+ }
+ }
+}
to provide room for augmentations, e.g. for
statistics or priorization information associated with
supporting nodes.";
- key "node-ref";
+ // This is not what was published in the initial draft,
+ // added topology-ref leaf and added it to the key
+ key "topology-ref node-ref";
+ leaf topology-ref {
+ type topology-ref;
+ }
leaf node-ref {
type node-ref;
}
<modules>
<module>ietf-inet-types</module>
+ <module>ietf-interfaces</module>
<module>ietf-yang-types</module>
<module>ietf-yang-types-20130715</module>
<module>ietf-ted</module>
import java.net.URL;
import org.opendaylight.yangtools.restconf.client.api.auth.AuthenticationHolder;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
/**
* An interface for acquiring #{@link RestconfClientContext} instances.
*/
public interface RestconfClientContextFactory {
- /**
- * Get a #{@link RestconfClientContext} attached to the server pointed to by an URL.
- * @param baseUrl URL pointer to the backend server
- * @return RestconfClientContext attached to the backend server.
- * @throws UnsupportedProtocolException if the factory cannot handle the protocol specified in the URL.
- */
- RestconfClientContext getRestconfClientContext(URL baseUrl,BindingIndependentMappingService mappingService,SchemaContextHolder holder) throws UnsupportedProtocolException;
+
+ RestconfClientContext getRestconfClientContext(URL baseUrl, SchemaContextHolder schemaContextHolder)
+ throws UnsupportedProtocolException;
+
void setAuthentication(AuthenticationHolder authenticationHolder);
}
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-binding</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-data-codec</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>restconf-util</artifactId>
import com.google.common.base.Optional;
import com.google.common.util.concurrent.ListenableFuture;
import com.sun.jersey.api.client.ClientResponse;
+import java.io.InputStream;
import java.util.Map.Entry;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.restconf.client.api.data.Datastore;
import org.opendaylight.yangtools.restconf.client.api.data.DefaultRetrievalStrategy;
import org.opendaylight.yangtools.restconf.client.api.data.RetrievalStrategy;
import org.opendaylight.yangtools.restconf.utils.RestconfUtils;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
RetrievalStrategy strategy) {
final SchemaContext schemaContext = client.getSchemaContext();
- final BindingIndependentMappingService mappingService = client.getMappingService();
- final Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(path, mappingService, schemaContext);
+ final BindingNormalizedNodeCodecRegistry mappingService = client.getMappingService();
+ final YangInstanceIdentifier domPath = mappingService.toYangInstanceIdentifier(path);
+ final Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(domPath,schemaContext);
String restconfPath = getStorePrefix() + pathWithSchema.getKey();
return client.get(restconfPath, "application/xml",new Function<ClientResponse, Optional<T>>() {
+ @SuppressWarnings("unchecked")
@Override
public com.google.common.base.Optional<T> apply(ClientResponse response) {
switch (response.getStatus()) {
case 200: // Status OK
- DataObject dataObject = RestconfUtils.dataObjectFromInputStream(path,
- response.getEntityInputStream(), schemaContext, mappingService,pathWithSchema.getValue());
+ DataObject dataObject = deserialize(domPath,response.getEntityInputStream());
return (Optional<T>) Optional.of(dataObject);
case 404: // Status Not Found
return Optional.<T> absent();
throw new IllegalStateException("Failed : HTTP error code : " + response.getStatus());
}
}
+
+
});
}
+ protected final DataObject deserialize(YangInstanceIdentifier domPath, InputStream entityInputStream) {
+ throw new UnsupportedOperationException("Not implemented yet.");
+ }
+
protected abstract String getStorePrefix();
}
package org.opendaylight.yangtools.restconf.client;
import com.google.common.base.Function;
-import com.google.common.base.Optional;
import com.sun.jersey.api.client.ClientResponse;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.restconf.client.to.RestRpcError;
import org.opendaylight.yangtools.restconf.client.to.RestRpcResult;
import org.opendaylight.yangtools.restconf.common.ResourceUri;
-import org.opendaylight.yangtools.restconf.utils.XmlTools;
import org.opendaylight.yangtools.yang.binding.BindingMapping;
import org.opendaylight.yangtools.yang.binding.DataContainer;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
-import org.w3c.dom.ls.DOMImplementationLS;
-import org.w3c.dom.ls.LSSerializer;
public class BindingToRestRpc implements InvocationHandler {
private final RestconfClientImpl client;
private static final Logger logger = LoggerFactory.getLogger(BindingToRestRpc.class);
- private final BindingIndependentMappingService mappingService;
+ private final BindingNormalizedNodeCodecRegistry mappingService;
private final SchemaContext schcemaContext;
private final Module module;
- public BindingToRestRpc(final Class<?> proxiedInterface,final BindingIndependentMappingService mappingService,final RestconfClientImpl client,final SchemaContext schemaContext) throws Exception {
- this.mappingService = mappingService;
+ public BindingToRestRpc(final Class<?> proxiedInterface,final BindingNormalizedNodeCodecRegistry mappingService2,final RestconfClientImpl client,final SchemaContext schemaContext) throws Exception {
+ this.mappingService = mappingService2;
this.client = client;
this.schcemaContext = schemaContext;
YangModuleInfo moduleInfo = BindingReflections.getModuleInfo(proxiedInterface);
this.module = schemaContext.findModuleByName(moduleInfo.getName(),org.opendaylight.yangtools.yang.common.QName.parseRevision(moduleInfo.getRevision()));
}
+ @SuppressWarnings("unchecked")
@Override
public Object invoke(final Object o,final Method method, final Object[] objects) throws Exception {
for (RpcDefinition rpcDef:module.getRpcs()){
String rpcMethodName = rpcDef.getQName().getLocalName();
Document rpcInputDoc = null;
for (Object component:objects){
- CompositeNode rpcInput = mappingService.toDataDom((DataObject) component);
- rpcInputDoc = XmlDocumentUtils.toDocument(rpcInput,rpcDef.getInput(),XmlDocumentUtils.defaultValueCodecProvider());
+ ContainerNode rpcInput = mappingService.toNormalizedNodeRpcData((DataObject) component);
+
+ // FIXME: NormalizedNodeXmlStreamWriter
+
}
- DOMImplementationLS lsImpl = (DOMImplementationLS)rpcInputDoc.getImplementation().getFeature("LS", "3.0");
- LSSerializer serializer = lsImpl.createLSSerializer();
- serializer.getDomConfig().setParameter("xml-declaration", false);
- String payloadString = serializer.writeToString(rpcInputDoc);
- final Class<? extends DataContainer> desiredOutputClass = (Class<? extends DataContainer>)BindingReflections.resolveRpcOutputClass(method).get();
+ String payloadString = null;
final DataSchemaNode rpcOutputSchema = rpcDef.getOutput();
return client.post(ResourceUri.OPERATIONS.getPath() + "/" + moduleName + ":" + rpcMethodName,payloadString,new Function<ClientResponse, Object>() {
@Override
}
List<RpcError> errors = new ArrayList<>();
try {
- Document rpcOutputDocument = XmlTools.fromXml(clientResponse.getEntityInputStream());
- CompositeNode cn = (CompositeNode) XmlDocumentUtils.toDomNode(rpcOutputDocument.getDocumentElement(),
- Optional.of(rpcOutputSchema),
- Optional.of(XmlDocumentUtils.defaultValueCodecProvider()));
- DataContainer rpcOutputDataObject = mappingService.dataObjectFromDataDom(desiredOutputClass, cn);
+ ContainerNode output = null;
+ DataContainer rpcOutputDataObject = mappingService.fromNormalizedNodeRpcData(rpcOutputSchema.getPath(), output);
return new RestRpcResult(true,rpcOutputDataObject);
} catch (Exception e) {
logger.trace("Error while extracting rpc output in proxy method {}",e);
throw new IllegalStateException("Unexpected state of proxy method.");
}
- public static<T> T getProxy(final Class<T> proxiedInterface,
- final BindingIndependentMappingService mappingService,
+ @SuppressWarnings("unchecked")
+ public static<T> T getProxy(final Class<T> rpcService,
+ final BindingNormalizedNodeCodecRegistry mappingService2,
final RestconfClientImpl restconfClient,
final SchemaContext schemaContext) {
T proxiedType = null;
try {
proxiedType = (T) Proxy.newProxyInstance
(BindingToRestRpc.class.getClassLoader(),
- new Class[]{proxiedInterface}, new BindingToRestRpc(proxiedInterface, mappingService, restconfClient, schemaContext));
+ new Class[]{rpcService}, new BindingToRestRpc(rpcService, mappingService2, restconfClient, schemaContext));
} catch (Exception e) {
throw new IllegalStateException(e.getMessage());
}
*/
package org.opendaylight.yangtools.restconf.client;
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.sun.jersey.api.client.ClientResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
-import java.util.Map.Entry;
-import java.util.concurrent.Executors;
-
import javax.ws.rs.core.MediaType;
-
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.restconf.client.api.data.ConfigurationDatastore;
import org.opendaylight.yangtools.restconf.client.to.RestRpcError;
import org.opendaylight.yangtools.restconf.client.to.RestRpcResult;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.sun.jersey.api.client.ClientResponse;
-
public class ConfigurationDataStoreImpl extends AbstractDataStore implements ConfigurationDatastore {
- private final ListeningExecutorService pool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
-
@Override
protected String getStorePrefix() {
return ResourceUri.CONFIG.getPath();
@Override
public ListenableFuture<RpcResult<Boolean>> deleteData(final InstanceIdentifier<?> path) {
final SchemaContext schemaContext = getClient().getSchemaContext();
- final BindingIndependentMappingService mappingService = getClient().getMappingService();
- final Map.Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(path, mappingService, schemaContext);
+ final BindingNormalizedNodeCodecRegistry mappingService = getClient().getMappingService();
+ final YangInstanceIdentifier domPath = mappingService.toYangInstanceIdentifier(path);
+ final Map.Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(domPath, schemaContext);
final String restconfPath = getStorePrefix() + pathWithSchema.getKey();
return getClient().delete(restconfPath,MediaType.APPLICATION_XML,new Function<ClientResponse, RpcResult<Boolean>>() {
+ @SuppressWarnings("unchecked")
@Override
public RpcResult<Boolean> apply(ClientResponse clientResponse) {
- Entry<String, DataSchemaNode> restconfEntry = RestconfUtils.toRestconfIdentifier(mappingService.toDataDom(path), schemaContext);
if (clientResponse.getStatus() != 200) {
RpcError rpcError = new RestRpcError(RpcError.ErrorSeverity.ERROR,RpcError.ErrorType.RPC,null,null,"HTTP status "+clientResponse.getStatus(),null,null);
Collection<RpcError> errors = new ArrayList<RpcError>();
RestRpcResult rpcResult = new RestRpcResult(false,null,errors);
return (RpcResult<Boolean>) Optional.of(rpcResult);
}
- DataObject dataObject = RestconfUtils.dataObjectFromInputStream(path, clientResponse.getEntityInputStream(), schemaContext, mappingService,restconfEntry.getValue());
+ DataObject dataObject = deserialize(domPath, clientResponse.getEntityInputStream());
RestRpcResult rpcResult = new RestRpcResult(true,dataObject,null);
return (RpcResult<Boolean>) Optional.of(rpcResult);
}
@Override
public ListenableFuture<RpcResult<Boolean>> putData(final InstanceIdentifier<?> path) {
final SchemaContext schemaContext = getClient().getSchemaContext();
- final BindingIndependentMappingService mappingService = getClient().getMappingService();
- final Map.Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(path, mappingService, schemaContext);
+ final BindingNormalizedNodeCodecRegistry mappingService = getClient().getMappingService();
+ final YangInstanceIdentifier domPath = mappingService.toYangInstanceIdentifier(path);
+ final Map.Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(domPath, schemaContext);
final String restconfPath = getStorePrefix() + pathWithSchema.getKey();
return getClient().put(restconfPath,MediaType.APPLICATION_XML,new Function<ClientResponse, RpcResult<Boolean>>() {
+ @SuppressWarnings("unchecked")
@Override
public RpcResult<Boolean> apply(ClientResponse clientResponse) {
- Map.Entry<String, DataSchemaNode> restconfEntry = RestconfUtils.toRestconfIdentifier(mappingService.toDataDom(path), schemaContext);
if (clientResponse.getStatus() != 200) {
RpcError rpcError = new RestRpcError(RpcError.ErrorSeverity.ERROR,RpcError.ErrorType.RPC,null,null,"HTTP status "+clientResponse.getStatus(),null,null);
Collection<RpcError> errors = new ArrayList<RpcError>();
RestRpcResult rpcResult = new RestRpcResult(false,null,errors);
return (RpcResult<Boolean>) Optional.of(rpcResult);
}
- DataObject dataObject = RestconfUtils.dataObjectFromInputStream(path, clientResponse.getEntityInputStream(),schemaContext,mappingService,restconfEntry.getValue());
+ DataObject dataObject = deserialize(domPath, clientResponse.getEntityInputStream());
RestRpcResult rpcResult = new RestRpcResult(true,dataObject);
return (RpcResult<Boolean>) Optional.of(rpcResult);
}
import org.opendaylight.yangtools.restconf.client.api.RestconfClientContextFactory;
import org.opendaylight.yangtools.restconf.client.api.UnsupportedProtocolException;
import org.opendaylight.yangtools.restconf.client.api.auth.AuthenticationHolder;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(RestconfClientFactory.class);
private AuthenticationHolder authenticationHolder;
+
+
@Override
- public RestconfClientContext getRestconfClientContext(URL baseUrl, BindingIndependentMappingService mappingService, SchemaContextHolder schemaContextHolder) throws UnsupportedProtocolException {
+ public RestconfClientContext getRestconfClientContext(URL baseUrl, SchemaContextHolder schemaContextHolder) throws UnsupportedProtocolException {
if (!baseUrl.getProtocol().equals("http")){
throw new UnsupportedProtocolException("Unsupported protocol "+baseUrl.getProtocol());
}
- RestconfClientImpl restconfClient = new RestconfClientImpl(baseUrl,mappingService,schemaContextHolder);
+ RestconfClientImpl restconfClient = new RestconfClientImpl(baseUrl,schemaContextHolder);
if (null!=authenticationHolder){
restconfClient.setAuthenticationHolder(authenticationHolder);
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
+ * This program and the accompanying materials are made available under the terms of the Eclipse
+ * Public License v1.0 which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.restconf.client;
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.sun.jersey.api.client.Client;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.WebResource;
+import com.sun.jersey.api.client.config.ClientConfig;
+import com.sun.jersey.api.client.config.DefaultClientConfig;
+import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
+import com.sun.jersey.api.client.filter.HTTPDigestAuthFilter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
-
+import javassist.ClassPool;
import javax.ws.rs.core.MediaType;
-
+import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializerGenerator;
+import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.restconf.client.api.RestconfClientContext;
import org.opendaylight.yangtools.restconf.client.api.auth.AuthenticationHolder;
import org.opendaylight.yangtools.restconf.client.api.data.ConfigurationDatastore;
import org.opendaylight.yangtools.restconf.common.ResourceUri;
import org.opendaylight.yangtools.restconf.utils.RestconfUtils;
import org.opendaylight.yangtools.restconf.utils.XmlTools;
+import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.api.client.config.ClientConfig;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
-import com.sun.jersey.api.client.filter.HTTPDigestAuthFilter;
-
public class RestconfClientImpl implements RestconfClientContext, SchemaContextListener {
private final URI defaultUri;
private final SchemaContextHolder schemaContextHolder;
- private final BindingIndependentMappingService mappingService;
+ private final BindingNormalizedNodeCodecRegistry mappingService;
private OperationalDataStoreImpl operationalDatastoreAccessor;
private ConfigurationDataStoreImpl configurationDatastoreAccessor;
- public RestconfClientImpl(final URL url,final BindingIndependentMappingService mappingService,
- final SchemaContextHolder schemaContextHolder){
- Preconditions.checkArgument(url != null,"Restconf endpoint URL must be supplied.");
- Preconditions.checkArgument(mappingService != null, "Mapping service must not be null.");
+ private DataObjectSerializerGenerator generator;
+
+ public RestconfClientImpl(final URL url, final SchemaContextHolder schemaContextHolder) {
+ Preconditions.checkArgument(url != null, "Restconf endpoint URL must be supplied.");
Preconditions.checkNotNull(schemaContextHolder, "Schema Context Holder must not be null.");
ClientConfig config = new DefaultClientConfig();
- this.restClient = Client.create(config);
+ this.restClient = Client.create(config);
URI uri = null;
try {
uri = url.toURI();
} catch (URISyntaxException e) {
- logger.trace("Error in URI syntax {}",e.getMessage(),e);
+ logger.trace("Error in URI syntax {}", e.getMessage(), e);
}
+
+ this.generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(ClassPool.getDefault()));
this.defaultUri = uri;
- this.mappingService = mappingService;
+ this.mappingService = new BindingNormalizedNodeCodecRegistry(generator);
this.schemaContextHolder = schemaContextHolder;
}
return schemaContextHolder;
}
- protected BindingIndependentMappingService getMappingService() {
+ protected BindingNormalizedNodeCodecRegistry getMappingService() {
return mappingService;
}
@Override
public ListenableFuture<Set<Class<? extends RpcService>>> getRpcServices() {
- return get(ResourceUri.MODULES.getPath(), MediaType.APPLICATION_XML,new Function<ClientResponse, Set<Class<? extends RpcService>>>() {
- @Override
- public Set<Class<? extends RpcService>> apply(final ClientResponse clientResponse) {
- if (clientResponse.getStatus() != 200) {
- throw new RuntimeException("Failed : HTTP error code : "
- + clientResponse.getStatus());
- }
- return RestconfUtils.rpcServicesFromInputStream(clientResponse.getEntityInputStream(),mappingService,schemaContextHolder.getSchemaContext());
- }
- });
+ return get(ResourceUri.MODULES.getPath(), MediaType.APPLICATION_XML,
+ new Function<ClientResponse, Set<Class<? extends RpcService>>>() {
+ @Override
+ public Set<Class<? extends RpcService>> apply(final ClientResponse clientResponse) {
+ if (clientResponse.getStatus() != 200) {
+ throw new RuntimeException("Failed : HTTP error code : " + clientResponse.getStatus());
+ }
+ return RestconfUtils.rpcServicesFromInputStream(clientResponse.getEntityInputStream(),
+ mappingService, schemaContextHolder.getSchemaContext());
+ }
+ });
}
@Override
public <T extends RpcService> RpcServiceContext<T> getRpcServiceContext(final Class<T> rpcService) {
- return new RestRpcServiceContext<T>(rpcService,this.mappingService,this,schemaContextHolder.getSchemaContext());
+ return new RestRpcServiceContext<T>(rpcService, this.mappingService, this,
+ schemaContextHolder.getSchemaContext());
}
@Override
public ListenableFuture<Set<EventStreamInfo>> getAvailableEventStreams() {
- return get(ResourceUri.STREAM.getPath(), MediaType.APPLICATION_XML, new Function<ClientResponse, Set<EventStreamInfo>>() {
- @Override
- public Set<EventStreamInfo> apply(final ClientResponse clientResponse) {
- if (clientResponse.getStatus() != 200) {
- throw new RuntimeException("Failed : HTTP error code : "
- + clientResponse.getStatus());
- }
- try {
- return XmlTools.evenStreamsFromInputStream(clientResponse.getEntityInputStream());
- } catch (Exception e) {
- logger.trace("Stream discovery failed due to {}",e);
- throw new IllegalStateException(e);
- }
- }
- });
+ return get(ResourceUri.STREAM.getPath(), MediaType.APPLICATION_XML,
+ new Function<ClientResponse, Set<EventStreamInfo>>() {
+ @Override
+ public Set<EventStreamInfo> apply(final ClientResponse clientResponse) {
+ if (clientResponse.getStatus() != 200) {
+ throw new RuntimeException("Failed : HTTP error code : " + clientResponse.getStatus());
+ }
+ try {
+ return XmlTools.evenStreamsFromInputStream(clientResponse.getEntityInputStream());
+ } catch (Exception e) {
+ logger.trace("Stream discovery failed due to {}", e);
+ throw new IllegalStateException(e);
+ }
+ }
+ });
}
@Override
@Override
public OperationalDatastore getOperationalDatastore() {
- if(operationalDatastoreAccessor == null) {
- operationalDatastoreAccessor = new OperationalDataStoreImpl(this);
+ if (operationalDatastoreAccessor == null) {
+ operationalDatastoreAccessor = new OperationalDataStoreImpl(this);
}
return operationalDatastoreAccessor;
}
public void setAuthenticationHolder(final AuthenticationHolder authenticationHolder) {
- if(authenticationHolder.authenticationRequired()){
- switch (authenticationHolder.getAuthType()){
- case DIGEST: restClient.addFilter(new HTTPDigestAuthFilter(authenticationHolder.getUserName(), authenticationHolder.getPassword()));
+ if (authenticationHolder.authenticationRequired()) {
+ switch (authenticationHolder.getAuthType()) {
+ case DIGEST:
+ restClient.addFilter(new HTTPDigestAuthFilter(authenticationHolder.getUserName(),
+ authenticationHolder.getPassword()));
break;
- default: restClient.addFilter(new HTTPBasicAuthFilter(authenticationHolder.getUserName(), authenticationHolder.getPassword()));
+ default:
+ restClient.addFilter(new HTTPBasicAuthFilter(authenticationHolder.getUserName(),
+ authenticationHolder.getPassword()));
break;
}
}
}
protected <T> ListenableFuture<T> get(final String path, final Function<ClientResponse, T> processingFunction) {
- return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), RestOperation.GET, processingFunction));
+ return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), RestOperation.GET,
+ processingFunction));
}
- protected <T> ListenableFuture<T> get(final String path,final String mediaType, final Function<ClientResponse, T> processingFunction) {
- return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),mediaType,RestOperation.GET,processingFunction));
+ protected <T> ListenableFuture<T> get(final String path, final String mediaType,
+ final Function<ClientResponse, T> processingFunction) {
+ return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), mediaType, RestOperation.GET,
+ processingFunction));
}
- protected <T> ListenableFuture<T> post(final String path, final String payload, final Function<ClientResponse, T> processingFunction) {
- return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),payload,RestOperation.POST,processingFunction));
+ protected <T> ListenableFuture<T> post(final String path, final String payload,
+ final Function<ClientResponse, T> processingFunction) {
+ return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), payload, RestOperation.POST,
+ processingFunction));
}
- protected <T> ListenableFuture<T> post(final String path,final String payload,final String mediaType, final Function<ClientResponse, T> processingFunction) {
- return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),payload,RestOperation.POST,mediaType,processingFunction));
+ protected <T> ListenableFuture<T> post(final String path, final String payload, final String mediaType,
+ final Function<ClientResponse, T> processingFunction) {
+ return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), payload, RestOperation.POST,
+ mediaType, processingFunction));
}
- protected <T> ListenableFuture<T> put(final String path, final String payload, final Function<ClientResponse, T> processingFunction) {
- return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),RestOperation.PUT,payload,processingFunction));
+ protected <T> ListenableFuture<T> put(final String path, final String payload,
+ final Function<ClientResponse, T> processingFunction) {
+ return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), RestOperation.PUT, payload,
+ processingFunction));
}
- protected <T> ListenableFuture<T> put(final String path,final String payload,final String mediaType, final Function<ClientResponse, T> processingFunction) {
- return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),payload,RestOperation.PUT,mediaType,processingFunction));
+ protected <T> ListenableFuture<T> put(final String path, final String payload, final String mediaType,
+ final Function<ClientResponse, T> processingFunction) {
+ return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), payload, RestOperation.PUT,
+ mediaType, processingFunction));
}
+
protected <T> ListenableFuture<T> delete(final String path, final Function<ClientResponse, T> processingFunction) {
- return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),RestOperation.DELETE,processingFunction));
+ return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), RestOperation.DELETE,
+ processingFunction));
}
- protected <T> ListenableFuture<T> delete(final String path,final String mediaType, final Function<ClientResponse, T> processingFunction) {
- return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),RestOperation.DELETE,mediaType,processingFunction));
+ protected <T> ListenableFuture<T> delete(final String path, final String mediaType,
+ final Function<ClientResponse, T> processingFunction) {
+ return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), RestOperation.DELETE,
+ mediaType, processingFunction));
}
protected String constructPath(final String path) {
return getDefaultUri().toString() + path;
}
- private enum RestOperation{
- PUT,POST,GET,DELETE;
+ private enum RestOperation {
+ PUT, POST, GET, DELETE;
}
private class ExecuteOperationAndTransformTask<T> implements Callable<T> {
private final String payload;
private final RestOperation restOperation;
- public ExecuteOperationAndTransformTask(final String path, final String payload, final RestOperation operation, final Function<ClientResponse, T> processingFunction) {
+ public ExecuteOperationAndTransformTask(final String path, final String payload, final RestOperation operation,
+ final Function<ClientResponse, T> processingFunction) {
this.path = path;
this.transformation = processingFunction;
- this.acceptType = MediaType.APPLICATION_XML; //ResourceMediaTypes.XML.getMediaType();
+ this.acceptType = MediaType.APPLICATION_XML; // ResourceMediaTypes.XML.getMediaType();
this.payload = payload;
this.restOperation = operation;
}
- public ExecuteOperationAndTransformTask(final String path,final String payload, final RestOperation operation,final String mediaType, final Function<ClientResponse, T> processingFunction) {
+ public ExecuteOperationAndTransformTask(final String path, final String payload, final RestOperation operation,
+ final String mediaType, final Function<ClientResponse, T> processingFunction) {
this.path = path;
this.transformation = processingFunction;
this.acceptType = mediaType;
this.payload = payload;
this.restOperation = operation;
}
- public ExecuteOperationAndTransformTask(final String path, final RestOperation operation,final String mediaType, final Function<ClientResponse, T> processingFunction) {
+
+ public ExecuteOperationAndTransformTask(final String path, final RestOperation operation,
+ final String mediaType, final Function<ClientResponse, T> processingFunction) {
this.path = path;
this.transformation = processingFunction;
this.acceptType = mediaType;
this.payload = null;
this.restOperation = operation;
}
- public ExecuteOperationAndTransformTask(final String path, final RestOperation operation, final Function<ClientResponse, T> processingFunction) {
+
+ public ExecuteOperationAndTransformTask(final String path, final RestOperation operation,
+ final Function<ClientResponse, T> processingFunction) {
this.path = path;
this.transformation = processingFunction;
- this.acceptType = MediaType.APPLICATION_XML;
+ this.acceptType = MediaType.APPLICATION_XML;
this.payload = null;
this.restOperation = operation;
}
ClientResponse response = null;
try {
WebResource resource = restClient.resource(path);
- switch (restOperation){
- case PUT: response = resource.type(MediaType.APPLICATION_XML).accept(acceptType).put(ClientResponse.class, payload);
+ switch (restOperation) {
+ case PUT:
+ response =
+ resource.type(MediaType.APPLICATION_XML).accept(acceptType)
+ .put(ClientResponse.class, payload);
+ break;
+ case POST:
+ response =
+ resource.type(MediaType.APPLICATION_XML).accept(acceptType)
+ .post(ClientResponse.class, payload);
break;
- case POST : response = resource.type(MediaType.APPLICATION_XML).accept(acceptType).post(ClientResponse.class, payload);
- break;
- case GET: response = resource.type(MediaType.APPLICATION_XML).accept(acceptType).get(ClientResponse.class);
+ case GET:
+ response =
+ resource.type(MediaType.APPLICATION_XML).accept(acceptType).get(ClientResponse.class);
break;
- case DELETE: response = resource.type(MediaType.APPLICATION_XML).accept(acceptType).delete(ClientResponse.class);
+ case DELETE:
+ response =
+ resource.type(MediaType.APPLICATION_XML).accept(acceptType)
+ .delete(ClientResponse.class);
break;
}
- } catch (Exception e){
- logger.trace("Exception occured while posting data to client {}",e);
+ } catch (Exception e) {
+ logger.trace("Exception occured while posting data to client {}", e);
}
*/
package org.opendaylight.yangtools.restconf.client.to;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.restconf.client.BindingToRestRpc;
import org.opendaylight.yangtools.restconf.client.RestconfClientImpl;
import org.opendaylight.yangtools.restconf.client.api.rpc.RpcServiceContext;
import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(RestRpcServiceContext.class);
private T rpcServiceProxy;
- public RestRpcServiceContext(Class<T> rpcService,BindingIndependentMappingService mappingService, RestconfClientImpl
+ public RestRpcServiceContext(Class<T> rpcService,BindingNormalizedNodeCodecRegistry mappingService, RestconfClientImpl
restconfClient,SchemaContext schemaContext){
this.rpcServiceProxy = BindingToRestRpc.getProxy(rpcService,mappingService,restconfClient,schemaContext);
}
*/
package org.opendaylight.yangtools.restconf.client;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
import com.google.common.util.concurrent.ListenableFuture;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutionException;
-import javassist.ClassPool;
import org.junit.Before;
import org.opendaylight.yangtools.restconf.client.api.RestconfClientContext;
import org.opendaylight.yangtools.restconf.client.api.UnsupportedProtocolException;
import org.opendaylight.yangtools.restconf.client.api.event.EventStreamInfo;
import org.opendaylight.yangtools.restconf.client.api.event.ListenableEventStreamContext;
import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
import org.opendaylight.yangtools.yang.binding.RpcService;
import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
public class RestconfClientImplTest {
public static final String JSON = "+json";
public static final String XML = "+xml";
private RestconfClientContext restconfClientContext;
- private RuntimeGeneratedMappingServiceImpl mappingService;
-
@Before
public void setupRestconfClientContext() throws MalformedURLException, UnsupportedProtocolException {
- mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
- mappingService.onGlobalContextUpdated(moduleInfo.tryToCreateSchemaContext().get());
- this.restconfClientContext = new RestconfClientFactory().getRestconfClientContext(new URL(restconfUrl),mappingService, mappingService);
+ this.restconfClientContext = new RestconfClientFactory().getRestconfClientContext(new URL(restconfUrl),new SchemaContextHolder() {
+
+ @Override
+ public SchemaContext getSchemaContext() {
+ return moduleInfo.tryToCreateSchemaContext().get();
+ }
+ });
assertNotNull(this.restconfClientContext);
}
}
if (streamsFuture.isDone()){
try {
- Set<EventStreamInfo> streams = (Set<EventStreamInfo>) streamsFuture.get();
+ Set<EventStreamInfo> streams = streamsFuture.get();
assertNotNull(streams);
} catch (InterruptedException e) {
fail(e.getMessage());
}
if (servicesFuture.isDone()){
try {
- Set<Class<? extends RpcService>> streams = (Set<Class<? extends RpcService>>) servicesFuture.get();
+ Set<Class<? extends RpcService>> streams = servicesFuture.get();
assertNotNull(streams);
} catch (InterruptedException e) {
fail(e.getMessage());
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.opendaylight.yangtools.draft.Draft01;
-import org.opendaylight.yangtools.draft.Draft02;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-
-@Path("restconf")
-public interface RestRestconfService {
-
- public static final String IDENTIFIER = "identifier";
- public static final String INPUT = "input";
- public static final String XML = "+xml";
- public static final String JSON = "+json";
-
- @GET
- public Object getRoot();
-
- @GET
- @Path("/modules")
- @Produces({Draft01.MediaTypes.API+JSON,Draft01.MediaTypes.API+XML,
- Draft02.MediaTypes.API+JSON,Draft02.MediaTypes.API+XML})
- public String getModules();
-
- @POST
- @Path("/operations/{identifier}")
- @Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
- Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- @Consumes({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
- Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public String invokeRpc(@PathParam(IDENTIFIER) String identifier, @QueryParam(INPUT) CompositeNode payload);
-
- @POST
- @Path("/operations/{identifier}")
- @Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
- Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public String invokeRpc(@PathParam(IDENTIFIER) String identifier);
-
- @GET
- @Path("/config/{identifier:.+}")
- @Produces({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public String readConfigurationData(@PathParam(IDENTIFIER) String identifier);
-
- @GET
- @Path("/operational/{identifier:.+}")
- @Produces({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public String readOperationalData(@PathParam(IDENTIFIER) String identifier);
-
- @PUT
- @Path("/config/{identifier:.+}")
- @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public Response updateConfigurationData(@PathParam(IDENTIFIER) String identifier,@QueryParam(INPUT) CompositeNode payload);
-
- @POST
- @Path("/config/{identifier:.+}")
- @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public Response createConfigurationData(@PathParam(IDENTIFIER) String identifier, @QueryParam(INPUT) CompositeNode payload);
-
- @POST
- @Path("/config")
- @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
- MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public Response createConfigurationData( @QueryParam(INPUT) CompositeNode payload);
-
- @DELETE
- @Path("/config/{identifier:.+}")
- public Response deleteConfigurationData(@PathParam(IDENTIFIER) String identifier);
-
-
-}
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-binding</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-data-codec</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-common</artifactId>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-model-api</artifactId>
</dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- </dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<artifactId>binding-generator-impl</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>binding-data-codec</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>bug527-test-model</artifactId>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.restconf.utils;
-
-import com.sun.jersey.api.client.ClientResponse;
-import java.io.IOException;
-import java.io.StringWriter;
-import org.apache.commons.io.IOUtils;
-import org.opendaylight.yangtools.draft.Draft01;
-import org.opendaylight.yangtools.draft.Draft02;
-import org.opendaylight.yangtools.restconf.client.api.RestMessage;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class RestMessageTools {
-
- public static final String XML = "+xml";
- public static final String JSON = "+json";
- private static final Logger logger = LoggerFactory.getLogger(RestMessageTools.class.toString());
-
- public RestMessage extractMessage(ClientResponse response){
- RestMessage restMessage = null;
- if (response.getType().equals(Draft01.MediaTypes.API+JSON) ||
- response.getType().equals(Draft02.MediaTypes.API+JSON)){
- //to be implemented
- }
- if (response.getType().equals(Draft01.MediaTypes.API+XML) ||
- response.getType().equals(Draft02.MediaTypes.API+XML)){
- StringWriter writer = new StringWriter();
- try {
- IOUtils.copy(response.getEntityInputStream(), writer, "UTF-8");
- } catch (IOException e) {
- logger.info("Error parsing XML file from response.");
- }
- }
- return restMessage;
- }
-}
*/
package org.opendaylight.yangtools.restconf.utils;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
-import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.yang.binding.RpcService;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class RestconfUtils {
private static final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
- public static Entry<String, DataSchemaNode> toRestconfIdentifier(
- final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<?> bindingIdentifier,
- final BindingIndependentMappingService mappingService, final SchemaContext schemaContext) {
- YangInstanceIdentifier domIdentifier = mappingService.toDataDom(bindingIdentifier);
- return toRestconfIdentifier(domIdentifier, schemaContext);
- }
-
public static Entry<String, DataSchemaNode> toRestconfIdentifier(final YangInstanceIdentifier xmlInstanceIdentifier,
final SchemaContext schemaContext) {
* @return Set of classes representing rpc services parsed from input stream
*/
public static Set<Class<? extends RpcService>> rpcServicesFromInputStream(final InputStream inputStream,
- final BindingIndependentMappingService mappingService, final SchemaContext schemaContext) {
+ final BindingNormalizedNodeCodecRegistry mappingService, final SchemaContext schemaContext) {
try {
DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
documentBuilder.setNamespaceAware(true);
DocumentBuilder builder = documentBuilder.newDocumentBuilder();
Document doc = builder.parse(inputStream);
Element rootElement = doc.getDocumentElement();
-
- List<Node<?>> domNodes = XmlDocumentUtils.toDomNodes(rootElement,
- Optional.of(schemaContext.getChildNodes()));
+ NodeList domNodes = rootElement.getChildNodes();
Set<Class<? extends RpcService>> rpcServices = new HashSet<Class<? extends RpcService>>();
- for (Node<?> node : domNodes) {
- if (node instanceof ImmutableCompositeNode) {
- ImmutableCompositeNode icNode = (ImmutableCompositeNode) node;
- QName namespace = null;
- QName revision = null;
- QName name = null;
- for (QName q : icNode.keySet()) {
- if (q.getLocalName().equals("namespace")) {
- namespace = q;
- }
- if (q.getLocalName().equals("revision")) {
- revision = q;
- }
- if (q.getLocalName().equals("name")) {
- name = q;
- }
- }
+ for (int i = 0; i < domNodes.getLength(); i++) {
- // FIXME: Method getRpcServiceClassFor has been modified and
- // fixed to follow API contract. This call MUST be updated
- // to follow contract i.e. pass correct parameters:
- // "NAMESPACE" and "REVISION"
- Optional<Class<? extends RpcService>> rpcService = mappingService.getRpcServiceClassFor(
- icNode.get(name).get(0).getValue().toString(), icNode.get(revision).get(0).getValue()
- .toString());
- if (rpcService.isPresent()) {
- rpcServices.add(rpcService.get());
- }
- }
}
-
+ /**
+ * FIXME: Parse modules section and find all related RPC services.
+ *
+ */
return rpcServices;
} catch (ParserConfigurationException e) {
logger.trace("Parse configuration exception {}", e);
return null;
}
- /**
- * Parse DataObject from input stream.
- *
- * @param path
- * identifier of expected result object
- * @param inputStream
- * stream containing xml data to parse
- * @param schemaContext
- * parsed yang data context
- * @param mappingService
- * current mapping service
- * @param dataSchema
- * yang data schema node representation of resulting data object
- * @return DataObject instance parsed from input stream
- */
- public static DataObject dataObjectFromInputStream(
- final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<?> path, final InputStream inputStream,
- final SchemaContext schemaContext, final BindingIndependentMappingService mappingService,
- final DataSchemaNode dataSchema) {
- // Parse stream into w3c Document
- try {
- DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
- documentBuilder.setNamespaceAware(true);
- DocumentBuilder builder = documentBuilder.newDocumentBuilder();
- Document doc = builder.parse(inputStream);
- Element rootElement = doc.getDocumentElement();
- Node<?> domNode = XmlDocumentUtils.toDomNode(rootElement, Optional.of(dataSchema),
- Optional.<XmlCodecProvider> absent(), Optional.of(schemaContext));
- DataObject dataObject = mappingService.dataObjectFromDataDom(path, (CompositeNode) domNode); // getDataFromResponse
- return dataObject;
- } catch (DeserializationException e) {
- logger.trace("Deserialization exception {}", e);
- } catch (ParserConfigurationException e) {
- logger.trace("Parse configuration exception {}", e);
- } catch (SAXException e) {
- logger.trace("SAX exception {}", e);
- } catch (IOException e) {
- logger.trace("IOException {}", e);
- }
- return null;
- }
-
}
import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
import org.opendaylight.yangtools.yang.binding.DataObject;
private static final ReportedLspKey LSP1_KEY = new ReportedLspKey("one");
private static final ReportedLspKey LSP2_KEY = new ReportedLspKey("two");
- private RuntimeGeneratedMappingServiceImpl mappingService;
+
private Optional<SchemaContext> schemaContext;
private DataObjectSerializerGenerator generator;
private BindingNormalizedNodeCodecRegistry registry;
@Before
public void setup() {
- this.mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault());
-
final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
schemaContext = moduleInfo.tryToCreateSchemaContext();
- this.mappingService.onGlobalContextUpdated(moduleInfo.tryToCreateSchemaContext().get());
JavassistUtils utils = JavassistUtils.forClassPool(ClassPool.getDefault());
generator = StreamWriterGenerator.create(utils);
registry = new BindingNormalizedNodeCodecRegistry(generator);
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.restconf.utils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.io.InputStream;
-import java.util.AbstractMap.SimpleEntry;
-import java.util.Map.Entry;
-
-import javassist.ClassPool;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.network.topology.unix.rev131222.network.topology.topology.node.path.computation.client.reported.lsp.lsp.tlvs.vs.tlv.vendor.payload.unix.UnixSubTlvs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.ReportedLsp1;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.Lsp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.network.topology.topology.node.path.computation.client.reported.lsp.lsp.tlvs.vs.tlv.vendor.payload.linux.LinuxSubTlvs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.vs.tlv.VsTlv;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-public class Bug1196Test {
-
- private static final InstanceIdentifier<PathComputationClient> PATH_TO_CLIENT = InstanceIdentifier.builder(NetworkTopology.class)
- .child(Topology.class)
- .child(Node.class)
- .augmentation(Node1.class)
- .child(PathComputationClient.class)
- .build();
- private RuntimeGeneratedMappingServiceImpl mappingService;
-
- @Before
- public void setup() {
- this.mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
-
- final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
- moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
- this.mappingService.onGlobalContextUpdated(moduleInfo.tryToCreateSchemaContext().get());
- }
-
- @Test
- public void testXmlDataToDataObjectLinuxCase() {
- final InstanceIdentifier<Topology> instanceIdentifier = InstanceIdentifier.builder(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(new TopologyId("example-pcep-topology"))).build();
- final InputStream is = this.getClass().getClassLoader().getResourceAsStream("topology-bug1196-linux.xml");
- final DataSchemaNode dataSchema = RestconfUtils.toRestconfIdentifier(instanceIdentifier, this.mappingService,
- this.mappingService.getSchemaContext()).getValue();
- Topology topology = (Topology) RestconfUtils.dataObjectFromInputStream(instanceIdentifier, is,
- this.mappingService.getSchemaContext(), this.mappingService, dataSchema);
- assertNotNull(topology);
- assertNotNull(topology.getNode());
- assertEquals(1, topology.getNode().size());
- Node node = topology.getNode().get(0);
- Node1 node1 = node.getAugmentation(Node1.class);
- assertNotNull(node1);
- final PathComputationClient pcc = node1.getPathComputationClient();
- final Lsp lsp = pcc.getReportedLsp().get(0).getAugmentation(ReportedLsp1.class).getLsp();
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs tlvs = lsp.getTlvs();
- assertNotNull(tlvs);
- VsTlv vsTlv = tlvs.getVsTlv();
- assertNotNull(vsTlv.getVendorPayload());
-
- Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> domPcc = mappingService.toDataDom(new SimpleEntry<InstanceIdentifier<?>,DataObject>(PATH_TO_CLIENT,pcc));
- CompositeNode domPccValue = domPcc.getValue();
- assertNotNull(domPccValue);
- CompositeNode domPccTlvs = getFirstReportedLspVsTlvs(domPccValue);
- assertNotNull(domPccTlvs);
- assertNotNull(domPccTlvs.getFirstCompositeByName(LinuxSubTlvs.QNAME));
-
- }
-
- private CompositeNode getFirstReportedLspVsTlvs(final CompositeNode domPccValue) {
- return domPccValue.getFirstCompositeByName(ReportedLsp.QNAME).getFirstCompositeByName(Lsp.QNAME).getFirstCompositeByName(Tlvs.QNAME).getFirstCompositeByName(QName.create(Tlvs.QNAME,VsTlv.QNAME.getLocalName()));
- }
-
- @Test
- public void testXmlDataToDataObjectUnixCase() {
- final InstanceIdentifier<Topology> instanceIdentifier = InstanceIdentifier.builder(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(new TopologyId("example-pcep-topology"))).build();
- final InputStream is = this.getClass().getClassLoader().getResourceAsStream("topology-bug1196-unix.xml");
- final DataSchemaNode dataSchema = RestconfUtils.toRestconfIdentifier(instanceIdentifier, this.mappingService,
- this.mappingService.getSchemaContext()).getValue();
- Topology topology = (Topology) RestconfUtils.dataObjectFromInputStream(instanceIdentifier, is,
- this.mappingService.getSchemaContext(), this.mappingService, dataSchema);
- assertNotNull(topology);
- assertNotNull(topology.getNode());
- assertEquals(1, topology.getNode().size());
- Node node = topology.getNode().get(0);
- Node1 node1 = node.getAugmentation(Node1.class);
- assertNotNull(node1);
- final PathComputationClient pcc = node1.getPathComputationClient();
- final Lsp lsp = pcc.getReportedLsp().get(0).getAugmentation(ReportedLsp1.class).getLsp();
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs tlvs = lsp.getTlvs();
- assertNotNull(tlvs);
- VsTlv vsTlv = tlvs.getVsTlv();
- assertNotNull(vsTlv.getVendorPayload());
-
- Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> domPcc = mappingService.toDataDom(new SimpleEntry<InstanceIdentifier<?>,DataObject>(PATH_TO_CLIENT,pcc));
- CompositeNode domPccValue = domPcc.getValue();
- assertNotNull(domPccValue);
- CompositeNode domPccTlvs = getFirstReportedLspVsTlvs(domPccValue);
- assertNotNull(domPccTlvs);
- assertNotNull(domPccTlvs.getFirstCompositeByName(UnixSubTlvs.QNAME));
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.restconf.utils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.io.InputStream;
-import java.util.AbstractMap.SimpleEntry;
-
-import javassist.ClassPool;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.CreateFactoryInput;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.Factory;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.factory.Alpha;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.factory.Beta;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.machine.ext.types.machine.type.TypeA;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.machine.types.Types;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.machine.types.types.MachineType;
-import org.opendaylight.yang.gen.v1.urn.yang.baz.rev140321.machine.def.Machine;
-import org.opendaylight.yang.gen.v1.urn.yang.baz.rev140321.machine.def.machine.Atts;
-import org.opendaylight.yang.gen.v1.urn.yang.foo.rev140321.AlphaExt;
-import org.opendaylight.yang.gen.v1.urn.yang.foo.rev140321.BetaExt;
-import org.opendaylight.yang.gen.v1.urn.yang.foo.rev140321.CreateExt;
-import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-public class Bug527Test {
-
- private RuntimeGeneratedMappingServiceImpl mappingService;
-
- @Before
- public void setup() {
- this.mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
-
- final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
- moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
- this.mappingService.onGlobalContextUpdated(moduleInfo.tryToCreateSchemaContext().get());
- }
-
- @Test
- public void testToDataObjectMappingWithNestedAugmentations() {
- InstanceIdentifier<Factory> factoryId = InstanceIdentifier.builder(Factory.class).build();
- InputStream is = this.getClass().getClassLoader().getResourceAsStream("topology-bug527.xml");
- DataSchemaNode dataSchema = RestconfUtils.toRestconfIdentifier(factoryId, mappingService,
- mappingService.getSchemaContext()).getValue();
-
- Factory factory = (Factory) RestconfUtils.dataObjectFromInputStream(factoryId, is,
- mappingService.getSchemaContext(), mappingService, dataSchema);
- assertNotNull(factory);
-
- Alpha alpha = factory.getAlpha();
- Machine alphaMachine = alpha.getMachine();
- Atts alphaAtts = alphaMachine.getAtts();
- AlphaExt alphaAttsAug = alphaAtts.getAugmentation(AlphaExt.class);
- Types alphaMachineTypes = alphaAttsAug.getTypes();
- MachineType alphaMachineType = alphaMachineTypes.getMachineType();
- TypeA alphaTypeA = (TypeA) alphaMachineType;
- assertEquals("id-alpha", alphaTypeA.getId());
- assertNull(alphaAtts.getAugmentation(BetaExt.class));
-
- Beta beta = factory.getBeta();
- Machine betaMachine = beta.getMachine();
- Atts betaAtts = betaMachine.getAtts();
- BetaExt betaAttsAug = betaAtts.getAugmentation(BetaExt.class);
- Types betaMachineTypes = betaAttsAug.getTypes();
- MachineType betaMachineType = betaMachineTypes.getMachineType();
- TypeA betaTypeA = (TypeA) betaMachineType;
- assertEquals("id-beta", betaTypeA.getId());
- assertNull(betaAtts.getAugmentation(AlphaExt.class));
-
- InstanceIdentifier<? extends DataObject> alphaPath = InstanceIdentifier.builder(Factory.class).child(Alpha.class).build();
- CompositeNode domAlpha = mappingService.toDataDom(new SimpleEntry<InstanceIdentifier<? extends DataObject>,DataObject>(alphaPath,alpha)).getValue();
- assertNotNull(domAlpha);
-
- CompositeNodeTOImpl domInput = new CompositeNodeTOImpl(QName.create(domAlpha.getNodeType(),"input"),null, domAlpha.getValue());
-
- CreateFactoryInput nestedInput = (CreateFactoryInput) mappingService.dataObjectFromDataDom(CreateFactoryInput.class, domInput);
- assertNotNull(nestedInput);
- assertNotNull(nestedInput.getMachine().getAtts().getAugmentation(CreateExt.class));
-
-
- }
-
-}
+++ /dev/null
-package org.opendaylight.yangtools.restconf.utils;
-
-import org.junit.Before;
-import org.junit.Test;
-
-public class LazyGeneratedCodecRestartTest {
-
- Bug527Test bug527;
- Bug1196Test bug1196;
- RestconfUtilsTest reUtils;
-
-
- @Before
- public void setup() {
- bug527 = new Bug527Test();
- bug1196 = new Bug1196Test();
- reUtils = new RestconfUtilsTest();
-
- }
-
- @Test
- public void test() {
- bug1196.setup();
- bug1196.testXmlDataToDataObjectUnixCase();
-
- reUtils.setup();
- reUtils.testToDataObjectMappingWithNestedAugmentations();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.restconf.utils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.io.InputStream;
-
-import javassist.ClassPool;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpNodeAttributes1;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Node1;
-import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-public class RestconfUtilsTest {
-
- private RuntimeGeneratedMappingServiceImpl mappingService;
-
- @Before
- public void setup() {
- this.mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
-
- final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
- moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
- this.mappingService.onGlobalContextUpdated(moduleInfo.tryToCreateSchemaContext().get());
- }
-
- @Test
- public void firstTest() { // test static state collisions with the other test
- final InstanceIdentifier<Topology> instanceIdentifier = InstanceIdentifier.builder(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(new TopologyId("example-pcep-topology"))).build();
- final InputStream is = this.getClass().getClassLoader().getResourceAsStream("topology-bug1196-linux.xml");
- RestconfUtils.toRestconfIdentifier(instanceIdentifier, this.mappingService,
- this.mappingService.getSchemaContext()).getValue();
- }
-
- @Test
- public void testToDataObjectMappingWithNestedAugmentations() {
- final InstanceIdentifier<Topology> topologyIdentifier = InstanceIdentifier.builder(NetworkTopology.class)
- .child(Topology.class).build();
- final InputStream is = this.getClass().getClassLoader().getResourceAsStream("topology.xml");
- final DataSchemaNode dataSchema = RestconfUtils.toRestconfIdentifier(topologyIdentifier, this.mappingService,
- this.mappingService.getSchemaContext()).getValue();
- final Topology topology = (Topology) RestconfUtils.dataObjectFromInputStream(topologyIdentifier, is,
- this.mappingService.getSchemaContext(), this.mappingService, dataSchema);
-
- assertNotNull(topology);
- assertEquals(1, topology.getNode().size());
- final Node node = topology.getNode().get(0);
- assertEquals("bgpls://IsisLevel2:1/type=node&as=72&domain=673720360&router=0000.0000.0042", node.getNodeId()
- .getValue());
-
- final Node1 node1 = node.getAugmentation(Node1.class);
- assertNotNull(node1);
- assertNotNull(node1.getIgpNodeAttributes());
- assertEquals("Of-9k-02", node1.getIgpNodeAttributes().getName().getValue());
-
- final IgpNodeAttributes1 igpAttributes1 = node1.getIgpNodeAttributes()
- .getAugmentation(IgpNodeAttributes1.class);
- assertNotNull(igpAttributes1);
- assertNotNull(igpAttributes1.getIsisNodeAttributes());
- assertEquals("0000.1111.2222", igpAttributes1.getIsisNodeAttributes().getIso().getIsoSystemId().getValue());
- }
-
-}
<module>yang-parser-api</module>
<module>yang-parser-impl</module>
<module>yang-model-export</module>
- <module>yang-data-composite-node</module>
</modules>
<build>
<plugins>
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
+
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
+import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
.expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS) //
.build(new ClassToQNameLoader());
-
-
private BindingReflections() {
throw new UnsupportedOperationException("Utility class.");
}
/**
* Find augmentation target class from concrete Augmentation class
*
- * This method uses first generic argument of
- * implemented {@link Augmentation} interface.
+ * This method uses first generic argument of implemented
+ * {@link Augmentation} interface.
*
* @param augmentation
* {@link Augmentation} subclass for which we want to determine
/**
* Find data hierarchy parent from concrete Data class
*
- * This method uses first generic argument of
- * implemented {@link ChildOf} interface.
+ * This method uses first generic argument of implemented {@link ChildOf}
+ * interface.
*
* @param childClass
* child class for which we want to find the parent class.
* Find data hierarchy parent from concrete Data class
*
* This method is shorthand which gets DataObject class by invoking
- * {@link DataObject#getImplementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
+ * {@link DataObject#getImplementedInterface()} and uses
+ * {@link #findHierarchicalParent(Class)}.
*
* @param child
* Child object for which the parent needs to be located.
*
*
*
- * @param possibleMethod Method to check
+ * @param possibleMethod
+ * Method to check
* @return true if method is RPC invocation, false otherwise.
*/
public static boolean isRpcMethod(final Method possibleMethod) {
*
* Extracts Output class for RPC method
*
- * @param targetMethod method to scan
- * @return Optional.absent() if result type could not be get,
- * or return type is Void.
+ * @param targetMethod
+ * method to scan
+ * @return Optional.absent() if result type could not be get, or return type
+ * is Void.
*/
@SuppressWarnings("rawtypes")
public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
*
* Extracts input class for RPC method
*
- * @param targetMethod method to scan
+ * @param targetMethod
+ * method to scan
* @return Optional.absent() if rpc has no input, Rpc input type otherwise.
*/
@SuppressWarnings("unchecked")
/**
* Returns root package name for suplied package.
*
- * @param pkg Package for which find model root package.
+ * @param pkg
+ * Package for which find model root package.
* @return Package of model root.
*/
public static String getModelRootPackageName(final Package pkg) {
/**
* Returns root package name for supplied package name.
*
- * @param name Package for which find model root package.
+ * @param name
+ * Package for which find model root package.
* @return Package of model root.
*/
public static String getModelRootPackageName(final String name) {
return match.group(0);
}
+ public static final QNameModule getQNameModule(Class<?> clz) {
+ if(DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)) {
+ return findQName(clz).getModule();
+ }
+ try {
+ YangModuleInfo modInfo = BindingReflections.getModuleInfo(clz);
+ return getQNameModule(modInfo);
+ } catch (Exception e) {
+ throw new IllegalStateException("Unable to get QName of defining model.", e);
+ }
+ }
+
+ public static final QNameModule getQNameModule(YangModuleInfo modInfo) {
+ return QNameModule.create(URI.create(modInfo.getNamespace()), QName.parseRevision(modInfo.getRevision()));
+ }
+
/**
*
- * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
+ * Returns instance of {@link YangModuleInfo} of declaring model for
+ * specific class.
*
* @param cls
- * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
+ * @return Instance of {@link YangModuleInfo} associated with model, from
+ * which this class was derived.
* @throws Exception
*/
public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
*
* Check if supplied class is derived from YANG model.
*
- * @param cls Class to check
+ * @param cls
+ * Class to check
* @return true if class is derived from YANG model.
*/
public static boolean isBindingClass(final Class<?> cls) {
* @return
*/
public static boolean isNotification(final Class<?> potentialNotification) {
- checkArgument(potentialNotification != null,"potentialNotification must not be null.");
+ checkArgument(potentialNotification != null, "potentialNotification must not be null.");
return Notification.class.isAssignableFrom(potentialNotification);
}
}
/**
- *
- * Loads {@link YangModuleInfo} infos available on supplied classloader.
- *
- * {@link YangModuleInfo} are discovered using {@link ServiceLoader}
- * for {@link YangModelBindingProvider}. {@link YangModelBindingProvider}
- * are simple classes which holds only pointers to actual instance
- * {@link YangModuleInfo}.
- *
- * When {@link YangModuleInfo} is available, all dependencies are recursivelly collected
- * into returning set by collecting results of {@link YangModuleInfo#getImportedModules()}.
- *
- *
- * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
- * @return Set of {@link YangModuleInfo} available for supplied classloader.
- */
+ *
+ * Loads {@link YangModuleInfo} infos available on supplied classloader.
+ *
+ * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for
+ * {@link YangModelBindingProvider}. {@link YangModelBindingProvider} are
+ * simple classes which holds only pointers to actual instance
+ * {@link YangModuleInfo}.
+ *
+ * When {@link YangModuleInfo} is available, all dependencies are
+ * recursivelly collected into returning set by collecting results of
+ * {@link YangModuleInfo#getImportedModules()}.
+ *
+ *
+ * @param loader
+ * Classloader for which {@link YangModuleInfo} should be
+ * retrieved.
+ * @return Set of {@link YangModuleInfo} available for supplied classloader.
+ */
public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.<YangModuleInfo> builder();
ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
*
* Checks if supplied class represents RPC Input / RPC Output.
*
- * @param targetType Class to be checked
+ * @param targetType
+ * Class to be checked
* @return true if class represents RPC Input or RPC Output class.
*/
public static boolean isRpcType(final Class<? extends DataObject> targetType) {
/**
*
- * Scans supplied class and returns an iterable of all data children classes.
+ * Scans supplied class and returns an iterable of all data children
+ * classes.
*
- * @param type YANG Modeled Entity derived from DataContainer
+ * @param type
+ * YANG Modeled Entity derived from DataContainer
* @return Iterable of all data children, which have YANG modeled entity
*/
@SuppressWarnings("unchecked")
}
/**
- *
- * Scans supplied class and returns an iterable of all data children classes.
- *
- * @param type YANG Modeled Entity derived from DataContainer
- * @return Iterable of all data children, which have YANG modeled entity
- */
- public static Map<Class<?>,Method> getChildrenClassToMethod(final Class<?> type) {
- checkArgument(type != null, "Target type must not be null");
- checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
- Map<Class<?>,Method> ret = new HashMap<>();
- for (Method method : type.getMethods()) {
- Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
- if (entity.isPresent()) {
- ret.put(entity.get(),method);
- }
- }
- return ret;
- }
+ *
+ * Scans supplied class and returns an iterable of all data children
+ * classes.
+ *
+ * @param type
+ * YANG Modeled Entity derived from DataContainer
+ * @return Iterable of all data children, which have YANG modeled entity
+ */
+ public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
+ checkArgument(type != null, "Target type must not be null");
+ checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
+ Map<Class<?>, Method> ret = new HashMap<>();
+ for (Method method : type.getMethods()) {
+ Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
+ if (entity.isPresent()) {
+ ret.put(entity.get(), method);
+ }
+ }
+ return ret;
+ }
@SuppressWarnings("unchecked")
private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
} catch (Exception e) {
/*
*
- * It is safe to log this this exception on debug, since
- * this method should not fail. Only failures are possible if
- * the runtime / backing.
- *
+ * It is safe to log this this exception on debug, since this
+ * method should not fail. Only failures are possible if the
+ * runtime / backing.
*/
LOG.debug("Unable to find YANG modeled return type for {}", method, e);
}
*
* Tries to resolve QName for supplied class.
*
- * Looks up for static field with name from constant {@link BindingMapping#QNAME_STATIC_FIELD_NAME}
- * and returns value if present.
+ * Looks up for static field with name from constant
+ * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if
+ * present.
*
- * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types.
+ * If field is not present uses {@link #computeQName(Class)} to compute
+ * QName for missing types.
*
* @param key
* @return
} catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
/*
*
- * It is safe to log this this exception on debug, since
- * this method should not fail. Only failures are possible if
- * the runtime / backing.
- *
+ * It is safe to log this this exception on debug, since this method
+ * should not fail. Only failures are possible if the runtime /
+ * backing.
*/
- LOG.debug("Unexpected exception during extracting QName for {}",key,e);
+ LOG.debug("Unexpected exception during extracting QName for {}", key, e);
}
return Optional.absent();
}
/**
* Computes QName for supplied class
*
- * Namespace and revision are same as {@link YangModuleInfo}
- * associated with supplied class.
+ * Namespace and revision are same as {@link YangModuleInfo} associated with
+ * supplied class.
* <p>
* If class is
* <ul>
- * <li>rpc input: local name is "input".
- * <li>rpc output: local name is "output".
- * <li>augmentation: local name is "module name".
+ * <li>rpc input: local name is "input".
+ * <li>rpc output: local name is "output".
+ * <li>augmentation: local name is "module name".
* </ul>
*
- * There is also fallback, if it is not possible to compute QName
- * using following algorithm returns module QName.
+ * There is also fallback, if it is not possible to compute QName using
+ * following algorithm returns module QName.
*
- * FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
+ * FIXME: Extend this algorithm to also provide QName for YANG modeled
+ * simple types.
*
- * @throws IllegalStateException If YangModuleInfo could not be resolved
- * @throws IllegalArgumentException If supplied class was not derived from YANG model.
+ * @throws IllegalStateException
+ * If YangModuleInfo could not be resolved
+ * @throws IllegalArgumentException
+ * If supplied class was not derived from YANG model.
*
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private static QName computeQName(final Class key) {
- if(isBindingClass(key)) {
+ if (isBindingClass(key)) {
YangModuleInfo moduleInfo;
try {
moduleInfo = getModuleInfo(key);
} catch (Exception e) {
- throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",e);
+ throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.", e);
}
final QName module = getModuleQName(moduleInfo);
if (Augmentation.class.isAssignableFrom(key)) {
return module;
- } else if(isRpcType(key)) {
+ } else if (isRpcType(key)) {
final String className = key.getSimpleName();
- if(className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
- return QName.create(module,"output");
+ if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
+ return QName.create(module, "output");
} else {
- return QName.create(module,"input");
+ return QName.create(module, "input");
}
}
/*
- * Fallback for Binding types which fo not have QNAME
- * field
+ * Fallback for Binding types which fo not have QNAME field
*/
return module;
} else {
- throw new IllegalArgumentException("Supplied class "+key+"is not derived from YANG.");
+ throw new IllegalArgumentException("Supplied class " + key + "is not derived from YANG.");
}
}
/**
* Given a {@link YangModuleInfo}, create a QName representing it. The QName
- * is formed by reusing the module's namespace and revision using the module's
- * name as the QName's local name.
+ * is formed by reusing the module's namespace and revision using the
+ * module's name as the QName's local name.
*
- * @param moduleInfo module information
+ * @param moduleInfo
+ * module information
* @return QName representing the module
*/
public static QName getModuleQName(final YangModuleInfo moduleInfo) {
checkArgument(moduleInfo != null, "moduleInfo must not be null.");
- return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(),
- moduleInfo.getName());
+ return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(), moduleInfo.getName());
}
/**
* Extracts augmentation from Binding DTO field using reflection
*
- * @param input Instance of DataObject which is augmentable and
- * may contain augmentation
- * @return Map of augmentations if read was successful, otherwise
- * empty map.
+ * @param input
+ * Instance of DataObject which is augmentable and may contain
+ * augmentation
+ * @return Map of augmentations if read was successful, otherwise empty map.
*/
public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
/**
*
- * Determines if two augmentation classes or case classes represents same data.
+ * Determines if two augmentation classes or case classes represents same
+ * data.
* <p>
* Two augmentations or cases could be substituted only if and if:
* <ul>
* <li>Both implements same interfaces</li>
* <li>Both have same children</li>
- * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in grouping.</li>
- * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
+ * <li>If augmentations: Both have same augmentation target class. Target
+ * class was generated for data node in grouping.</li>
+ * <li>If cases: Both are from same choice. Choice class was generated for
+ * data node in grouping.</li>
* </ul>
* <p>
- * <b>Explanation:</b> Binding Specification reuses classes generated for groupings as part of normal data tree,
- * this classes from grouping could be used at various locations and user may not be aware of it
- * and may use incorrect case or augmentation in particular subtree (via copy constructors, etc).
- *
- * @param potential Class which is potential substition
- * @param target Class which should be used at particular subtree
+ * <b>Explanation:</b> Binding Specification reuses classes generated for
+ * groupings as part of normal data tree, this classes from grouping could
+ * be used at various locations and user may not be aware of it and may use
+ * incorrect case or augmentation in particular subtree (via copy
+ * constructors, etc).
+ *
+ * @param potential
+ * Class which is potential substition
+ * @param target
+ * Class which should be used at particular subtree
* @return true if and only if classes represents same data.
*/
- @SuppressWarnings({"rawtypes","unchecked"})
+ @SuppressWarnings({ "rawtypes", "unchecked" })
public static boolean isSubstitutionFor(final Class potential, final Class target) {
HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
- if(!subImplemented.equals(targetImplemented)) {
+ if (!subImplemented.equals(targetImplemented)) {
return false;
}
- if(Augmentation.class.isAssignableFrom(potential)
- && !BindingReflections.findAugmentationTarget(potential).equals(BindingReflections.findAugmentationTarget(target))) {
- return false;
+ if (Augmentation.class.isAssignableFrom(potential)
+ && !BindingReflections.findAugmentationTarget(potential).equals(
+ BindingReflections.findAugmentationTarget(target))) {
+ return false;
}
- for(Method potentialMethod : potential.getMethods()) {
+ for (Method potentialMethod : potential.getMethods()) {
try {
Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
- if(!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
+ if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
return false;
}
} catch (NoSuchMethodException e) {
- // Counterpart method is missing, so classes could not be substituted.
+ // Counterpart method is missing, so classes could not be
+ // substituted.
return false;
} catch (SecurityException e) {
- throw new IllegalStateException("Could not compare methods",e);
+ throw new IllegalStateException("Could not compare methods", e);
}
}
return true;
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.binding.util;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMap.Builder;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.MethodType;
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.DataContainer;
+import org.opendaylight.yangtools.yang.binding.NotificationListener;
+import org.opendaylight.yangtools.yang.common.QName;
+
+/**
+ * Provides single method invocation of notificatoin callbacks on supplied instance.
+ *
+ * Notification Listener invoker provides common invocation interface for any subtype of {@link NotificationListener}.
+ * via {@link #invokeNotification(NotificationListener, QName, DataContainer)} method.
+ *
+ */
+public final class NotificationListenerInvoker {
+
+ private static final Lookup LOOKUP = MethodHandles.publicLookup();
+
+ private static final LoadingCache<Class<? extends NotificationListener>, NotificationListenerInvoker> INVOKERS = CacheBuilder
+ .newBuilder().weakKeys()
+ .build(new CacheLoader<Class<? extends NotificationListener>, NotificationListenerInvoker>() {
+
+ @Override
+ public NotificationListenerInvoker load(Class<? extends NotificationListener> key) throws Exception {
+ return createInvoker(key);
+ }
+
+ });
+
+ private final Map<QName, MethodHandle> methodInvokers;
+
+ public NotificationListenerInvoker(Map<QName, MethodHandle> map) {
+ this.methodInvokers = map;
+ }
+
+ /**
+ *
+ * Creates RPCServiceInvoker for specified RpcService type
+ *
+ * @param type
+ * RpcService interface, which was generated from model.
+ * @return Cached instance of {@link NotificationListenerInvoker} for
+ * supplied RPC type.
+ *
+ */
+ public static NotificationListenerInvoker from(Class<? extends NotificationListener> type) {
+ Preconditions.checkArgument(type.isInterface());
+ Preconditions.checkArgument(BindingReflections.isBindingClass(type));
+ return INVOKERS.getUnchecked(type);
+ }
+
+ /**
+ * Invokes supplied RPC on provided implementation of RPC Service.
+ *
+ * @param impl
+ * Imlementation on which notifiaction callback should be
+ * invoked.
+ * @param rpcName
+ * Name of RPC to be invoked.
+ * @param input
+ * Input data for RPC.
+ *
+ */
+ public void invokeNotification(@Nonnull NotificationListener impl, @Nonnull QName rpcName,
+ @Nullable DataContainer input) {
+ Preconditions.checkNotNull(impl, "implemetation must be supplied");
+ MethodHandle invoker = methodInvokers.get(rpcName);
+ Preconditions.checkArgument(invoker != null, "Supplied notification is not valid for implementation %s", impl);
+ try {
+ invoker.invokeExact(impl, input);
+ } catch (Throwable e) {
+ throw Throwables.propagate(e);
+ }
+ }
+
+ private static NotificationListenerInvoker createInvoker(Class<? extends NotificationListener> key) {
+ return new NotificationListenerInvoker(createInvokerMap(key));
+ }
+
+ private static Map<QName, MethodHandle> createInvokerMap(Class<? extends NotificationListener> key) {
+ Builder<QName, MethodHandle> ret = ImmutableMap.<QName, MethodHandle> builder();
+ for (Method method : key.getMethods()) {
+ if (BindingReflections.isNotificationCallback(method)) {
+
+ Class<?> notification = method.getParameterTypes()[0];
+ QName name = BindingReflections.findQName(notification);
+ MethodHandle handle;
+ try {
+ handle = LOOKUP.unreflect(method).asType(
+ MethodType.methodType(Void.class, NotificationListener.class, DataContainer.class));
+ ret.put(name, handle);
+ } catch (IllegalAccessException e) {
+ throw new IllegalStateException("Can not access public method.", e);
+ }
+ }
+
+ }
+ return ret.build();
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.binding.util;
+
+import com.google.common.base.Optional;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.reflect.Method;
+import java.util.concurrent.Future;
+import org.opendaylight.yangtools.yang.binding.DataContainer;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.RpcService;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+
+abstract class RpcMethodInvoker {
+
+ private static Lookup LOOKUP = MethodHandles.publicLookup();
+
+ protected abstract Future<RpcResult<?>> invokeOn(RpcService impl, DataObject input);
+
+ protected static RpcMethodInvoker from(Method method) {
+ Optional<Class<? extends DataContainer>> input = BindingReflections.resolveRpcInputClass(method);
+ try {
+ MethodHandle methodHandle = LOOKUP.unreflect(method);
+ if(input.isPresent()) {
+ return new RpcMethodInvokerWithInput(methodHandle);
+ }
+ return new RpcMethodInvokerWithoutInput(methodHandle);
+ } catch (IllegalAccessException e) {
+ throw new IllegalStateException("Lookup on public method failed.",e);
+ }
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.binding.util;
+
+import com.google.common.base.Throwables;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodType;
+import java.util.concurrent.Future;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.RpcService;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+
+class RpcMethodInvokerWithInput extends RpcMethodInvoker {
+
+ private static final MethodType INVOCATION_SIGNATURE = MethodType.methodType(Future.class, RpcService.class,DataObject.class);
+ private final MethodHandle handle;
+
+ RpcMethodInvokerWithInput(MethodHandle methodHandle) {
+ this.handle = methodHandle.asType(INVOCATION_SIGNATURE);
+ }
+
+ @Override
+ public Future<RpcResult<?>> invokeOn(RpcService impl, DataObject input) {
+ try {
+ return (Future<RpcResult<?>>) handle.invokeExact(impl,input);
+ } catch (Throwable e) {
+ throw Throwables.propagate(e);
+ }
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.binding.util;
+
+import com.google.common.base.Throwables;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodType;
+import java.util.concurrent.Future;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.RpcService;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+
+class RpcMethodInvokerWithoutInput extends RpcMethodInvoker {
+
+ private static final MethodType INVOCATION_SIGNATURE = MethodType.methodType(Future.class, RpcService.class);
+ private final MethodHandle handle;
+
+ RpcMethodInvokerWithoutInput(MethodHandle methodHandle) {
+ this.handle = methodHandle.asType(INVOCATION_SIGNATURE);
+ }
+
+ @Override
+ public Future<RpcResult<?>> invokeOn(RpcService impl, DataObject input) {
+ try {
+ return (Future<RpcResult<?>>) handle.invokeExact(impl);
+ } catch (Throwable e) {
+ throw Throwables.propagate(e);
+ }
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.binding.util;
+
+import com.google.common.base.Preconditions;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMap.Builder;
+import java.lang.reflect.Method;
+import java.util.Map;
+import java.util.concurrent.Future;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.BindingMapping;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.RpcService;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+
+/**
+ * Provides single method invocation of RPCs on supplied instance.
+ *
+ * Rpc Service invoker provides common invocation interface for any subtype of {@link RpcService}.
+ * via {@link #invokeRpc(RpcService, QName, DataObject)} method.
+ *
+ *
+ *
+ */
+public final class RpcServiceInvoker {
+
+ private static final LoadingCache<Class<? extends RpcService>, RpcServiceInvoker> INVOKERS = CacheBuilder.newBuilder()
+ .weakKeys()
+ .build(new CacheLoader<Class<? extends RpcService>, RpcServiceInvoker>() {
+
+ @Override
+ public RpcServiceInvoker load(Class<? extends RpcService> key) throws Exception {
+ return createInvoker(key);
+ }
+
+ });
+
+ private final Map<String, RpcMethodInvoker> methodInvokers;
+
+ private RpcServiceInvoker(Map<String, RpcMethodInvoker> methodInvokers) {
+ this.methodInvokers = Preconditions.checkNotNull(methodInvokers);
+ }
+
+ /**
+ *
+ * Creates RPCServiceInvoker for specified RpcService type
+ *
+ * @param type RpcService interface, which was generated from model.
+ * @return Cached instance of {@link RpcServiceInvoker} for supplied RPC type.
+ *
+ */
+ public static RpcServiceInvoker from(Class<? extends RpcService> type) {
+ Preconditions.checkArgument(type.isInterface());
+ Preconditions.checkArgument(BindingReflections.isBindingClass(type));
+ return INVOKERS.getUnchecked(type);
+ }
+
+ /**
+ * Invokes supplied RPC on provided implementation of RPC Service.
+ *
+ * @param impl Imlementation on which RPC should be invoked.
+ * @param rpcName Name of RPC to be invoked.
+ * @param input Input data for RPC.
+ * @return Future which will complete once rpc procesing is finished.
+ */
+ public Future<RpcResult<?>> invokeRpc(@Nonnull RpcService impl, @Nonnull QName rpcName,@Nullable DataObject input ) {
+ Preconditions.checkNotNull(impl, "implemetation must be supplied");
+ return invoke(impl,BindingMapping.getMethodName(rpcName),input);
+ }
+
+ private static RpcServiceInvoker createInvoker(Class<? extends RpcService> key) {
+ return new RpcServiceInvoker(createInvokerMap(key));
+ }
+
+ private static Map<String, RpcMethodInvoker> createInvokerMap(Class<? extends RpcService> key) {
+ Builder<String, RpcMethodInvoker> ret = ImmutableMap.<String, RpcMethodInvoker>builder();
+ for(Method method : key.getMethods()) {
+ if(BindingReflections.isRpcMethod(method)) {
+ ret.put(method.getName(), RpcMethodInvoker.from(method));
+ }
+
+ }
+ return ret.build();
+ }
+
+ private Future<RpcResult<?>> invoke(RpcService impl, String methodName, DataObject input) {
+ RpcMethodInvoker invoker = methodInvokers.get(methodName);
+ Preconditions.checkArgument(invoker != null,"Supplied rpc is not valid for implementation %s",impl);
+ return invoker.invokeOn(impl, input);
+ }
+}
package org.opendaylight.yangtools.yang.data.api;
import java.util.Map;
-
import org.opendaylight.yangtools.yang.common.QName;
/**
- *
- * Container of attributes, which may be attached to {@link Node}
- *
+ *
+ * Container of attributes, which may be attached to nodes.
+ *
*/
public interface AttributesContainer {
/**
* Returns immutable map of QName and value of the attribute.
- *
+ *
* @return immutable map of attribute names and values.
*/
Map<QName, String> getAttributes();
/**
* Returns attribute value by supplied QName
- *
- *
+ *
+ *
* @param name Attribute name
* @return Value of attribute if present, null otherwise.
*/
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-
-/**
- * Composite node represents a branch in the data tree, which could contain
- * nested composite nodes or leaf nodes. In the terms of the XML the simple node
- * is element which does not text data directly (CDATA or PCDATA), only other
- * nodes. The composite node is the manifestation of the following data schema
- * constructs in the YANG:
- *
- * <ul>
- * <li><b>container</b> - the composite node represents the YANG container and
- * could contain all children schema nodes of that container</li>
- * <li><b>item</b> in the <b>list</b> - the composite node represents one item
- * in the YANG list and could contain all children schema nodes of that list
- * item.</li>
- * <li><b>anyxml</b></li>
- * </ul>
- *
- * @deprecated Use {@link NormalizedNodeContainer} instead.
- */
-@Deprecated
-public interface CompositeNode extends Node<List<Node<?>>>, NodeModification, Map<QName,List<Node<?>>> {
-
- /**
- * Returns a list of children as seens in resulting XML serialization
- * defined by YANG specification.
- *
- * @return
- *
- * @deprecated Use {@link #getValue()} instead.
- */
- @Deprecated
- List<Node<?>> getChildren();
-
- List<CompositeNode> getCompositesByName(QName children);
-
- List<CompositeNode> getCompositesByName(String children);
-
- List<SimpleNode<?>> getSimpleNodesByName(QName children);
-
- List<SimpleNode<?>> getSimpleNodesByName(String children);
-
- CompositeNode getFirstCompositeByName(QName container);
-
- SimpleNode<?> getFirstSimpleByName(QName leaf);
-
- /**
- * @return cast self to mutable, if possible
- */
- @Deprecated
- MutableCompositeNode asMutable();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import java.util.List;
-
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-
-
-/**
- * @author michal.rehak
- *
- * @deprecated Deprecated in favor of {@link NormalizedNodeContainer} classes.
- */
-@Deprecated
-public interface MutableCompositeNode extends MutableNode<List<Node<?>>>, CompositeNode {
-
- /**
- * update internal map
- */
- @Deprecated
- void init();
-
- /**
- * @return original node, if available
- */
- CompositeNode getOriginal();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import org.opendaylight.yangtools.concepts.Mutable;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-
-/**
- * Base representation of node in the data tree, defines basic parameters of
- * node such as a QName.
- *
- *
- * @param <T>
- *
- * @deprecated Use {@link NormalizedNode} instead.
- */
-@Deprecated
-public interface MutableNode<T> extends Node<T>,Mutable {
-
- /**
- * @param parent value to set
- */
- void setParent(CompositeNode parent);
-
- /**
- * @param value value to set (children list or leaf value)
- */
- @Override
- T setValue(T value);
-
- /**
- * @param action value to set
- */
- void setModifyAction(ModifyAction action);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-
-/**
- * @author michal.rehak
- * @param <T> node value type
- *
- * @deprecated Use {@link NormalizedNode} instead.
- */
-@Deprecated
-public interface MutableSimpleNode<T> extends MutableNode<T>, SimpleNode<T> {
-
- /**
- * @return original node, if available
- */
- SimpleNode<T> getOriginal();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import java.util.Map.Entry;
-
-import org.opendaylight.yangtools.yang.common.QName;
-
-/**
- * Base representation of node in the data tree, defines basic parameters of
- * node such as a QName.
- *
- *
- * @param <T>
- */
-public interface Node<T> extends Entry<QName, T> {
-
- /**
- * Returns the name of the Node
- *
- * @return qName of node
- */
- QName getNodeType();
-
- /**
- * Returns parent node
- *
- * @return parent node
- * @deprecated Unused, Deprecated because reference to parent disallows of sharing one instance
- * in multiple trees / subtress.
- */
- @Deprecated
- CompositeNode getParent();
-
- /**
- * Returns the value that holds current node, if no value is defined method
- * can return <code>null</code>
- *
- * @return Returns the value that holds current node.
- */
- @Override
- T getValue();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use {@link org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes} instead.
- */
-@Deprecated
-public interface NodeModificationBuilder {
-
- Node<?> getMutableEquivalent(Node<?> originalNode);
-
- CompositeNode buildDiffTree();
-
- void mergeNode(MutableCompositeNode alteredNode);
-
- void removeNode(MutableCompositeNode deadNode);
-
- void removeNode(MutableSimpleNode<?> deadNode);
-
- void deleteNode(MutableSimpleNode<?> deadNode);
-
- void deleteNode(MutableCompositeNode deadNode);
-
- void replaceNode(MutableCompositeNode replacementNode);
-
- void replaceNode(MutableSimpleNode<?> replacementNode);
-
- void addNode(MutableCompositeNode newNode);
-
- void addNode(MutableSimpleNode<?> newNode);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * Simple node represents a leaf in the data tree, which does not contain any
- * nested nodes, but the value of node. In the terms of the XML the simple node
- * is element which contains only text data (CDATA or PCDATA). The simple node
- * is the manifestation of the following data schema constructs in YANG:
- * <ul>
- * <li><b>leaf</b> - simple node could represent YANG leafs of all types except
- * the empty type, which in XML form is similar to the empty container.</li>
- * <li><b>item</b> in <b>leaf-list</b></li>
- * </ul>
- *
- *
- * @param <T>
- *
- * @deprecated Use {@link NormalizedNode} instead.
- */
-@Deprecated
-public interface SimpleNode<T> extends Node<T>, NodeModification {
-
- /**
- * @return cast self to mutable, if possible
- */
- MutableSimpleNode<T> asMutable();
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api.codec;
-
-import org.opendaylight.yangtools.concepts.Codec;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface DataNodeCodec<I> extends Codec<I, Node<?>> {
- @Override
- Node<?> deserialize(I input);
-
- @Override
- I serialize(Node<?> input);
-}
*/
package org.opendaylight.yangtools.yang.data.api.schema;
+import javax.xml.transform.dom.DOMSource;
import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.Node;
/**
* Anyxml normalizedNode.
- *
- * <p>
- * This node contains values for anyxml as either SimpleNode or CompositeNode.
- * The concrete value depends on the current value of anyxml node.
- * </p>
- *
- * <p>
- * For yang node: anyxml foo;
- *
- * <ul>
- * <li>
- * with xml value:
- * <pre>
- * {@code <foo>justSomeString</foo>}
- * </pre>
- * this AnyXmlNode returns SimpleNode with QName{namespace=someNamespace, revision=someRevision, localName=foo} and value="justSomeString"
- * </li>
- *
- * <li>
- * but with xml value:
- * <pre>
- * {@code <foo><bar>stringInXml</bar></foo>}
- * </pre>
- * this AnyXmlNode returns CompositeNode with QName{}namespace=someNamespace, revision=someRevision, localName=foo}
- * and values [SimpleNode with QName{}namespace=someNamespace, revision=someRevision, localName=bar} and value="stringInXml"]
- * </li>
- *
- * </ul>
*/
-public interface AnyXmlNode extends AttributesContainer, DataContainerChild<NodeIdentifier, Node<?>> {
+public interface AnyXmlNode extends AttributesContainer, DataContainerChild<NodeIdentifier, DOMSource> {
@Override
NodeIdentifier getIdentifier();
/**
- * @return anyxml node value represented as SimpleNode or CompositeNode.
- * Returned node contains top level element that duplicates the anyxml node.
+ * @return anyxml node value represented as DOMSource.
+ * Returned source contains top level element that duplicates the anyxml node.
*/
@Override
- Node<?> getValue();
+ DOMSource getValue();
}
*/
package org.opendaylight.yangtools.yang.data.api.schema;
+import java.util.Collection;
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.PathArgument;
/**
*
* Data instance of <code>augment</code> assiociated with parent node.
- *
+ *
* Augmentation is addition of subtree defined by other external YANG Model and
* is schema for subtree is described by instance of {@link AugmentationSchema}
* associated with parent node of this node.
public interface AugmentationNode extends //
MixinNode, //
DataContainerNode<AugmentationIdentifier>,
- DataContainerChild<YangInstanceIdentifier.AugmentationIdentifier, Iterable<DataContainerChild<? extends PathArgument, ?>>> {
+ DataContainerChild<YangInstanceIdentifier.AugmentationIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> {
/**
* Gets identifier of augmentation node
- *
- * Returned identifier of augmentation node contains all possible
+ *
+ * Returned identifier of augmentation node contains all possible
* direct child QNames.
- *
+ *
* This is sufficient to identify instance of augmentation,
* since RFC6020 states that <code>augment</code> that augment
- * statement must not add multiple nodes from same namespace
+ * statement must not add multiple nodes from same namespace
* / module
* to the target node.
- *
+ *
* @return Identifier which uniquelly identifies augmentation in particular subtree.
- *
+ *
*/
@Override
public AugmentationIdentifier getIdentifier();
*/
package org.opendaylight.yangtools.yang.data.api.schema;
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
public interface ChoiceNode extends //
MixinNode, //
DataContainerNode<NodeIdentifier>,
- DataContainerChild<NodeIdentifier, Iterable<DataContainerChild<? extends PathArgument, ?>>> {
+ DataContainerChild<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> {
}
*/
package org.opendaylight.yangtools.yang.data.api.schema;
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
/**
* Data subtree with cardinality 0..1 in the context of parent node
- *
+ *
* Node which does not have value but contains valid {@link DataContainerChild} nodes.
- *
+ *
* Schema of this node is described by instance of {@link org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode}.
- *
+ *
*/
public interface ContainerNode extends //
AttributesContainer,
DataContainerNode<NodeIdentifier>,
- DataContainerChild<NodeIdentifier, Iterable<DataContainerChild<? extends PathArgument, ?>>> {
+ DataContainerChild<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> {
}
*/
package org.opendaylight.yangtools.yang.data.api.schema;
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
/**
* @return Iteration of all child nodes
*/
@Override
- Iterable<DataContainerChild<? extends PathArgument, ?>> getValue();
+ Collection<DataContainerChild<? extends PathArgument, ?>> getValue();
}
*/
package org.opendaylight.yangtools.yang.data.api.schema;
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
*/
public interface LeafSetNode<T> extends
MixinNode, //
- DataContainerChild<NodeIdentifier, Iterable<LeafSetEntryNode<T>>>, //
+ DataContainerChild<NodeIdentifier, Collection<LeafSetEntryNode<T>>>, //
NormalizedNodeContainer<NodeIdentifier, NodeWithValue,LeafSetEntryNode<T>> {
}
*/
package org.opendaylight.yangtools.yang.data.api.schema;
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
*/
public interface MapNode extends //
MixinNode,
- DataContainerChild<NodeIdentifier, Iterable<MapEntryNode>>,
+ DataContainerChild<NodeIdentifier, Collection<MapEntryNode>>,
NormalizedNodeContainer<NodeIdentifier, NodeIdentifierWithPredicates, MapEntryNode> {
}
*/
package org.opendaylight.yangtools.yang.data.api.schema;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-
import com.google.common.base.Optional;
+import java.util.Collection;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
/**
* Node which is not leaf, but has child {@link NormalizedNode}s as its valzue.
- *
- *
+ *
+ *
* NormalizedNodeContainer does not have a value, but it has a child
* nodes. Definition of possible and valid child nodes is introduced
* in subclasses of this interface.
- *
+ *
* This interface should not be used directly, but rather use of of derived subinterfaces
* such as {@link DataContainerNode}, {@link MapNode}, {@link LeafSetNode}.
- *
+ *
* @param <I>
* Node Identifier type
* @param <K>
* Child Node type
*/
public interface NormalizedNodeContainer<I extends PathArgument, K extends PathArgument, V extends NormalizedNode<? extends K, ?>>
- extends NormalizedNode<I, Iterable<V>> {
+ extends NormalizedNode<I, Collection<V>> {
@Override
I getIdentifier();
/**
* Returns immutable iteration of child nodes of this node.
- *
+ *
*/
@Override
- Iterable<V> getValue();
+ Collection<V> getValue();
/**
* Returns child node identified by provided key.
- *
+ *
* @param child
* Path argument identifying child node
* @return Optional with child node if child exists.
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
+import java.util.Arrays;
import java.util.Iterator;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
}
}
- public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> tree, final YangInstanceIdentifier path) {
- checkNotNull(tree, "Tree must not be null");
- checkNotNull(path, "Path must not be null");
+ public static Optional<NormalizedNode<?, ?>> findNode(final Optional<NormalizedNode<?, ?>> parent, final Iterable<PathArgument> relativePath) {
+ checkNotNull(parent, "Parent must not be null");
+ checkNotNull(relativePath, "Relative path must not be null");
- Optional<NormalizedNode<?, ?>> currentNode = Optional.<NormalizedNode<?, ?>> of(tree);
- final Iterator<PathArgument> pathIterator = path.getPathArguments().iterator();
+ Optional<NormalizedNode<?, ?>> currentNode = parent;
+ final Iterator<PathArgument> pathIterator = relativePath.iterator();
while (currentNode.isPresent() && pathIterator.hasNext()) {
currentNode = getDirectChild(currentNode.get(), pathIterator.next());
}
return currentNode;
}
+ public static Optional<NormalizedNode<?, ?>> findNode(final Optional<NormalizedNode<?, ?>> parent, final PathArgument... relativePath) {
+ return findNode(parent, Arrays.asList(relativePath));
+ }
+
+ public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent, final Iterable<PathArgument> relativePath) {
+ return findNode(Optional.<NormalizedNode<?, ?>>fromNullable(parent), relativePath);
+ }
+
+ public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent, final PathArgument... relativePath) {
+ return findNode(parent, Arrays.asList(relativePath));
+ }
+
+ public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> tree, final YangInstanceIdentifier path) {
+ checkNotNull(tree, "Tree must not be null");
+ checkNotNull(path, "Path must not be null");
+
+ return findNode(Optional.<NormalizedNode<?, ?>>of(tree), path.getPathArguments());
+ }
+
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Optional<NormalizedNode<?, ?>> getDirectChild(final NormalizedNode<?, ?> node, final PathArgument pathArg) {
if (node instanceof LeafNode<?> || node instanceof LeafSetEntryNode<?>) {
*/
package org.opendaylight.yangtools.yang.data.api.schema;
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
/**
*
* Normalized Node container which preserves user supplied ordering
- * and allows addressing of child elements by positiion.
+ * and allows addressing of child elements by position.
*
- * @param <V>
+ * @param <V> child type
*/
-public interface OrderedNodeContainer<V extends NormalizedNode<?, ?>> extends MixinNode, NormalizedNode<NodeIdentifier, Iterable<V>> {
+public interface OrderedNodeContainer<V extends NormalizedNode<?, ?>> extends MixinNode, NormalizedNode<NodeIdentifier, Collection<V>> {
/**
* Returns child node by position
*/
package org.opendaylight.yangtools.yang.data.api.schema;
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
*
*/
public interface UnkeyedListNode extends
- DataContainerChild<NodeIdentifier, Iterable<UnkeyedListEntryNode>>,
+ DataContainerChild<NodeIdentifier, Collection<UnkeyedListEntryNode>>,
OrderedNodeContainer<UnkeyedListEntryNode> {
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.api.schema.stream;
+
+import java.io.IOException;
+import java.util.Map;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+
+/**
+ * Extension to the NormalizedNodeStreamWriter with attribute support
+ */
+public interface NormalizedNodeStreamAttributeWriter extends NormalizedNodeStreamWriter {
+
+ void leafNode(YangInstanceIdentifier.NodeIdentifier name, Object value, Map<QName, String> attributes) throws IOException, IllegalArgumentException;
+
+ void leafSetEntryNode(Object value, Map<QName, String> attributes) throws IOException, IllegalArgumentException;
+
+ void startContainerNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint, Map<QName, String> attributes) throws IOException, IllegalArgumentException;
+
+ void startUnkeyedListItem(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint, Map<QName, String> attributes) throws IOException, IllegalStateException;
+
+ void startMapEntryNode(YangInstanceIdentifier.NodeIdentifierWithPredicates identifier, int childSizeHint, Map<QName, String> attributes) throws IOException, IllegalArgumentException;
+}
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
-
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
-
import javax.xml.stream.XMLStreamReader;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
private boolean wasProcessAsSimpleNode(final NormalizedNode<?, ?> node) throws IOException {
if (node instanceof LeafSetEntryNode) {
final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>)node;
- writer.leafSetEntryNode(nodeAsLeafList.getValue());
+ if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+ ((NormalizedNodeStreamAttributeWriter) writer).leafSetEntryNode(nodeAsLeafList.getValue(), nodeAsLeafList.getAttributes());
+ } else {
+ writer.leafSetEntryNode(nodeAsLeafList.getValue());
+ }
return true;
} else if (node instanceof LeafNode) {
final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
- writer.leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue());
+ if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+ ((NormalizedNodeStreamAttributeWriter) writer).leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue(), nodeAsLeaf.getAttributes());
+ } else {
+ writer.leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue());
+ }
return true;
} else if (node instanceof AnyXmlNode) {
final AnyXmlNode anyXmlNode = (AnyXmlNode)node;
}
protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
- writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
+ if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+ ((NormalizedNodeStreamAttributeWriter) writer)
+ .startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
+ } else {
+ writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
+ }
return writeChildren(node.getValue());
}
private boolean wasProcessedAsCompositeNode(final NormalizedNode<?, ?> node) throws IOException {
if (node instanceof ContainerNode) {
final ContainerNode n = (ContainerNode) node;
- writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
+ if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+ ((NormalizedNodeStreamAttributeWriter) writer).startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()), n.getAttributes());
+ } else {
+ writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
+ }
return writeChildren(n.getValue());
}
if (node instanceof MapEntryNode) {
@Override
protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
- getWriter().startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
+ final NormalizedNodeStreamWriter writer = getWriter();
+ if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+ ((NormalizedNodeStreamAttributeWriter) writer).startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
+ } else {
+ writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
+ }
final Set<QName> qnames = node.getIdentifier().getKeyValues().keySet();
// Write out all the key children
* contents, it has been merged. This means that any incoming nodes which
* were present in the tree have been replaced, but their child nodes have
* been retained.
+ *
+ * @deprecated This value is never reported. Whenever it would be reported, based
+ * on the actual effects, either {@link #WRITE} or {@link #SUBTREE_MODIFIED}
+ * is reported.
*/
+ @Deprecated
MERGE,
}
package org.opendaylight.yangtools.yang.data.codec.gson;
import com.google.common.base.Preconditions;
-
import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.data.api.codec.BooleanCodec;
import org.opendaylight.yangtools.yang.data.api.codec.DecimalCodec;
* @param codec underlying codec
* @return A JSONCodec instance
*/
- public static <T> JSONCodec<T> create(final Codec<String, T> codec) {
- if (codec instanceof BooleanCodec || codec instanceof DecimalCodec ||
- codec instanceof Int8Codec || codec instanceof Int16Codec ||
- codec instanceof Int32Codec || codec instanceof Int64Codec ||
- codec instanceof Uint8Codec || codec instanceof Uint16Codec ||
- codec instanceof Uint32Codec || codec instanceof Uint64Codec) {
- return new UnquotedJSONCodec<>(codec);
+ public static JSONCodec<?> create(final Codec<String, ?> codec) {
+ if (codec instanceof BooleanCodec) {
+ return new BooleanJSONCodec((BooleanCodec<String>) codec);
+ } else if (codec instanceof DecimalCodec || codec instanceof Int8Codec
+ || codec instanceof Int16Codec || codec instanceof Int32Codec
+ || codec instanceof Int64Codec || codec instanceof Uint8Codec
+ || codec instanceof Uint16Codec || codec instanceof Uint32Codec
+ || codec instanceof Uint64Codec) {
+ return new NumberJSONCodec(codec);
+ } else {
+ return new QuotedJSONCodec<>(codec);
}
-
- return new QuotedJSONCodec<>(codec);
}
@Override
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.codec.gson;
+
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import org.opendaylight.yangtools.concepts.Codec;
+
+/**
+ * A {@link JSONCodec} which does not need double quotes in output representation.
+ *
+ * @param <T> Deserialized value type
+ */
+final class BooleanJSONCodec extends AbstractJSONCodec<Boolean> {
+ BooleanJSONCodec(final Codec<String, Boolean> codec) {
+ super(codec);
+ }
+
+ @Override
+ public boolean needQuotes() {
+ return false;
+ }
+
+ /**
+ * Serialize specified value with specified JsonWriter.
+ *
+ * @param writer JsonWriter
+ * @param value
+ */
+ @Override
+ public void serializeToWriter(JsonWriter writer, Boolean value) throws IOException {
+ writer.value(value);
+ };
+}
\ No newline at end of file
package org.opendaylight.yangtools.yang.data.codec.gson;
import java.io.IOException;
-
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
/**
private CaseNodeDataWithSchema caseNodeDataWithSchema;
- public ChoiceNodeDataWithSchema(final ChoiceNode schema) {
+ public ChoiceNodeDataWithSchema(final ChoiceSchemaNode schema) {
super(schema);
}
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
// The choice/case mess, reuse what we already popped
final DataSchemaNode choiceCandidate = schema;
- Preconditions.checkArgument(choiceCandidate instanceof ChoiceNode,
+ Preconditions.checkArgument(choiceCandidate instanceof ChoiceSchemaNode,
"Expected node of type ChoiceNode but was %s", choiceCandidate.getClass().getSimpleName());
- final ChoiceNode choiceNode = (ChoiceNode) choiceCandidate;
+ final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) choiceCandidate;
final DataSchemaNode caseCandidate = schemas.pop();
Preconditions.checkArgument(caseCandidate instanceof ChoiceCaseNode,
CompositeNodeDataWithSchema caseNodeDataWithSchema = findChoice(childNodes, choiceCandidate, caseCandidate);
if (caseNodeDataWithSchema == null) {
ChoiceNodeDataWithSchema choiceNodeDataWithSchema = new ChoiceNodeDataWithSchema(choiceNode);
- addChild(choiceNodeDataWithSchema);
+ childNodes.add(choiceNodeDataWithSchema);
caseNodeDataWithSchema = choiceNodeDataWithSchema.addCompositeChild(caseNode);
}
* node is found then it is returned, else null.
*/
AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
- if (parent instanceof AugmentationTarget && !((parent instanceof ChoiceCaseNode) || (parent instanceof ChoiceNode))) {
+ if (parent instanceof AugmentationTarget && !((parent instanceof ChoiceCaseNode) || (parent instanceof ChoiceSchemaNode))) {
for (AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
if (childInAugmentation != null) {
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
import org.opendaylight.yangtools.concepts.Codec;
interface JSONCodec<T> extends Codec<String, T> {
+ // FIXME: Unused, remove once we are sure we do not need this anymore.
boolean needQuotes();
+
+
+ /**
+ * Serialize specified value with specified JsonWriter.
+ *
+ * @param writer JsonWriter
+ * @param value
+ */
+ void serializeToWriter(JsonWriter writer, T value) throws IOException;
}
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
-
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
import org.opendaylight.yangtools.yang.model.util.IdentityrefType;
import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
+import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Beta
public final class JSONCodecFactory {
private static final Logger LOG = LoggerFactory.getLogger(JSONCodecFactory.class);
- private static final JSONCodec<Object> LEAFREF_DEFAULT_CODEC = new JSONLeafrefCodec();
private static final JSONCodec<Object> NULL_CODEC = new JSONCodec<Object>() {
@Override
public Object deserialize(final String input) {
public boolean needQuotes() {
return false;
}
- };
- private static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
- TypeDefinition<?> superType = type;
- while (superType.getBaseType() != null) {
- superType = superType.getBaseType();
+ @Override
+ public void serializeToWriter(JsonWriter writer, Object value) throws IOException {
+ // NOOP since codec is unkwown.
+ LOG.warn("Call of the serializeToWriter method on JSONCodecFactory.NULL_CODEC object. No operation performed.");
}
- return superType;
- }
+ };
- private final LoadingCache<TypeDefinition<?>, JSONCodec<Object>> codecs =
- CacheBuilder.newBuilder().softValues().build(new CacheLoader<TypeDefinition<?>, JSONCodec<Object>>() {
- @SuppressWarnings("unchecked")
+ private final LoadingCache<DataSchemaNode, JSONCodec<Object>> codecs =
+ CacheBuilder.newBuilder().softValues().build(new CacheLoader<DataSchemaNode, JSONCodec<Object>>() {
@Override
- public JSONCodec<Object> load(final TypeDefinition<?> key) throws Exception {
- final TypeDefinition<?> type = resolveBaseTypeFrom(key);
-
- if (type instanceof InstanceIdentifierType) {
- return (JSONCodec<Object>) iidCodec;
- }
- if (type instanceof IdentityrefType) {
- return (JSONCodec<Object>) idrefCodec;
+ public JSONCodec<Object> load(final DataSchemaNode key) throws Exception {
+ final TypeDefinition<?> type;
+ if (key instanceof LeafSchemaNode) {
+ type = ((LeafSchemaNode) key).getType();
+ } else if (key instanceof LeafListSchemaNode) {
+ type = ((LeafListSchemaNode) key).getType();
+ } else {
+ throw new IllegalArgumentException("Not supported node type " + key.getClass().getName());
}
- if (type instanceof LeafrefTypeDefinition) {
- return LEAFREF_DEFAULT_CODEC;
- }
-
- final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = TypeDefinitionAwareCodec.from(type);
- if (codec == null) {
- LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
- return NULL_CODEC;
- }
-
- return AbstractJSONCodec.create(codec);
+ return createCodec(key,type);
}
});
return new JSONCodecFactory(context);
}
+ private static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
+ TypeDefinition<?> superType = type;
+ while (superType.getBaseType() != null) {
+ superType = superType.getBaseType();
+ }
+ return superType;
+ }
+
+ private JSONCodec<Object> createCodec(DataSchemaNode key, TypeDefinition<?> type) {
+ TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
+ if (baseType instanceof LeafrefTypeDefinition) {
+ return createReferencedTypeCodec(key, (LeafrefTypeDefinition) baseType);
+ }
+ return createFromSimpleType(type);
+ }
+
+ private JSONCodec<Object> createReferencedTypeCodec(DataSchemaNode schema,
+ LeafrefTypeDefinition type) {
+ // FIXME: Verify if this does indeed support leafref of leafref
+ TypeDefinition<?> referencedType =
+ SchemaContextUtil.getBaseTypeForLeafRef(type, getSchemaContext(), schema);
+ return createFromSimpleType(referencedType);
+ }
+
+ @SuppressWarnings("unchecked")
+ private JSONCodec<Object> createFromSimpleType(TypeDefinition<?> type) {
+ final TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
+ if (baseType instanceof InstanceIdentifierType) {
+ return (JSONCodec<Object>) iidCodec;
+ }
+ if (baseType instanceof IdentityrefType) {
+ return (JSONCodec<Object>) idrefCodec;
+ }
+
+ final TypeDefinitionAwareCodec<Object, ?> codec = TypeDefinitionAwareCodec.from(type);
+ if (codec == null) {
+ LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName()
+ .getLocalName());
+ return NULL_CODEC;
+ }
+ return (JSONCodec<Object>) AbstractJSONCodec.create(codec);
+ }
+
SchemaContext getSchemaContext() {
return schemaContext;
}
- JSONCodec<Object> codecFor(final TypeDefinition<?> typeDefinition) {
- return codecs.getUnchecked(typeDefinition);
+ JSONCodec<Object> codecFor(DataSchemaNode schema) {
+ return codecs.getUnchecked(schema);
}
+
}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.codec.gson;
-
-import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
-
-final class JSONLeafrefCodec implements JSONCodec<Object>, LeafrefCodec<String> {
- @Override
- public Object deserialize(final String input) {
- return input;
- }
-
- @Override
- public String serialize(final Object input) {
- return String.valueOf(input);
- }
-
- @Override
- public boolean needQuotes() {
- return true;
- }
-}
\ No newline at end of file
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
-import com.google.common.base.CharMatcher;
import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.Writer;
*
* Values of leaf and leaf-list are NOT translated according to codecs.
*
- * FIXME: rewrite this in terms of {@link JsonWriter}.
*/
public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
/**
*/
private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
- /**
- * Matcher used to check if a string needs to be escaped.
- */
- private static final CharMatcher JSON_ILLEGAL_STRING_CHARACTERS = CharMatcher.anyOf("\\\"\n\r");
-
private final SchemaTracker tracker;
private final JSONCodecFactory codecs;
- private final Writer writer;
- private final String indent;
+ private final JsonWriter writer;
private JSONStreamWriterContext context;
- private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path,
- final Writer writer, final URI initialNs, final int indentSize) {
- this.writer = Preconditions.checkNotNull(writer);
-
- Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
- if (indentSize != 0) {
- indent = Strings.repeat(" ", indentSize);
- } else {
- indent = null;
- }
+ private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path, JsonWriter JsonWriter, JSONStreamWriterRootContext rootContext) {
+ this.writer = Preconditions.checkNotNull(JsonWriter);
this.codecs = Preconditions.checkNotNull(codecFactory);
this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
- this.context = new JSONStreamWriterRootContext(initialNs);
+ this.context = Preconditions.checkNotNull(rootContext);
}
/**
* Create a new stream writer, which writes to the specified {@link Writer}.
*
+ * This instance of writer can be used only to emit one top level element,
+ * therwise it will produce incorrect JSON.
+ *
* @param schemaContext Schema context
* @param writer Output writer
* @return A stream writer instance
*/
public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
- return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, 0);
+ return create(schemaContext, SchemaPath.ROOT, null, writer);
}
/**
* Create a new stream writer, which writes to the specified {@link Writer}.
*
+ * This instance of writer can be used only to emit one top level element,
+ * therwise it will produce incorrect JSON.
+ *
* @param schemaContext Schema context
* @param path Root schemapath
* @param writer Output writer
* @return A stream writer instance
*/
public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path, final Writer writer) {
- return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, null, 0);
+ return create(schemaContext, path, null, writer);
}
/**
* Create a new stream writer, which writes to the specified {@link Writer}.
*
+ * This instance of writer can be used only to emit one top level element,
+ * therwise it will produce incorrect JSON.
+ *
* @param schemaContext Schema context
* @param path Root schemapath
* @param writer Output writer
*/
public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path,
final URI initialNs, final Writer writer) {
- return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, initialNs, 0);
+ return createExclusiveWriter(JSONCodecFactory.create(schemaContext), path, initialNs, JsonWriterFactory.createJsonWriter(writer));
}
/**
* Create a new stream writer, which writes to the specified output stream.
*
+ * This instance of writer can be used only to emit one top level element,
+ * therwise it will produce incorrect JSON.
+ *
* @param schemaContext Schema context
* @param writer Output writer
* @param indentSize indentation size
* @return A stream writer instance
*/
public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
- return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, indentSize);
+ return createExclusiveWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, null,JsonWriterFactory.createJsonWriter(writer, indentSize));
}
/**
* Create a new stream writer, which writes to the specified output stream. The codec factory
* can be reused between multiple writers.
*
+ * This instance of writer can be used only to emit one top level element,
+ * therwise it will produce incorrect JSON.
+ *
* @param codecFactory JSON codec factory
* @param writer Output writer
* @param indentSize indentation size
* @return A stream writer instance
*/
public static NormalizedNodeStreamWriter create(final JSONCodecFactory codecFactory, final Writer writer, final int indentSize) {
- return new JSONNormalizedNodeStreamWriter(codecFactory, SchemaPath.ROOT, writer, null, indentSize);
+ return createExclusiveWriter(codecFactory, SchemaPath.ROOT, null, JsonWriterFactory.createJsonWriter(writer,indentSize));
+ }
+
+ /**
+ * Create a new stream writer, which writes to the specified output stream.
+ *
+ * This instance of writer can be used only to emit one top level element,
+ * therwise it will produce incorrect JSON.
+ *
+ * @param schemaContext Schema context
+ * @param path Schema Path
+ * @param initialNs Initial namespace
+ * @param jsonWriter JsonWriter
+ * @return A stream writer instance
+ */
+ public static NormalizedNodeStreamWriter create(SchemaContext schemaContext, SchemaPath path, URI initialNs,
+ JsonWriter jsonWriter) {
+ return createExclusiveWriter(JSONCodecFactory.create(schemaContext), path, initialNs, jsonWriter);
+ }
+
+ /**
+ * Create a new stream writer, which writes to the specified output stream.
+ *
+ * The codec factory can be reused between multiple writers.
+ *
+ * Returned writer is exclusive user of JsonWriter, which means it will start
+ * top-level JSON element and ends it.
+ *
+ * This instance of writer can be used only to emit one top level element,
+ * therwise it will produce incorrect JSON.
+ *
+ * @param codecFactory JSON codec factory
+ * @param path Schema Path
+ * @param initialNs Initial namespace
+ * @param jsonWriter JsonWriter
+ * @return A stream writer instance
+ */
+ public static NormalizedNodeStreamWriter createExclusiveWriter(JSONCodecFactory codecFactory, SchemaPath path, URI initialNs, JsonWriter jsonWriter) {
+ return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
+ }
+
+ /**
+ * Create a new stream writer, which writes to the specified output stream.
+ *
+ * The codec factory can be reused between multiple writers.
+ *
+ * Returned writer can be used emit multiple top level element,
+ * but does not start / close parent JSON object, which must be done
+ * by user providing {@code jsonWriter} instance in order for
+ * JSON to be valid.
+ *
+ * @param codecFactory JSON codec factory
+ * @param path Schema Path
+ * @param initialNs Initial namespace
+ * @param jsonWriter JsonWriter
+ * @return A stream writer instance
+ */
+ public static NormalizedNodeStreamWriter createNestedWriter(JSONCodecFactory codecFactory, SchemaPath path, URI initialNs, JsonWriter jsonWriter) {
+ return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
}
@Override
public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
final LeafSchemaNode schema = tracker.leafNode(name);
- final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
-
- context.emittingChild(codecs.getSchemaContext(), writer, indent);
+ final JSONCodec<Object> codec = codecs.codecFor(schema);
+ context.emittingChild(codecs.getSchemaContext(), writer);
context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
- writeValue(codec.serialize(value), codec.needQuotes());
+ writeValue(value, codec);
}
@Override
@Override
public void leafSetEntryNode(final Object value) throws IOException {
final LeafListSchemaNode schema = tracker.leafSetEntryNode();
- final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
-
- context.emittingChild(codecs.getSchemaContext(), writer, indent);
- writeValue(codec.serialize(value), codec.needQuotes());
+ final JSONCodec<Object> codec = codecs.codecFor(schema);
+ context.emittingChild(codecs.getSchemaContext(), writer);
+ writeValue(value, codec);
}
/*
final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
// FIXME: should have a codec based on this :)
- context.emittingChild(codecs.getSchemaContext(), writer, indent);
+ context.emittingChild(codecs.getSchemaContext(), writer);
context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
- writeValue(String.valueOf(value), true);
+ // FIXME this kind of serialization is incorrect since the value for AnyXml is now a DOMSource
+ writer.value(String.valueOf(value));
}
@Override
public void endNode() throws IOException {
tracker.endNode();
- context = context.endNode(codecs.getSchemaContext(), writer, indent);
- }
+ context = context.endNode(codecs.getSchemaContext(), writer);
- private void writeValue(final String str, final boolean needQuotes) throws IOException {
- if (needQuotes) {
- writer.append('"');
-
- final int needEscape = JSON_ILLEGAL_STRING_CHARACTERS.countIn(str);
- if (needEscape != 0) {
- final char[] escaped = new char[str.length() + needEscape];
- int offset = 0;
-
- for (int i = 0; i < str.length(); i++) {
- final char c = str.charAt(i);
- if (JSON_ILLEGAL_STRING_CHARACTERS.matches(c)) {
- escaped[offset++] = '\\';
- }
- escaped[offset++] = c;
- }
- writer.write(escaped);
- } else {
- writer.append(str);
- }
-
- writer.append('"');
- } else {
- writer.append(str);
+ if(context instanceof JSONStreamWriterRootContext) {
+ context.emitEnd(writer);
}
}
+ private void writeValue(Object value, JSONCodec<Object> codec)
+ throws IOException {
+ codec.serializeToWriter(writer,value);
+ }
+
@Override
public void flush() throws IOException {
writer.flush();
writer.close();
}
+
+
}
package org.opendaylight.yangtools.yang.data.codec.gson;
import com.google.common.base.Preconditions;
+import com.google.gson.stream.JsonWriter;
import java.io.IOException;
-import java.io.Writer;
+import java.io.StringWriter;
import java.net.URI;
import javax.annotation.Nonnull;
import org.opendaylight.yangtools.yang.common.QName;
private final boolean mandatory;
private final int depth;
private boolean emittedMyself = false;
- private boolean haveChild = false;
/**
* Construct a new context.
* @param qname Namespace/name tuple
* @throws IOException when the writer reports it
*/
- final void writeChildJsonIdentifier(final SchemaContext schema, final Writer writer, final QName qname) throws IOException {
- writer.append('"');
+ final void writeChildJsonIdentifier(final SchemaContext schema, final JsonWriter writer, final QName qname) throws IOException {
+ StringWriter strWriter = new StringWriter();
// Prepend module name if namespaces do not match
final URI ns = qname.getNamespace();
if (!ns.equals(getNamespace())) {
final Module module = schema.findModuleByNamespaceAndRevision(ns, null);
Preconditions.checkArgument(module != null, "Could not find module for namespace {}", ns);
- writer.append(module.getName());
- writer.append(':');
+ strWriter.append(module.getName());
+ strWriter.append(':');
}
+ strWriter.append(qname.getLocalName());
- writer.append(qname.getLocalName());
- writer.append("\":");
+ writer.name(strWriter.toString());
}
/**
* @param qname Namespace/name tuple
* @throws IOException when the writer reports it
*/
- protected final void writeMyJsonIdentifier(final SchemaContext schema, final Writer writer, final QName qname) throws IOException {
+ protected final void writeMyJsonIdentifier(final SchemaContext schema, final JsonWriter writer, final QName qname) throws IOException {
parent.writeChildJsonIdentifier(schema, writer, qname);
}
* @param writer Output writer
* @throws IOException
*/
- protected abstract void emitStart(final SchemaContext schema, final Writer writer) throws IOException;
+ protected abstract void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException;
/**
* Emit the end of an element.
* @param writer Output writer
* @throws IOException
*/
- protected abstract void emitEnd(final Writer writer) throws IOException;
+ protected abstract void emitEnd(final JsonWriter writer) throws IOException;
- private final void emitMyself(final SchemaContext schema, final Writer writer, final String indent) throws IOException {
+ private final void emitMyself(final SchemaContext schema, final JsonWriter writer) throws IOException {
if (!emittedMyself) {
if (parent != null) {
- parent.emittingChild(schema, writer, indent);
+ parent.emittingChild(schema, writer);
}
emitStart(schema, writer);
*
* @param schema Schema context
* @param writer Output writer
- * @param indent Indentation string
* @throws IOException when writer reports it
*/
- final void emittingChild(final SchemaContext schema, final Writer writer, final String indent) throws IOException {
- emitMyself(schema, writer, indent);
- if (haveChild) {
- writer.append(',');
- }
-
- if (indent != null) {
- writer.append('\n');
-
- for (int i = 0; i < depth; i++) {
- writer.append(indent);
- }
- }
- haveChild = true;
+ final void emittingChild(final SchemaContext schema, final JsonWriter writer) throws IOException {
+ emitMyself(schema, writer);
}
/**
*
* @param schema Schema context
* @param writer Output writer
- * @param indent Indentation string
* @return Parent node context
* @throws IOException when writer reports it
* @throws IllegalArgumentException if this node cannot be ended (e.g. root)
*/
- final JSONStreamWriterContext endNode(final SchemaContext schema, final Writer writer, final String indent) throws IOException {
+ final JSONStreamWriterContext endNode(final SchemaContext schema, final JsonWriter writer) throws IOException {
if (!emittedMyself && mandatory) {
- emitMyself(schema, writer, indent);
+ emitMyself(schema, writer);
}
if (emittedMyself) {
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.codec.gson;
+
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.net.URI;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+final class JSONStreamWriterExclusiveRootContext extends JSONStreamWriterRootContext {
+ JSONStreamWriterExclusiveRootContext(final URI namespace) {
+ super(namespace);
+ }
+
+ @Override
+ protected void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException {
+ writer.beginObject();
+ }
+
+ @Override
+ protected void emitEnd(final JsonWriter writer) throws IOException {
+ writer.endObject();
+ }
+}
package org.opendaylight.yangtools.yang.data.codec.gson;
import com.google.common.base.Preconditions;
+import com.google.gson.stream.JsonWriter;
+
-import java.io.Writer;
/**
* A virtual recursion level in {@link JSONNormalizedNodeStreamWriter}, used for nodes
}
@Override
- protected void emitEnd(final Writer writer) {
+ protected void emitEnd(final JsonWriter writer) {
// No-op
}
}
\ No newline at end of file
package org.opendaylight.yangtools.yang.data.codec.gson;
import com.google.common.base.Preconditions;
+import com.google.gson.stream.JsonWriter;
import java.io.IOException;
-import java.io.Writer;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
}
@Override
- protected void emitStart(final SchemaContext schema, final Writer writer) throws IOException {
+ protected void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException {
writeMyJsonIdentifier(schema, writer, getQName());
- writer.append('[');
+ writer.beginArray();
}
@Override
- protected void emitEnd(final Writer writer) throws IOException {
- writer.append(']');
+ protected void emitEnd(final JsonWriter writer) throws IOException {
+ writer.endArray();
}
}
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
+import com.google.gson.stream.JsonWriter;
import java.io.IOException;
-import java.io.Writer;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
/**
* A recursion level of {@link JSONNormalizedNodeStreamWriter}, which represents
* a JSON object which has to be prefixed with its identifier -- such as a
}
@Override
- protected void emitStart(final SchemaContext schema, final Writer writer) throws IOException {
+ protected void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException {
writeMyJsonIdentifier(schema, writer, getQName());
super.emitStart(schema, writer);
}
package org.opendaylight.yangtools.yang.data.codec.gson;
import com.google.common.base.Preconditions;
-
+import com.google.gson.stream.JsonWriter;
import java.io.IOException;
-import java.io.Writer;
-
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
}
@Override
- protected void emitStart(final SchemaContext schema, final Writer writer) throws IOException {
- writer.append('{');
+ protected void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException {
+ writer.beginObject();
}
@Override
- protected void emitEnd(final Writer writer) throws IOException {
- writer.append('}');
+ protected void emitEnd(final JsonWriter writer) throws IOException {
+ writer.endObject();
}
}
\ No newline at end of file
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
-import java.io.Writer;
import java.net.URI;
+
/**
* The root node of a particular {@link JSONNormalizedNodeStreamWriter} instance.
* It holds the base namespace and can never be removed from the stack.
*/
-final class JSONStreamWriterRootContext extends JSONStreamWriterURIContext {
+abstract class JSONStreamWriterRootContext extends JSONStreamWriterURIContext {
+
JSONStreamWriterRootContext(final URI namespace) {
super(null, namespace);
}
- @Override
- protected void emitEnd(final Writer writer) {
- throw new IllegalArgumentException("Top-level node reached");
- }
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.codec.gson;
+
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.net.URI;
+
+final class JSONStreamWriterSharedRootContext extends JSONStreamWriterRootContext {
+ JSONStreamWriterSharedRootContext(final URI namespace) {
+ super(namespace);
+ }
+
+ @Override
+ protected void emitEnd(final JsonWriter writer) throws IOException {
+ // NOOP
+ }
+}
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
+import com.google.gson.stream.JsonWriter;
import java.io.IOException;
-import java.io.Writer;
import java.net.URI;
-
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
/**
* Abstract class tracking a virtual level of {@link JSONNormalizedNodeStreamWriter}
* recursion. It only tracks the namespace associated with this node.
}
@Override
- protected final void emitStart(final SchemaContext schema, final Writer writer) throws IOException {
+ protected void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException {
// No-op
}
}
\ No newline at end of file
package org.opendaylight.yangtools.yang.data.codec.gson;
import com.google.common.base.Preconditions;
-
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
import java.net.URI;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.util.AbstractModuleStringIdentityrefCodec;
import org.opendaylight.yangtools.yang.model.api.Module;
public boolean needQuotes() {
return true;
}
+
+ /**
+ * Serialize QName with specified JsonWriter.
+ *
+ * @param writer JsonWriter
+ * @param value QName
+ */
+ @Override
+ public void serializeToWriter(JsonWriter writer, QName value) throws IOException {
+ writer.value(serialize(value));
+ }
}
package org.opendaylight.yangtools.yang.data.codec.gson;
import com.google.common.base.Preconditions;
-
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
import java.net.URI;
-
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.util.AbstractModuleStringInstanceIdentifierCodec;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
final class JSONStringInstanceIdentifierCodec extends AbstractModuleStringInstanceIdentifierCodec implements JSONCodec<YangInstanceIdentifier> {
private final SchemaContext context;
+ private final DataSchemaContextTree dataContextTree;
JSONStringInstanceIdentifierCodec(final SchemaContext context) {
this.context = Preconditions.checkNotNull(context);
+ this.dataContextTree = DataSchemaContextTree.from(context);
}
@Override
return module == null ? null : module.getName();
}
+ @Override
+ protected DataSchemaContextTree getDataContextTree() {
+ return dataContextTree;
+ }
+
@Override
public boolean needQuotes() {
return true;
}
+
+ /**
+ * Serialize YangInstanceIdentifier with specified JsonWriter.
+ *
+ * @param writer JsonWriter
+ * @param value YangInstanceIdentifier
+ */
+ @Override
+ public void serializeToWriter(JsonWriter writer, YangInstanceIdentifier value) throws IOException {
+ writer.value(serialize(value));
+ }
}
package org.opendaylight.yangtools.yang.data.codec.gson;
import com.google.common.annotations.Beta;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.MalformedJsonException;
-
import java.io.Closeable;
import java.io.EOFException;
import java.io.Flushable;
import java.net.URI;
import java.util.ArrayDeque;
import java.util.ArrayList;
-import java.util.Arrays;
+import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
/**
* This class parses JSON elements from a GSON JsonReader. It disallows multiple elements of the same name unlike the
}
public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext, final SchemaNode parentNode ) {
+ if(parentNode instanceof RpcDefinition) {
+ return new JsonParserStream(writer, schemaContext, new RpcAsContainer((RpcDefinition) parentNode));
+ }
Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
return new JsonParserStream(writer, schemaContext, (DataSchemaNode) parentNode);
}
public JsonParserStream parse(final JsonReader reader) throws JsonIOException, JsonSyntaxException {
// code copied from gson's JsonParser and Stream classes
- boolean lenient = reader.isLenient();
+ final boolean lenient = reader.isLenient();
reader.setLenient(true);
boolean isEmpty = true;
try {
reader.peek();
isEmpty = false;
- CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
+ final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
read(reader, compositeNodeDataWithSchema);
compositeNodeDataWithSchema.write(writer);
return this;
// return read(reader);
- } catch (EOFException e) {
+ } catch (final EOFException e) {
if (isEmpty) {
return this;
// return JsonNull.INSTANCE;
}
// The stream ended prematurely so it is likely a syntax error.
throw new JsonSyntaxException(e);
- } catch (MalformedJsonException e) {
+ } catch (final MalformedJsonException e) {
throw new JsonSyntaxException(e);
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new JsonIOException(e);
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
throw new JsonSyntaxException(e);
} catch (StackOverflowError | OutOfMemoryError e) {
throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
((SimpleNodeDataWithSchema) parent).setValue(translatedValue);
}
- public void read(final JsonReader in, final AbstractNodeDataWithSchema parent) throws IOException {
+ public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
switch (in.peek()) {
case STRING:
case NUMBER:
case BEGIN_ARRAY:
in.beginArray();
while (in.hasNext()) {
- AbstractNodeDataWithSchema newChild = null;
- if (parent instanceof ListNodeDataWithSchema) {
- newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
- ((CompositeNodeDataWithSchema) parent).addChild(newChild);
- } else if (parent instanceof LeafListNodeDataWithSchema) {
- newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
- ((CompositeNodeDataWithSchema) parent).addChild(newChild);
- }
+ final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
read(in, newChild);
}
in.endArray();
return;
case BEGIN_OBJECT:
- Set<String> namesakes = new HashSet<>();
+ final Set<String> namesakes = new HashSet<>();
in.beginObject();
+ /*
+ * This allows parsing of incorrectly /as showcased/
+ * in testconf nesting of list items - eg.
+ * lists with one value are sometimes serialized
+ * without wrapping array.
+ *
+ */
+ if(isArray(parent)) {
+ parent = newArrayEntry(parent);
+ }
while (in.hasNext()) {
final String jsonElementName = in.nextName();
- final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName);
+ final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parent.getSchema());
final String localName = namespaceAndName.getName();
addNamespace(namespaceAndName.getUri());
if (namesakes.contains(jsonElementName)) {
+ getCurrentNamespace() + " doesn't exist.");
}
- AbstractNodeDataWithSchema newChild;
- newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
-// FIXME:anyxml data shouldn't be skipped but should be loaded somehow. will be specified after 17AUG2014
+ final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
+ /*
+ * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
+ * will be able to load anyxml which conforms to YANG data using these
+ * parser, for other anyxml will be harder.
+ */
if (newChild instanceof AnyXmlNodeDataWithSchema) {
in.skipValue();
} else {
}
}
- private Object translateValueByType(final String value, final DataSchemaNode node) {
- final TypeDefinition<? extends Object> typeDefinition = typeDefinition(node);
- if (typeDefinition == null) {
- return value;
- }
-
- return codecs.codecFor(typeDefinition).deserialize(value);
+ private boolean isArray(final AbstractNodeDataWithSchema parent) {
+ return parent instanceof ListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema;
}
- private static TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
- TypeDefinition<?> baseType = null;
- if (node instanceof LeafListSchemaNode) {
- baseType = ((LeafListSchemaNode) node).getType();
- } else if (node instanceof LeafSchemaNode) {
- baseType = ((LeafSchemaNode) node).getType();
- } else if (node instanceof AnyXmlSchemaNode) {
- return null;
+ private AbstractNodeDataWithSchema newArrayEntry(final AbstractNodeDataWithSchema parent) {
+ AbstractNodeDataWithSchema newChild;
+ if (parent instanceof ListNodeDataWithSchema) {
+ newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
+ } else if (parent instanceof LeafListNodeDataWithSchema) {
+ newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
} else {
- throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
+ throw new IllegalStateException("Incorrec nesting caused by parser.");
}
+ ((CompositeNodeDataWithSchema) parent).addChild(newChild);
+ return newChild;
+ }
- if (baseType != null) {
- while (baseType.getBaseType() != null) {
- baseType = baseType.getBaseType();
- }
+ private Object translateValueByType(final String value, final DataSchemaNode node) {
+ if (node instanceof AnyXmlSchemaNode) {
+ /*
+ * FIXME: Figure out some YANG extension dispatch, which will
+ * reuse JSON parsing or XML parsing - anyxml is not well-defined in
+ * JSON.
+ */
+ return value;
}
- return baseType;
+ return codecs.codecFor(node).deserialize(value);
}
private void removeNamespace() {
namespaces.pop();
}
- private void addNamespace(final Optional<URI> namespace) {
- if (!namespace.isPresent()) {
- if (namespaces.isEmpty()) {
- throw new IllegalStateException("Namespace has to be specified at top level.");
- } else {
- namespaces.push(namespaces.peek());
- }
- } else {
- namespaces.push(namespace.get());
- }
+ private void addNamespace(final URI namespace) {
+ namespaces.push(namespace);
}
- private NamespaceAndName resolveNamespace(final String childName) {
- int lastIndexOfColon = childName.lastIndexOf(':');
+ private NamespaceAndName resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
+ final int lastIndexOfColon = childName.lastIndexOf(':');
String moduleNamePart = null;
String nodeNamePart = null;
URI namespace = null;
nodeNamePart = childName;
}
- Optional<URI> namespaceOpt = namespace == null ? Optional.<URI> absent() : Optional.of(namespace);
- return new NamespaceAndName(nodeNamePart, namespaceOpt);
+ if (namespace == null) {
+ Set<URI> potentialUris = Collections.emptySet();
+ potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
+ if (potentialUris.contains(getCurrentNamespace())) {
+ namespace = getCurrentNamespace();
+ } else if (potentialUris.size() == 1) {
+ namespace = potentialUris.iterator().next();
+ } else if (potentialUris.size() > 1) {
+ throw new IllegalStateException("Choose suitable module name for element "+nodeNamePart+":"+toModuleNames(potentialUris));
+ } else if (potentialUris.isEmpty()) {
+ throw new IllegalStateException("Schema node with name "+nodeNamePart+" wasn't found.");
+ }
+ }
+
+ return new NamespaceAndName(nodeNamePart, namespace);
+ }
+
+ private String toModuleNames(final Set<URI> potentialUris) {
+ final StringBuilder builder = new StringBuilder();
+ for (final URI potentialUri : potentialUris) {
+ builder.append("\n");
+ //FIXME how to get information about revision from JSON input? currently first available is used.
+ builder.append(schema.findModuleByNamespace(potentialUri).iterator().next().getName());
+ }
+ return builder.toString();
+ }
+
+ private Set<URI> resolveAllPotentialNamespaces(final String elementName, final DataSchemaNode dataSchemaNode) {
+ final Set<URI> potentialUris = new HashSet<>();
+ final Set<ChoiceSchemaNode> choices = new HashSet<>();
+ if (dataSchemaNode instanceof DataNodeContainer) {
+ for (final DataSchemaNode childSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
+ if (childSchemaNode instanceof ChoiceSchemaNode) {
+ choices.add((ChoiceSchemaNode)childSchemaNode);
+ } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
+ potentialUris.add(childSchemaNode.getQName().getNamespace());
+ }
+ }
+
+ for (final ChoiceSchemaNode choiceNode : choices) {
+ for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
+ potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
+ }
+ }
+ }
+ return potentialUris;
}
private URI getCurrentNamespace() {
private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
final String childName, final URI namespace) {
final Deque<DataSchemaNode> result = new ArrayDeque<>();
- List<ChoiceNode> childChoices = new ArrayList<>();
+ final List<ChoiceSchemaNode> childChoices = new ArrayList<>();
if (dataSchemaNode instanceof DataNodeContainer) {
- for (DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
- if (childNode instanceof ChoiceNode) {
- childChoices.add((ChoiceNode) childNode);
+ for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
+ if (childNode instanceof ChoiceSchemaNode) {
+ childChoices.add((ChoiceSchemaNode) childNode);
} else {
final QName childQName = childNode.getQName();
if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
}
}
// try to find data schema node in choice (looking for first match)
- for (ChoiceNode choiceNode : childChoices) {
- for (ChoiceCaseNode concreteCase : choiceNode.getCases()) {
- Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
+ for (final ChoiceSchemaNode choiceNode : childChoices) {
+ for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
+ final Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
namespace);
if (!resultFromRecursion.isEmpty()) {
resultFromRecursion.push(concreteCase);
}
private static class NamespaceAndName {
- private final Optional<URI> uri;
+ private final URI uri;
private final String name;
- public NamespaceAndName(final String name, final Optional<URI> uri) {
+ public NamespaceAndName(final String name, final URI uri) {
this.name = name;
this.uri = uri;
}
return name;
}
- public Optional<URI> getUri() {
+ public URI getUri() {
return uri;
}
}
--- /dev/null
+/**
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.codec.gson;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Strings;
+import com.google.gson.stream.JsonWriter;
+import java.io.Writer;
+
+/**
+ * Factory Method class for JsonWriter creation
+ */
+@Beta
+public final class JsonWriterFactory {
+
+ private JsonWriterFactory() {
+ }
+ /**
+ * Create a new JsonWriter, which writes to the specified output writer.
+ *
+ * @param writer Output writer
+ * @return A JsonWriter instance
+ */
+ public static JsonWriter createJsonWriter(Writer writer) {
+ return new JsonWriter(writer);
+ }
+
+ /**
+ * Create a new JsonWriter, which writes to the specified output writer.
+ *
+ * @param writer Output writer
+ * @param indentSize size of the indent
+ * @return A JsonWriter instance
+ */
+ public static JsonWriter createJsonWriter(Writer writer, int indentSize) {
+ JsonWriter jsonWriter = new JsonWriter(writer);
+ final String indent = Strings.repeat(" ", indentSize);
+ jsonWriter.setIndent(indent);
+ return jsonWriter;
+ }
+
+}
@Override
public void write(final NormalizedNodeStreamWriter writer) throws IOException {
- if (((ListSchemaNode) getSchema()).getKeyDefinition().isEmpty()) {
+ final ListSchemaNode schema = (ListSchemaNode) getSchema();
+ if (schema.getKeyDefinition().isEmpty()) {
writer.startUnkeyedList(provideNodeIdentifier(), childSizeHint());
+ } else if(schema.isUserOrdered()) {
+ writer.startOrderedMapNode(provideNodeIdentifier(), childSizeHint());
} else {
writer.startMapNode(provideNodeIdentifier(), childSizeHint());
}
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
import org.opendaylight.yangtools.concepts.Codec;
/**
*
* @param <T> Deserialized value type
*/
-final class UnquotedJSONCodec<T> extends AbstractJSONCodec<T> {
- UnquotedJSONCodec(final Codec<String, T> codec) {
+final class NumberJSONCodec<T extends Number> extends AbstractJSONCodec<T > {
+ NumberJSONCodec(final Codec<String, T> codec) {
super(codec);
}
public boolean needQuotes() {
return false;
}
+
+ /**
+ * Serialize specified value with specified JsonWriter.
+ *
+ * @param writer JsonWriter
+ * @param value
+ */
+ @Override
+ public void serializeToWriter(JsonWriter writer, T value) throws IOException {
+ writer.value(value);
+ }
}
\ No newline at end of file
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
import org.opendaylight.yangtools.concepts.Codec;
/**
public boolean needQuotes() {
return true;
}
+
+ /**
+ * Serialize specified value with specified JsonWriter.
+ *
+ * @param writer JsonWriter
+ * @param value
+ */
+ @Override
+ public void serializeToWriter(JsonWriter writer, T value) throws IOException {
+ writer.value(serialize(value));
+ }
}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.codec.gson;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.UsesNode;
+
+final class RpcAsContainer implements ContainerSchemaNode {
+
+ private final RpcDefinition delegate;
+
+ @Override
+ public String getDescription() {
+ return delegate.getDescription();
+ }
+
+ @Override
+ public String getReference() {
+ return delegate.getReference();
+ }
+
+ @Override
+ public Set<TypeDefinition<?>> getTypeDefinitions() {
+ return delegate.getTypeDefinitions();
+ }
+
+ @Override
+ public Set<GroupingDefinition> getGroupings() {
+ return delegate.getGroupings();
+ }
+
+ @Override
+ public Status getStatus() {
+ return delegate.getStatus();
+ }
+
+ public ContainerSchemaNode getInput() {
+ return delegate.getInput();
+ }
+
+ public ContainerSchemaNode getOutput() {
+ return delegate.getOutput();
+ }
+
+ RpcAsContainer(final RpcDefinition parentNode) {
+ delegate = parentNode;
+ }
+
+ @Override
+ public QName getQName() {
+ return delegate.getQName();
+ }
+
+ @Override
+ public SchemaPath getPath() {
+ return delegate.getPath();
+ }
+
+ @Override
+ public List<UnknownSchemaNode> getUnknownSchemaNodes() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public DataSchemaNode getDataChildByName(final QName name) {
+ return getDataChildByName(name.getLocalName());
+ }
+
+ @Override
+ public DataSchemaNode getDataChildByName(final String name) {
+ switch (name) {
+ case "input":
+ return delegate.getInput();
+ case "output":
+ return delegate.getOutput();
+ }
+ return null;
+ }
+
+ @Override
+ public Set<UsesNode> getUses() {
+ return Collections.emptySet();
+ }
+
+ @Override
+ public Set<AugmentationSchema> getAvailableAugmentations() {
+ return Collections.emptySet();
+ }
+
+ @Override
+ public boolean isPresenceContainer() {
+ return false;
+ }
+
+ @Override
+ public Collection<DataSchemaNode> getChildNodes() {
+ final ArrayList<DataSchemaNode> ret = new ArrayList<>();
+ final ContainerSchemaNode input = getInput();
+ final ContainerSchemaNode output = getOutput();
+ if(input != null) {
+ ret.add(input);
+ }
+ if(output != null) {
+ ret.add(output);
+ }
+ return ret;
+ }
+
+ @Override
+ public boolean isAugmenting() {
+ return false;
+ }
+
+ @Override
+ public boolean isAddedByUses() {
+ return false;
+ }
+
+ @Override
+ public boolean isConfiguration() {
+ return false;
+ }
+
+ @Override
+ public ConstraintDefinition getConstraints() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
package org.opendaylight.yangtools.yang.data.codec.gson;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.loadModules;
import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.loadTextFile;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
/**
*
@Test
public void leafNodeInContainer() throws IOException, URISyntaxException {
- String inputJson = loadTextFile("/complexjson/leaf-node-in-container.json");
+ final String inputJson = loadTextFile("/complexjson/leaf-node-in-container.json");
verifyTransformationToNormalizedNode(inputJson, TestingNormalizedNodeStructuresCreator.leafNodeInContainer());
}
@Test
public void leafNodeViaAugmentationInContainer() throws IOException, URISyntaxException {
- String inputJson = loadTextFile("/complexjson/leaf-node-via-augmentation-in-container.json");
+ final String inputJson = loadTextFile("/complexjson/leaf-node-via-augmentation-in-container.json");
verifyTransformationToNormalizedNode(inputJson,
TestingNormalizedNodeStructuresCreator.leafNodeViaAugmentationInContainer());
}
@Test
public void leafListNodeInContainer() throws IOException, URISyntaxException {
- String inputJson = loadTextFile("/complexjson/leaflist-node-in-container.json");
+ final String inputJson = loadTextFile("/complexjson/leaflist-node-in-container.json");
verifyTransformationToNormalizedNode(inputJson,
TestingNormalizedNodeStructuresCreator.leafListNodeInContainer());
}
@Test
public void keyedListNodeInContainer() throws IOException, URISyntaxException {
- String inputJson = loadTextFile("/complexjson/keyed-list-node-in-container.json");
+ final String inputJson = loadTextFile("/complexjson/keyed-list-node-in-container.json");
verifyTransformationToNormalizedNode(inputJson,
TestingNormalizedNodeStructuresCreator.keyedListNodeInContainer());
}
@Test
public void choiceNodeInContainer() throws IOException, URISyntaxException {
- String inputJson = loadTextFile("/complexjson/choice-node-in-container.json");
+ final String inputJson = loadTextFile("/complexjson/choice-node-in-container.json");
verifyTransformationToNormalizedNode(inputJson, TestingNormalizedNodeStructuresCreator.choiceNodeInContainer());
}
*/
@Test
public void caseNodeAugmentationInChoiceInContainer() throws IOException, URISyntaxException {
- String inputJson = loadTextFile("/complexjson/case-node-augmentation-in-choice-in-container.json");
+ final String inputJson = loadTextFile("/complexjson/case-node-augmentation-in-choice-in-container.json");
verifyTransformationToNormalizedNode(inputJson,
TestingNormalizedNodeStructuresCreator.caseNodeAugmentationInChoiceInContainer());
}
*/
@Test
public void caseNodeExternalAugmentationInChoiceInContainer() throws IOException, URISyntaxException {
- String inputJson = loadTextFile("/complexjson/case-node-external-augmentation-in-choice-in-container.json");
+ final String inputJson = loadTextFile("/complexjson/case-node-external-augmentation-in-choice-in-container.json");
verifyTransformationToNormalizedNode(inputJson,
TestingNormalizedNodeStructuresCreator.caseNodeExternalAugmentationInChoiceInContainer());
}
*/
@Test
public void choiceNodeAugmentationInContainer() throws IOException, URISyntaxException {
- String inputJson = loadTextFile("/complexjson/choice-node-augmentation-in-container.json");
+ final String inputJson = loadTextFile("/complexjson/choice-node-augmentation-in-container.json");
verifyTransformationToNormalizedNode(inputJson,
TestingNormalizedNodeStructuresCreator.choiceNodeAugmentationInContainer());
}
@Test
public void unkeyedNodeInContainer() throws IOException, URISyntaxException {
- String inputJson = loadTextFile("/complexjson/unkeyed-node-in-container.json");
+ final String inputJson = loadTextFile("/complexjson/unkeyed-node-in-container.json");
verifyTransformationToNormalizedNode(inputJson, TestingNormalizedNodeStructuresCreator.unkeyedNodeInContainer());
}
+ /**
+ * Top level JSON element contains no information about module name.
+ *
+ * It should be possible to find out potential module name from available schema context.
+ *
+ */
+ @Test
+ public void missingModuleInfoInTopLevelElement() throws IOException, URISyntaxException {
+ final String inputJson = loadTextFile("/complexjson/missing-module-in-top-level.json");
+ verifyTransformationToNormalizedNode(inputJson, TestingNormalizedNodeStructuresCreator.topLevelContainer());
+ }
+
+ /**
+ *
+ * Exception expected.
+ *
+ * It tests case when several elements with the same name and various namespaces exists and are in JSON specified
+ * without module name prefix.
+ */
+ @Test
+ public void leafNamesakes() throws IOException, URISyntaxException {
+ final String inputJson = loadTextFile("/complexjson/namesakes.json");
+ try {
+ //second parameter isn't necessary because error will be raised before it is used.
+ verifyTransformationToNormalizedNode(inputJson, null);
+ } catch (final IllegalStateException e) {
+ final String errorMessage = e.getMessage();
+ assertTrue(errorMessage.contains("Choose suitable module name for element lf11-namesake:"));
+ assertTrue(errorMessage.contains("complexjson-augmentation"));
+ assertTrue(errorMessage.contains("complexjson-augmentation-namesake"));
+ }
+ }
+
+ /**
+ *
+ * Exception expected.
+ *
+ * Json input contains element which doesn't exist in YANG schema
+ */
+ @Test
+ public void parsingNotExistingElement() throws IOException, URISyntaxException {
+ final String inputJson = loadTextFile("/complexjson/not-existing-element.json");
+ try {
+ //second parameter isn't necessary because error will be raised before it is used.
+ verifyTransformationToNormalizedNode(inputJson, null);
+ } catch (final IllegalStateException e) {
+ assertTrue(e.getMessage().contains("Schema node with name dummy-element wasn't found."));
+ }
+ }
+
+
+ @Test
+ public void listItemWithoutArray() throws IOException, URISyntaxException {
+ final String inputJson = loadTextFile("/complexjson/keyed-list-restconf-behaviour.json");
+
+ final NormalizedNodeResult result = new NormalizedNodeResult();
+ final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
+ final SchemaNode parentNode = schemaContext.getDataChildByName("cont1");
+ final JsonParserStream jsonParser = JsonParserStream.create(streamWriter, schemaContext, parentNode);
+ jsonParser.parse(new JsonReader(new StringReader(inputJson)));
+ final NormalizedNode<?, ?> transformedInput = result.getResult();
+ assertNotNull(transformedInput);
+ }
+
+ @Test
+ public void listItemWithArray() throws IOException, URISyntaxException {
+ final String inputJson = loadTextFile("/complexjson/keyed-list-yang-json-behaviour.json");
+
+ final NormalizedNodeResult result = new NormalizedNodeResult();
+ final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
+ final SchemaNode parentNode = schemaContext.getDataChildByName("cont1");
+ final JsonParserStream jsonParser = JsonParserStream.create(streamWriter, schemaContext, parentNode);
+ jsonParser.parse(new JsonReader(new StringReader(inputJson)));
+ final NormalizedNode<?, ?> transformedInput = result.getResult();
+ assertNotNull(transformedInput);
+ }
+
private void verifyTransformationToNormalizedNode(final String inputJson,
final NormalizedNode<?, ?> awaitedStructure) {
- NormalizedNodeResult result = new NormalizedNodeResult();
+ final NormalizedNodeResult result = new NormalizedNodeResult();
final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
- JsonParserStream jsonParser = JsonParserStream.create(streamWriter, schemaContext);
+ final JsonParserStream jsonParser = JsonParserStream.create(streamWriter, schemaContext);
jsonParser.parse(new JsonReader(new StringReader(inputJson)));
- NormalizedNode<?, ?> transformedInput = result.getResult();
+ final NormalizedNode<?, ?> transformedInput = result.getResult();
assertEquals("Transformation of json input to normalized node wasn't successful.", awaitedStructure,
transformedInput);
}
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.childArray;
+import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.childPrimitive;
+import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.loadModules;
+import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.resolveCont1;
+
import com.google.common.collect.Sets;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.net.URISyntaxException;
+import java.util.HashSet;
+import java.util.Iterator;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.net.URISyntaxException;
-import java.util.HashSet;
-import java.util.Iterator;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.childArray;
-import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.childPrimitive;
-import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.loadModules;
-import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.resolveCont1;
-
/**
* Each test tests whether json output obtained after transformation contains is corect. The transformation takes
* normalized node data structure and transform it to json output. To make it easier validate json output it is loaded
assertNotNull(lf111);
assertEquals("key111 value", key111.getAsString());
- assertEquals("/complexjson:cont1/complexjson:lflst11", lf112.getAsString());
+ assertEquals("/complexjson:cont1/complexjson:lflst11[.='foo']", lf112.getAsString());
assertEquals("lf113 value", lf113.getAsString());
assertEquals("lf111 value", lf111.getAsString());
}
private String normalizedNodeToJsonStreamTransformation(final Writer writer,
final NormalizedNode<?, ?> inputStructure) throws IOException {
- writer.write("{\n");
+
final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.create(schemaContext, writer, 2);
final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
nodeWriter.write(inputStructure);
- writer.write("\n}");
+
nodeWriter.close();
return writer.toString();
}
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
+import java.util.HashMap;
+import java.util.Map;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
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.InstanceIdentifierBuilder;
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.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
-import java.util.HashMap;
-import java.util.Map;
-
public class TestingNormalizedNodeStructuresCreator {
static NormalizedNode<?, ?> cont1Node(
}
private static Object lf112Value() {
- InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
- builder.node(QName.create("ns:complex:json", "2014-08-11", "cont1"));
- builder.node(QName.create("ns:complex:json", "2014-08-11", "lflst11"));
- return builder.build();
+ return YangInstanceIdentifier.create(
+ new NodeIdentifier(QName.create("ns:complex:json", "2014-08-11", "cont1")),
+ new NodeIdentifier(QName.create("ns:complex:json", "2014-08-11", "lflst11")),
+ new NodeWithValue(QName.create("ns:complex:json", "2014-08-11", "lflst11"),"foo")
+ );
}
private static DataContainerChild<? extends PathArgument, ?> childLflst11() {
return lflst11.build();
}
- private static CompositeNode prepareLf12Value() {
- SimpleNode<?> anyxmlInData = NodeFactory.createImmutableSimpleNode(
- QName.create("ns:complex:json", "2014-08-11", "anyxml-in-data"), null, "foo");
- return ImmutableCompositeNode.builder().add(anyxmlInData)
- .setQName(QName.create("ns:complex:json", "2014-08-11", "lf12-any")).build();
- }
-
- private static CompositeNode prepareLf13Value() {
- SimpleNode<?> anyxmlInData = NodeFactory.createImmutableSimpleNode(
- QName.create("ns:complex:json", "2014-08-11", "anyxml-in-data"), null, "foo");
- return ImmutableCompositeNode.builder().add(anyxmlInData)
- .setQName(QName.create("ns:complex:json", "2014-08-11", "lf13-any")).build();
- }
-
public static NormalizedNode<?, ?> leafNodeInContainer() {
LeafNode<Object> lf11 = Builders.leafBuilder()
.withNodeIdentifier(new NodeIdentifier(QName.create("ns:complex:json", "2014-08-11", "lf11")))
- .withValue((int) 453).build();
+ .withValue(453).build();
return cont1Node(lf11);
}
return cont1Node(lst12Node());
}
+ public static NormalizedNode<?, ?> topLevelContainer() {
+ return cont1Node();
+ }
}
"lst11":[
{
"key111":"key111 value",
- "lf112":"/complexjson:cont1/complexjson:lflst11",
+ "lf112":"/complexjson:cont1/complexjson:lflst11[.='foo']",
"lf113":"lf113 value",
"lf111":"lf111 value"
}
"lst11":[
{
"key111":"key111 value",
- "lf112":"/complexjson:cont1/complexjson:lflst11",
+ "lf112":"/complexjson:cont1/complexjson:lflst11[.='foo']",
"lf113":"lf113 value",
"lf111":"lf111 value"
}
--- /dev/null
+{
+ "lst11": {
+ "key111":"key111 value",
+ "lf112":"/complexjson:cont1/complexjson:lflst11[.='foo']",
+ "lf113":"lf113 value",
+ "lf111":"lf111 value"
+ }
+}
--- /dev/null
+{
+ "lst11": [{
+ "key111":"key111 value",
+ "lf112":"/complexjson:cont1/complexjson:lflst11[.='foo']",
+ "lf113":"lf113 value",
+ "lf111":"lf111 value"
+ }]
+}
--- /dev/null
+{
+ "cont1": {
+ }
+}
--- /dev/null
+{
+ "cont1": {
+ "lf11-namesake":"value lf11"
+ }
+}
\ No newline at end of file
--- /dev/null
+{
+ "cont1": {
+ "dummy-element":"value lf11"
+ }
+}
\ No newline at end of file
}
]
}
-}
+}
\ No newline at end of file
--- /dev/null
+module complexjson-augmentation-namesake {
+ namespace "ns:complex:json:augmentation:namesake";
+ prefix cjaugnmsk;
+
+ import complexjson {
+ prefix cj;
+ }
+
+ revision "2014-08-14" {
+ }
+
+ augment "/cj:cont1" {
+ leaf lf11-namesake {
+ type string;
+ }
+ }
+
+}
module complexjson-augmentation {
namespace "ns:complex:json:augmentation";
prefix cjaug;
-
+
import complexjson {
prefix cj;
- }
+ }
- revision "2014-08-14" {
+ revision "2014-08-14" {
}
-
+
+ augment "/cj:cont1" {
+ leaf lf11-namesake {
+ type string;
+ }
+ }
+
augment "/cj:cont1/cj:choc11/cj:c11A" {
- leaf lf15_11 {
+ leaf lf15_11 {
type string;
}
- leaf lf15_12 {
+ leaf lf15_12 {
type string;
}
-
- }
-
+
+ }
+
augment "/cj:cont1" {
leaf lf12_1aug {
type string;
leaf lf12_2aug {
type string;
}
- }
-
+ }
+
augment "/cj:cont1/cj:choc11/cj:c11A" {
leaf lf15_21aug {
type string;
}
- }
+ }
}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!-- Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <parent>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yangtools-parent</artifactId>
- <version>0.7.0-SNAPSHOT</version>
- <relativePath>/../../common/parent/pom.xml</relativePath>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <artifactId>yang-data-composite-node</artifactId>
- <name>${project.artifactId}</name>
- <description>${project.artifactId}</description>
- <packaging>bundle</packaging>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-data-api</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-data-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-model-api</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-parser-impl</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-Name>Composite node Normalized node transformator</Bundle-Name>
- <Import-Package>*</Import-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.AnyXmlNodeBaseParser;
-import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-
-public class AnyXmlNodeCnSnParser extends AnyXmlNodeBaseParser<Node<?>> {
-
- public AnyXmlNodeCnSnParser() {
- super();
- }
-
- @Override
- protected Node<?> parseAnyXml(Node<?> element, AnyXmlSchemaNode schema) {
- return element;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.json.CnSnToNormalizedNodesUtils;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.AugmentationNodeBaseParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.LinkedListMultimap;
-
-public final class AugmentationNodeCnSnParser extends AugmentationNodeBaseParser<Node<?>> {
-
- private final NodeParserDispatcher<Node<?>> dispatcher;
-
- public AugmentationNodeCnSnParser(final NodeParserDispatcher<Node<?>> dispatcher) {
- this.dispatcher = Preconditions.checkNotNull(dispatcher);
- }
-
- @Override
- protected LinkedListMultimap<QName, Node<?>> mapChildElements(Iterable<Node<?>> elements) {
- return CnSnToNormalizedNodesUtils.mapChildElements(elements);
- }
-
- @Override
- protected NodeParserDispatcher<Node<?>> getDispatcher() {
- return dispatcher;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.json.CnSnToNormalizedNodesUtils;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.ChoiceNodeBaseParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.LinkedListMultimap;
-
-public final class ChoiceNodeCnSnParser extends ChoiceNodeBaseParser<Node<?>> {
-
- private final NodeParserDispatcher<Node<?>> dispatcher;
-
- public ChoiceNodeCnSnParser(final NodeParserDispatcher<Node<?>> dispatcher) {
- this.dispatcher = Preconditions.checkNotNull(dispatcher);
- }
-
- @Override
- protected LinkedListMultimap<QName, Node<?>> mapChildElements(Iterable<Node<?>> elements) {
- return CnSnToNormalizedNodesUtils.mapChildElements(elements);
- }
-
- @Override
- protected NodeParserDispatcher<Node<?>> getDispatcher() {
- return dispatcher;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
-import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParserFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-public class CnSnToNormalizedNodeParserFactory implements ToNormalizedNodeParserFactory<Node<?>> {
-
- private final ContainerNodeCnSnParser containerNodeCnSnParser;
- private final LeafNodeCnSnParser leafNodeCnSnParser;
- private final LeafSetEntryNodeCnSnParser leafSetEntryNodeCnSnParser;
- private final LeafSetNodeCnSnParser leafSetNodeCnSnParser;
- private final MapNodeCnSnParser mapNodeCnSnParser;
- private final MapEntryNodeCnSnParser mapEntryNodeCnSnParser;
- private final ChoiceNodeCnSnParser choiceNodeCnSnParser;
- private final AugmentationNodeCnSnParser augmentationNodeCnSnParser;
- private final AnyXmlNodeCnSnParser anyXmlNodeCnSnParser;
-
- private CnSnToNormalizedNodeParserFactory() {
- leafNodeCnSnParser = new LeafNodeCnSnParser();
- leafSetEntryNodeCnSnParser = new LeafSetEntryNodeCnSnParser();
- leafSetNodeCnSnParser = new LeafSetNodeCnSnParser(leafSetEntryNodeCnSnParser);
- anyXmlNodeCnSnParser = new AnyXmlNodeCnSnParser();
-
- final NodeParserDispatcher<Node<?>> dispatcher = new NodeParserDispatcher.BaseNodeParserDispatcher<Node<?>>(
- this) {
-
- };
-
- containerNodeCnSnParser = new ContainerNodeCnSnParser(dispatcher);
- mapEntryNodeCnSnParser = new MapEntryNodeCnSnParser(dispatcher);
- mapNodeCnSnParser = new MapNodeCnSnParser(mapEntryNodeCnSnParser);
- choiceNodeCnSnParser = new ChoiceNodeCnSnParser(dispatcher);
- augmentationNodeCnSnParser = new AugmentationNodeCnSnParser(dispatcher);
-
- }
-
- public static CnSnToNormalizedNodeParserFactory getInstance() {
- return new CnSnToNormalizedNodeParserFactory();
- }
-
- @Override
- public ToNormalizedNodeParser<Node<?>, ContainerNode, ContainerSchemaNode> getContainerNodeParser() {
- return containerNodeCnSnParser;
- }
-
- @Override
- public ToNormalizedNodeParser<Node<?>, LeafNode<?>, LeafSchemaNode> getLeafNodeParser() {
- return leafNodeCnSnParser;
- }
-
- @Override
- public ToNormalizedNodeParser<Node<?>, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeParser() {
- return leafSetNodeCnSnParser;
- }
-
- @Override
- public ToNormalizedNodeParser<Node<?>, MapNode, ListSchemaNode> getMapNodeParser() {
- return mapNodeCnSnParser;
- }
-
- @Override
- public ToNormalizedNodeParser<Node<?>, org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode, ChoiceNode> getChoiceNodeParser() {
- return choiceNodeCnSnParser;
- }
-
- @Override
- public ToNormalizedNodeParser<Node<?>, AugmentationNode, AugmentationSchema> getAugmentationNodeParser() {
- return augmentationNodeCnSnParser;
- }
-
- @Override
- public ToNormalizedNodeParser<Node<?>, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeParser() {
- return leafSetEntryNodeCnSnParser;
- }
-
- @Override
- public ToNormalizedNodeParser<Node<?>, MapEntryNode, ListSchemaNode> getMapEntryNodeParser() {
- return mapEntryNodeCnSnParser;
- }
-
- @Override
- public ToNormalizedNodeParser<Node<?>, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeParser() {
- return anyXmlNodeCnSnParser;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.json.CnSnToNormalizedNodesUtils;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.ContainerNodeBaseParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.LinkedListMultimap;
-
-public final class ContainerNodeCnSnParser extends ContainerNodeBaseParser<Node<?>> {
-
- private final NodeParserDispatcher<Node<?>> dispatcher;
-
- public ContainerNodeCnSnParser(final NodeParserDispatcher<Node<?>> dispatcher) {
- this.dispatcher = Preconditions.checkNotNull(dispatcher);
- }
-
- @Override
- protected NodeParserDispatcher<Node<?>> getDispatcher() {
- return dispatcher;
- }
-
- @Override
- protected LinkedListMultimap<QName, Node<?>> mapChildElements(Iterable<Node<?>> elements) {
- return CnSnToNormalizedNodesUtils.mapChildElementsForSingletonNode(elements.iterator().next());
- }
-
- @Override
- protected Map<QName, String> getAttributes(Node<?> e) {
- return Collections.emptyMap();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.LeafNodeBaseParser;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-
-public class LeafNodeCnSnParser extends LeafNodeBaseParser<Node<?>> {
-
- public LeafNodeCnSnParser() {
- super();
- }
-
- @Override
- protected Object parseLeaf(Node<?> elements, LeafSchemaNode schema) {
- return elements.getValue();
- }
-
- @Override
- protected Map<QName, String> getAttributes(Node<?> e) {
- return Collections.emptyMap();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.LeafSetEntryNodeBaseParser;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-
-public class LeafSetEntryNodeCnSnParser extends LeafSetEntryNodeBaseParser<Node<?>> {
-
- public LeafSetEntryNodeCnSnParser() {
- super();
- }
-
- @Override
- protected Object parseLeafListEntry(Node<?> elements, LeafListSchemaNode schema) {
- return elements.getValue();
- }
-
- @Override
- protected Map<QName, String> getAttributes(Node<?> e) {
- return Collections.emptyMap();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.LeafSetNodeBaseParser;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-
-public class LeafSetNodeCnSnParser extends LeafSetNodeBaseParser<Node<?>> {
-
- private final LeafSetEntryNodeCnSnParser leafSetEntryNodeCnSnParser;
-
- public LeafSetNodeCnSnParser(LeafSetEntryNodeCnSnParser leafSetEntryNodeCnSnParser) {
- this.leafSetEntryNodeCnSnParser = leafSetEntryNodeCnSnParser;
- }
-
- @Override
- protected ToNormalizedNodeParser<Node<?>, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeParser() {
- return leafSetEntryNodeCnSnParser;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.json.CnSnToNormalizedNodesUtils;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.MapEntryNodeBaseParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.LinkedListMultimap;
-
-public final class MapEntryNodeCnSnParser extends MapEntryNodeBaseParser<Node<?>> {
-
- private final NodeParserDispatcher<Node<?>> dispatcher;
-
- public MapEntryNodeCnSnParser(final NodeParserDispatcher<Node<?>> dispatcher) {
- this.dispatcher = Preconditions.checkNotNull(dispatcher);
- }
-
-
- @Override
- protected LinkedListMultimap<QName, Node<?>> mapChildElements(Iterable<Node<?>> elements) {
- return CnSnToNormalizedNodesUtils.mapChildElementsForSingletonNode(elements.iterator().next());
- }
-
- @Override
- protected NodeParserDispatcher<Node<?>> getDispatcher() {
- return dispatcher;
- }
-
- @Override
- protected Map<QName, String> getAttributes(Node<?> e) {
- return Collections.emptyMap();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.AnyXmlNodeBaseSerializer;
-
-public class AnyXmlNodeCnSnSerializer extends AnyXmlNodeBaseSerializer<Node<?>> {
-
- @Override
- protected Node<?> serializeAnyXml(AnyXmlNode node) {
- return node.getValue();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.AugmentationNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-
-import com.google.common.base.Preconditions;
-
-public class AugmentationNodeCnSnSerializer extends AugmentationNodeBaseSerializer<Node<?>> {
-
- private NodeSerializerDispatcher<Node<?>> dispatcher;
-
- AugmentationNodeCnSnSerializer(final NodeSerializerDispatcher<Node<?>> dispatcher) {
- this.dispatcher = Preconditions.checkNotNull(dispatcher);
- }
-
- @Override
- protected NodeSerializerDispatcher<Node<?>> getNodeDispatcher() {
- return dispatcher;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ChoiceNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-
-import com.google.common.base.Preconditions;
-
-public class ChoiceNodeCnSnSerializer
- extends
- ChoiceNodeBaseSerializer<Node<?>> {
-
- private final NodeSerializerDispatcher<Node<?>> dispatcher;
-
- ChoiceNodeCnSnSerializer(final NodeSerializerDispatcher<Node<?>> dispatcher) {
- this.dispatcher = Preconditions.checkNotNull(dispatcher);
- }
-
- @Override
- protected NodeSerializerDispatcher<Node<?>> getNodeDispatcher() {
- return dispatcher;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
-import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
-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.LeafNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializerFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-public final class CnSnFromNormalizedNodeSerializerFactory implements FromNormalizedNodeSerializerFactory<Node<?>> {
- private final ContainerNodeCnSnSerializer containerSerializer;
- private final ChoiceNodeCnSnSerializer choiceSerializer;
- private final AugmentationNodeCnSnSerializer augmentSerializer;
- private final LeafNodeCnSnSerializer leafNodeSerializer;
- private final LeafSetNodeCnSnSerializer leafSetSerializer;
- private final MapNodeCnSnSerializer mapNodeSerializer;
- private final LeafSetEntryNodeCnSnSerializer leafSetEntryNodeSerializer;
- private final MapEntryNodeCnSnSerializer mapEntryNodeSerializer;
- private final AnyXmlNodeCnSnSerializer anyXmlNodeSerializer;
-
- private CnSnFromNormalizedNodeSerializerFactory() {
- final NodeSerializerDispatcher.BaseNodeSerializerDispatcher<Node<?>> dispatcher = new NodeSerializerDispatcher.BaseNodeSerializerDispatcher<Node<?>>(
- this) {
-
- };
-
- containerSerializer = new ContainerNodeCnSnSerializer(dispatcher);
- choiceSerializer = new ChoiceNodeCnSnSerializer(dispatcher);
- augmentSerializer = new AugmentationNodeCnSnSerializer(dispatcher);
- leafNodeSerializer = new LeafNodeCnSnSerializer();
- anyXmlNodeSerializer = new AnyXmlNodeCnSnSerializer();
-
- leafSetEntryNodeSerializer = new LeafSetEntryNodeCnSnSerializer();
- leafSetSerializer = new LeafSetNodeCnSnSerializer(leafSetEntryNodeSerializer);
-
- mapEntryNodeSerializer = new MapEntryNodeCnSnSerializer(dispatcher);
- mapNodeSerializer = new MapNodeCnSnSerializer(mapEntryNodeSerializer);
- }
-
-
- public static CnSnFromNormalizedNodeSerializerFactory getInstance() {
- return new CnSnFromNormalizedNodeSerializerFactory();
-}
-
- @Override
- public FromNormalizedNodeSerializer<Node<?>, ContainerNode, ContainerSchemaNode> getContainerNodeSerializer() {
- return containerSerializer;
- }
-
- @Override
- public FromNormalizedNodeSerializer<Node<?>, LeafNode<?>, LeafSchemaNode> getLeafNodeSerializer() {
- return leafNodeSerializer;
- }
-
- @Override
- public FromNormalizedNodeSerializer<Node<?>, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeSerializer() {
- return leafSetSerializer;
- }
-
- @Override
- public FromNormalizedNodeSerializer<Node<?>, MapNode, ListSchemaNode> getMapNodeSerializer() {
- return mapNodeSerializer;
- }
-
- @Override
- public FromNormalizedNodeSerializer<Node<?>, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeSerializer() {
- return choiceSerializer;
- }
-
- @Override
- public FromNormalizedNodeSerializer<Node<?>, AugmentationNode, AugmentationSchema> getAugmentationNodeSerializer() {
- return augmentSerializer;
- }
-
-
- @Override
- public FromNormalizedNodeSerializer<Node<?>, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer() {
- return leafSetEntryNodeSerializer;
- }
-
-
- @Override
- public FromNormalizedNodeSerializer<Node<?>, MapEntryNode, ListSchemaNode> getMapEntryNodeSerializer() {
- return mapEntryNodeSerializer;
- }
-
- @Override
- public FromNormalizedNodeSerializer<Node<?>, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeSerializer() {
- return anyXmlNodeSerializer;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import com.google.common.base.Preconditions;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ContainerNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-
-public class ContainerNodeCnSnSerializer extends ContainerNodeBaseSerializer<Node<?>> {
-
- private final NodeSerializerDispatcher<Node<?>> dispatcher;
-
- ContainerNodeCnSnSerializer(final NodeSerializerDispatcher<Node<?>> dispatcher) {
- this.dispatcher = Preconditions.checkNotNull(dispatcher);
- }
-
- @Override
- public List<Node<?>> serialize(final ContainerSchemaNode schema, final ContainerNode node) {
- CompositeNodeBuilder<ImmutableCompositeNode> compNodeBuilder = ImmutableCompositeNode.builder();
- compNodeBuilder.setQName(node.getNodeType());
- compNodeBuilder.addAll(super.serialize(schema, node));
- return Collections.<Node<?>> singletonList(compNodeBuilder.build());
- }
-
- @Override
- protected NodeSerializerDispatcher<Node<?>> getNodeDispatcher() {
- return dispatcher;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.LeafNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-
-public class LeafNodeCnSnSerializer extends LeafNodeBaseSerializer<Node<?>> {
-
- @Override
- protected Node<?> serializeLeaf(LeafSchemaNode schema, LeafNode<?> node) {
- return NodeFactory.createMutableSimpleNode(node.getNodeType(), null, node.getValue(), null, null);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.LeafSetEntryNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-
-public class LeafSetEntryNodeCnSnSerializer extends
- LeafSetEntryNodeBaseSerializer<Node<?>> {
-
- @Override
- protected Node<?> serializeLeaf(LeafListSchemaNode schema, LeafSetEntryNode<?> node) {
- return NodeFactory.createMutableSimpleNode(
- node.getNodeType(), null, node.getValue(), null, null);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.LeafSetNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-
-public class LeafSetNodeCnSnSerializer extends
- LeafSetNodeBaseSerializer<Node<?>> {
-
- private FromNormalizedNodeSerializer<Node<?>, LeafSetEntryNode<?>, LeafListSchemaNode> leafSetEntryNodeSerializer;
-
- public LeafSetNodeCnSnSerializer(final LeafSetEntryNodeCnSnSerializer leafSetEntryNodeSerializer) {
- this.leafSetEntryNodeSerializer = leafSetEntryNodeSerializer;
- }
-
- @Override
- protected FromNormalizedNodeSerializer<Node<?>, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer() {
- return leafSetEntryNodeSerializer;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import com.google.common.base.Preconditions;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.MapEntryNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-public class MapEntryNodeCnSnSerializer extends MapEntryNodeBaseSerializer<Node<?>> {
-
- private final NodeSerializerDispatcher<Node<?>> dispatcher;
-
- MapEntryNodeCnSnSerializer(final NodeSerializerDispatcher<Node<?>> dispatcher) {
- this.dispatcher = Preconditions.checkNotNull(dispatcher);
- }
-
- @Override
- public List<Node<?>> serialize(ListSchemaNode schema, MapEntryNode node) {
- CompositeNodeBuilder<ImmutableCompositeNode> compNodeBuilder = ImmutableCompositeNode.builder();
- compNodeBuilder.setQName(node.getNodeType());
- compNodeBuilder.addAll(super.serialize(schema, node));
- return Collections.<Node<?>> singletonList(compNodeBuilder.build());
- }
-
- @Override
- protected NodeSerializerDispatcher<Node<?>> getNodeDispatcher() {
- return dispatcher;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.MapNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-public class MapNodeCnSnSerializer extends MapNodeBaseSerializer<Node<?>> {
-
- private final FromNormalizedNodeSerializer<Node<?>, MapEntryNode, ListSchemaNode> mapEntrySerializer;
-
- public MapNodeCnSnSerializer(final MapEntryNodeCnSnSerializer mapEntrySerializer) {
- this.mapEntrySerializer = mapEntrySerializer;
- }
-
- @Override
- protected FromNormalizedNodeSerializer<Node<?>, MapEntryNode, ListSchemaNode> getMapEntryNodeDomSerializer() {
- return mapEntrySerializer;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.json;
-
-import com.google.common.collect.LinkedListMultimap;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public final class CnSnToNormalizedNodesUtils {
-
-
- private CnSnToNormalizedNodesUtils() {
- throw new UnsupportedOperationException("Utility class should not be instantiated");
- }
-
- public static LinkedListMultimap<QName, Node<?>> mapChildElementsForSingletonNode(Node<?> node) {
- return mapChildElements( ((CompositeNode)node).getValue());
- }
-
- public static LinkedListMultimap<QName, Node<?>> mapChildElements(Iterable<Node<?>> childNodesCollection) {
- LinkedListMultimap<QName, Node<?>> mappedChildElements = LinkedListMultimap.create();
-
- for (Node<?> node : childNodesCollection) {
- mappedChildElements.put(node.getNodeType(), node);
- }
-
- return mappedChildElements;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema;
-
-import static org.junit.Assert.assertNotNull;
-import static org.opendaylight.yangtools.yang.data.impl.NodeFactory.createMutableSimpleNode;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
-import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class TestUtils {
-
- private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
- private static final QNameModule MODULE_AUGMENT;
- private static final QNameModule MODULE_BASE;
-
- static {
- final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
-
- try {
- MODULE_BASE = QNameModule.create(URI.create("simple:container:yang"), df.parse("2013-11-12"));
- MODULE_AUGMENT = QNameModule.create(URI.create("augment:container:yang"), df.parse("2014-03-19"));
- } catch (ParseException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
-
- public static Set<Module> loadModules(final URI resourceURI) throws FileNotFoundException {
- final YangModelParser parser = new YangParserImpl();
- final File testDir = new File(resourceURI);
- final String[] fileList = testDir.list();
- final List<File> testFiles = new ArrayList<>();
- if (fileList == null) {
- throw new FileNotFoundException(resourceURI.toString());
- }
- for (String fileName : fileList) {
- testFiles.add(new File(testDir, fileName));
- }
- return parser.parseYangModels(testFiles);
- }
-
- public static Set<Module> loadModulesFrom(final String yangPath) throws URISyntaxException {
- try {
- return loadModules(TestUtils.class.getResource(yangPath).toURI());
- } catch (FileNotFoundException e) {
- LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
- }
-
- return null;
- }
-
- public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
- assertNotNull("Module can't be null", module);
-
- if (searchedDataSchemaName != null) {
- for (DataSchemaNode dsn : module.getChildNodes()) {
- if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
- return dsn;
- }
- }
- } else if (module.getChildNodes().size() == 1) {
- return module.getChildNodes().iterator().next();
- }
- return null;
- }
-
- public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
- assertNotNull("Modules can't be null.", modules);
- if (searchedModuleName != null) {
- for (Module m : modules) {
- if (m.getName().equals(searchedModuleName)) {
- return m;
- }
- }
- } else if (modules.size() == 1) {
- return modules.iterator().next();
- }
- return null;
- }
-
- /**
- * Prepare composite node structure according to
- * /cnsn-to-normalized-node/simple-conainer.json
- */
- public static CompositeNode prepareCompositeNodeStruct() {
- CompositeNodeBuilder<ImmutableCompositeNode> contBuilder = ImmutableCompositeNode.builder();
- contBuilder.setQName(QName.create(MODULE_BASE, "cont"));
-
- // cont1
- contBuilder.add(ImmutableCompositeNode.builder().setQName(QName.create(MODULE_BASE, "cont1")).build());
-
- // cont2
- CompositeNodeBuilder<ImmutableCompositeNode> cont2 = ImmutableCompositeNode.builder().setQName(
- QName.create(MODULE_BASE, "cont2"));
- cont2.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lf21"), null, "value in cont2/lf21", null, null));
- contBuilder.add(cont2.build());
-
- // lst1
- contBuilder.add(ImmutableCompositeNode.builder().setQName(QName.create(MODULE_BASE, "lst1")).build());
-
- // lst2
- CompositeNodeBuilder<ImmutableCompositeNode> lst2_1Builder = ImmutableCompositeNode.builder().setQName(
- QName.create(MODULE_BASE, "lst2"));
- lst2_1Builder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lf21"), null, "some value21", null, null));
- contBuilder.add(lst2_1Builder.build());
-
- CompositeNodeBuilder<ImmutableCompositeNode> lst2_2Builder = ImmutableCompositeNode.builder().setQName(
- QName.create(MODULE_BASE, "lst2"));
- lst2_2Builder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lf22"), null, "some value22", null, null));
- contBuilder.add(lst2_2Builder.build());
-
- // lflst1
- contBuilder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lflst1"), null, "lflst1_1", null, null));
- contBuilder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lflst1"), null, "lflst1_2", null, null));
-
- // lf1
- contBuilder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lf1"), null, "lf1", null, null));
-
- // lf11
- contBuilder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lf11"), null, "value from case (cs1)", null,
- null));
-
- // cont3
- CompositeNodeBuilder<ImmutableCompositeNode> cont3Builder = ImmutableCompositeNode.builder().setQName(
- QName.create(MODULE_AUGMENT, "cont3"));
- cont3Builder.add(createMutableSimpleNode(QName.create(MODULE_AUGMENT, "lf31"), null,
- "value in leaf in augment", null, null));
- contBuilder.add(cont3Builder.build());
-
- // anxml-composite
- CompositeNodeBuilder<ImmutableCompositeNode> anxmlCompositeBuilder = ImmutableCompositeNode.builder().setQName(
- QName.create(MODULE_BASE, "anxml-composite"));
- anxmlCompositeBuilder.add(NodeFactory.createImmutableSimpleNode(QName.create(MODULE_BASE, "anxml-cont"), null,
- null));
- contBuilder.add(anxmlCompositeBuilder.build());
-
- // anxml-simple
- contBuilder.add(NodeFactory.createImmutableSimpleNode(QName.create(MODULE_BASE, "anxml-simple"), null,43));
-
- return contBuilder.build();
- }
-
- /**
- * Prepare composite node structure according to
- * /cnsn-to-normalized-node/simple-conainer.json
- */
- public static ContainerNode prepareNormalizedNodeStruct() throws URISyntaxException {
- DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder = Builders.containerBuilder();
- containerBuilder.withNodeIdentifier(getNodeIdentifier("cont"));
- containerBuilder.withChild(Builders.containerBuilder().withNodeIdentifier(getNodeIdentifier("cont1")).build());
- containerBuilder.withChild(Builders
- .containerBuilder()
- .withNodeIdentifier(getNodeIdentifier("cont2"))
- .withChild(
- Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("lf21"))
- .withValue("value in cont2/lf21").build()).build());
-
- CollectionNodeBuilder<MapEntryNode, MapNode> lst1 = Builders.mapBuilder().withNodeIdentifier(
- getNodeIdentifier("lst1"));
- lst1.withChild(Builders.mapEntryBuilder()
- .withNodeIdentifier(getNodeIdentifierPredicate("lst1", new HashMap<String, Object>()))
- .withValue(Collections.<DataContainerChild<? extends PathArgument, ?>> emptyList()).build());
- containerBuilder.withChild(lst1.build());
-
- CollectionNodeBuilder<MapEntryNode, MapNode> lst2 = Builders.mapBuilder().withNodeIdentifier(
- getNodeIdentifier("lst2"));
-
- Map<String, Object> lst2_1 = new HashMap<>();
- lst2_1.put("lf21", "some value21");
-
- List<DataContainerChild<? extends PathArgument, ?>> lst2_1_values = new ArrayList<>();
- lst2_1_values.add(Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("lf21"))
- .withValue("some value21").build());
- lst2.withChild(Builders.mapEntryBuilder().withNodeIdentifier(getNodeIdentifierPredicate("lst2", lst2_1))
- .withValue(lst2_1_values).build());
-
- Map<String, Object> lst2_2 = new HashMap<>();
- lst2_2.put("lf22", "some value22");
- List<DataContainerChild<? extends PathArgument, ?>> lst2_2_values = new ArrayList<>();
- lst2_2_values.add(Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("lf22"))
- .withValue("some value22").build());
- lst2.withChild(Builders.mapEntryBuilder().withNodeIdentifier(getNodeIdentifierPredicate("lst2", lst2_2))
- .withValue(lst2_2_values).build());
- containerBuilder.withChild(lst2.build());
-
- ListNodeBuilder<Object, LeafSetEntryNode<Object>> lflst1 = Builders.leafSetBuilder().withNodeIdentifier(
- getNodeIdentifier("lflst1"));
- lflst1.withChild(Builders.leafSetEntryBuilder().withNodeIdentifier(getNodeIdentifier("lflst1", "lflst1_1"))
- .withValue("lflst1_1").build());
- lflst1.withChild(Builders.leafSetEntryBuilder().withNodeIdentifier(getNodeIdentifier("lflst1", "lflst1_2"))
- .withValue("lflst1_2").build());
- containerBuilder.withChild(lflst1.build());
-
- containerBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("lf1")).withValue("lf1")
- .build());
-
- containerBuilder.withChild(Builders
- .choiceBuilder()
- .withNodeIdentifier(getNodeIdentifier("chc"))
- .withChild(
- Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("lf11"))
- .withValue("value from case (cs1)").build()).build());
-
- Set<QName> children = new HashSet<>();
- children.add(QName.create(MODULE_AUGMENT, "cont3"));
-
- containerBuilder.withChild(Builders
- .augmentationBuilder()
- .withNodeIdentifier(getAugmentationIdentifier(null, null, null, children))
- .withChild(
- Builders.containerBuilder()
- .withNodeIdentifier(getNodeIdentifier(MODULE_AUGMENT, "cont3"))
- .withChild(
- Builders.leafBuilder()
- .withNodeIdentifier(getNodeIdentifier(MODULE_AUGMENT, "lf31"))
- .withValue("value in leaf in augment").build()).build()).build());
-
- containerBuilder.withChild(Builders
- .anyXmlBuilder()
- .withNodeIdentifier(getNodeIdentifier("anxml-composite"))
- .withValue(
- ImmutableCompositeNode
- .builder()
- .setQName(QName.create("simple:container:yang", "2013-11-12", "anxml-composite"))
- .add(NodeFactory.createImmutableSimpleNode(
- QName.create("simple:container:yang", "2013-11-12", "anxml-cont"), null, null))
- .build()).build());
-
- containerBuilder
- .withChild(Builders
- .anyXmlBuilder()
- .withNodeIdentifier(getNodeIdentifier("anxml-simple"))
- .withValue(
- NodeFactory.createImmutableSimpleNode(
- QName.create("simple:container:yang", "2013-11-12", "anxml-simple"), null, 43))
- .build());
-
- ContainerNode build = containerBuilder.build();
- return build;
- }
-
- private static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName) {
- return getNodeIdentifier(MODULE_BASE, localName);
- }
-
- private static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final QNameModule module, final String localName) {
- return new YangInstanceIdentifier.NodeIdentifier(QName.create(module, localName));
- }
-
- private static YangInstanceIdentifier.NodeWithValue getNodeIdentifier(final String localName, final Object value) {
- return new YangInstanceIdentifier.NodeWithValue(QName.create(MODULE_BASE, localName),
- value);
- }
-
- private static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
- final Map<String, Object> keys) {
- Map<QName, Object> predicate = new HashMap<>();
- for (String key : keys.keySet()) {
- predicate.put(QName.create(MODULE_BASE, key), keys.get(key));
- }
-
- return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(MODULE_BASE, localName), predicate);
- }
-
- private static YangInstanceIdentifier.AugmentationIdentifier getAugmentationIdentifier(final String localName,
- final String namespace, final Date revision, final Set<QName> children) {
- return new YangInstanceIdentifier.AugmentationIdentifier(children);
- }
-
-}
+++ /dev/null
-package org.opendaylight.yangtools.yang.data.composite.node.schema.parser;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.data.api.Node;
-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.OrderedLeafSetNode;
-import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
-import org.opendaylight.yangtools.yang.data.composite.node.schema.TestUtils;
-import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Set;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-public class Bug2180Test {
- private Module simpleContainerModule;
- private Module bug2111TestModule;
-
- @Before
- public void init() throws URISyntaxException {
- Set<Module> modules = TestUtils.loadModulesFrom("/cnsn-to-normalized-node/yang");
- simpleContainerModule = TestUtils.resolveModule("simple-container-yang", modules);
- bug2111TestModule = TestUtils.resolveModule("bug2180-test-module", modules);
- }
-
- @Test
- public void orderedListParseTest() throws DataValidationFailedException, URISyntaxException {
- ContainerSchemaNode topContainerSchemaNode = (ContainerSchemaNode) TestUtils.resolveDataSchemaNode("top", bug2111TestModule);
- ListSchemaNode aceListSchemaNode = (ListSchemaNode) topContainerSchemaNode.getDataChildByName("ordered-list");
- ToNormalizedNodeParser<Node<?>, MapNode, ListSchemaNode> mapNodeParser =
- CnSnToNormalizedNodeParserFactory.getInstance().getMapNodeParser();
- MapNode mapNode = mapNodeParser.parse(new ArrayList<Node<?>>(), aceListSchemaNode);
- assertTrue(mapNode instanceof OrderedMapNode);
- }
-
- @Test
- public void unorderedListParseTest() throws DataValidationFailedException, URISyntaxException {
- ContainerSchemaNode topContainerSchemaNode = (ContainerSchemaNode) TestUtils.resolveDataSchemaNode("cont", simpleContainerModule);
- ListSchemaNode aceListSchemaNode = (ListSchemaNode) topContainerSchemaNode.getDataChildByName("lst2");
- ToNormalizedNodeParser<Node<?>, MapNode, ListSchemaNode> mapNodeParser =
- CnSnToNormalizedNodeParserFactory.getInstance().getMapNodeParser();
- MapNode mapNode = mapNodeParser.parse(new ArrayList<Node<?>>(), aceListSchemaNode);
- assertFalse(mapNode instanceof OrderedMapNode);
- }
-
- @Test
- public void orderedLeafListParseTest() throws DataValidationFailedException, URISyntaxException {
- ContainerSchemaNode topContainerSchemaNode = (ContainerSchemaNode) TestUtils.resolveDataSchemaNode("top", bug2111TestModule);
- LeafListSchemaNode aceListSchemaNode = (LeafListSchemaNode) topContainerSchemaNode.getDataChildByName("ordered-leaf-list");
- ToNormalizedNodeParser<Node<?>, LeafSetNode<?>, LeafListSchemaNode> leafSetNodeParser =
- CnSnToNormalizedNodeParserFactory.getInstance().getLeafSetNodeParser();
- LeafSetNode<?> leafSetNode = leafSetNodeParser.parse(new ArrayList<Node<?>>(), aceListSchemaNode);
- assertTrue(leafSetNode instanceof OrderedLeafSetNode);
- }
-
- @Test
- public void unorderedLeafListParseTest() throws DataValidationFailedException, URISyntaxException {
- ContainerSchemaNode topContainerSchemaNode = (ContainerSchemaNode) TestUtils.resolveDataSchemaNode("cont", simpleContainerModule);
- LeafListSchemaNode aceListSchemaNode = (LeafListSchemaNode) topContainerSchemaNode.getDataChildByName("lflst1");
- ToNormalizedNodeParser<Node<?>, LeafSetNode<?>, LeafListSchemaNode> leafSetNodeParser =
- CnSnToNormalizedNodeParserFactory.getInstance().getLeafSetNodeParser();
- LeafSetNode<?> leafSetNode = leafSetNodeParser.parse(new ArrayList<Node<?>>(), aceListSchemaNode);
- assertFalse(leafSetNode instanceof OrderedLeafSetNode);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.parser;
-
-import static org.junit.Assert.assertEquals;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
-
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.TestUtils;
-
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-public class ParseCnSnStructToNormalizedStructTest {
-
- private static DataSchemaNode resolvedDataSchemaNode;
-
- @BeforeClass
- public static void loadData() throws URISyntaxException {
- Set<Module> modules = TestUtils.loadModulesFrom("/cnsn-to-normalized-node/yang");
- Module resolvedModule = TestUtils.resolveModule("simple-container-yang", modules);
- resolvedDataSchemaNode = TestUtils.resolveDataSchemaNode("cont", resolvedModule);
- }
-
- @Test
- public void testCnSnToNormalizedNode() throws URISyntaxException {
-
- CompositeNode compNode = TestUtils.prepareCompositeNodeStruct();
-
- List<Node<?>> lst = new ArrayList<Node<?>>();
- lst.add(compNode);
- ContainerNode parsed = CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
- .parse(lst, (ContainerSchemaNode) resolvedDataSchemaNode);
-
- ContainerNode prepareExpectedStruct = TestUtils.prepareNormalizedNodeStruct();
- assertEquals(prepareExpectedStruct, parsed);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.serializer;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer.CnSnFromNormalizedNodeSerializerFactory;
-
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.TestUtils;
-
-import java.net.URISyntaxException;
-import java.util.Set;
-
-import com.google.common.collect.Sets;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-public class SerializeNormalizedStructToCnSnStructTest {
-
- private static DataSchemaNode resolvedDataSchemaNode;
-
- @BeforeClass
- public static void loadData() throws URISyntaxException {
- Set<Module> modules = TestUtils.loadModulesFrom("/cnsn-to-normalized-node/yang");
- Module resolvedModule = TestUtils.resolveModule("simple-container-yang", modules);
- resolvedDataSchemaNode = TestUtils.resolveDataSchemaNode("cont", resolvedModule);
- }
-
- @Test
- public void testCnSnToNormalizedNode() throws URISyntaxException {
- ContainerNode containerNode = TestUtils.prepareNormalizedNodeStruct();
-
- Iterable<Node<?>> serialized = CnSnFromNormalizedNodeSerializerFactory.getInstance()
- .getContainerNodeSerializer().serialize((ContainerSchemaNode) resolvedDataSchemaNode, containerNode);
-
- assertNotNull(serialized);
- assertNotNull(serialized.iterator());
- assertNotNull(serialized.iterator().hasNext());
-
- CompositeNode compNode = TestUtils.prepareCompositeNodeStruct();
-
- assertEquals(serialized.iterator().next().getNodeType(), compNode.getNodeType());
-
- Set<Node<?>> value = Sets.newHashSet(((CompositeNode)serialized.iterator().next()).getValue());
- assertEquals(value, Sets.newHashSet(compNode.getValue()));
- }
-}
+++ /dev/null
-{
- "simple-container-yang:cont":{
- "cont1":{
- },
- "cont2":{
- "lf21":"value in cont2/lf21"
- },
- "augment-container-yang:cont3":{
- "lf31":"value in leaf in augment"
- },
- "lst1": [
- {
- }
- ],
- "lst2": [
- {
- "lf21":"some value21"
- },
- {
- "lf22":"some value22"
- }
- ],
- "lflst1":[
- "lflst1_1",
- "lflst1_2"
- ],
- "lf1":"lf1",
-
- "lf11":"value from case (cs1)"
- "anxml-composite": {
- "anxml-cont" {
- }
- }
-
- "anxml-simple":43;
- }
-}
\ No newline at end of file
+++ /dev/null
-module augment-container-yang {
- namespace "augment:container:yang";
-
- prefix "auconyang";
- import simple-container-yang { prefix "simple"; revision-date 2013-11-12; }
-
- revision 2014-03-19 {
- }
-
- augment "/simple:cont" {
- container cont3 {
- leaf lf31 {
- type string;
- }
- }
- }
-
-}
+++ /dev/null
-module bug2180-test-module {
- yang-version 1;
-
- namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:bug2180:test";
-
- prefix bug2180-test-module;
-
- revision 2014-10-22 {
- description "creating base model for netmod";
- }
-
- container top {
- list ordered-list {
- key id;
- ordered-by user;
- leaf id{
- type string;
- }
- }
-
- leaf-list ordered-leaf-list {
- type string;
- ordered-by user;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-module simple-container-yang {
- namespace "simple:container:yang";
-
- prefix "smpdtp";
- revision 2013-11-12 {
- }
-
- container cont {
- container cont1 {
- }
- container cont2 {
- leaf lf21 {
- type string;
- }
- }
- list lst1 {
- }
- list lst2 {
- leaf lf21 {
- type string;
- }
- leaf lf22 {
- type string;
- }
- }
- leaf-list lflst1 {
- type string;
- }
- leaf lf1 {
- type string;
- }
-
- choice chc {
- case cs1 {
- leaf lf11 {
- type string;
- }
- }
- case cs2 {
- leaf lf21 {
- type string;
- }
- }
- }
-
- anyxml anxml-composite;
- anyxml anxml-simple;
- }
-}
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModification;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
-
-/**
- * @author michal.rehak
- * @param <T>
- * type of node value
- * @deprecated Use one of the {@link NormalizedNodeBuilder} implementations.
- */
-@Deprecated
-public abstract class AbstractNodeTO<T> implements Node<T>, NodeModification {
-
- private QName qName;
- private CompositeNode parent;
- private T value;
- private ModifyAction modifyAction;
-
- // Only for Serialization use
- public AbstractNodeTO(){
-
- }
-
- /**
- * @param qname
- * @param parent
- * @param value
- */
- public AbstractNodeTO(final QName qname, final CompositeNode parent, final T value) {
- this(qname, parent, value, null);
- }
-
- /**
- * @param qname
- * @param parent
- * @param value
- * @param modifyAction
- */
- public AbstractNodeTO(final QName qname, final CompositeNode parent, final T value, final ModifyAction modifyAction) {
- this.qName = qname;
- this.parent = parent;
- this.value = value;
- this.modifyAction = modifyAction;
- }
-
- @Override
- public QName getNodeType() {
- return qName;
- }
-
- /**
- * @return the qName
- */
- public QName getQName() {
- return qName;
- }
-
- @Override
- public CompositeNode getParent() {
- return parent;
- }
-
- /**
- * @param parent
- * the parent to set
- */
- public void setParent(final CompositeNode parent) {
- this.parent = parent;
- }
-
- /**
- * @param value
- * the value to set
- */
- @Override
- public T setValue(final T value) {
- T oldValue = this.value;
- this.value = value;
- return oldValue;
- }
-
- @Override
- public T getValue() {
- return value;
- }
-
- /**
- * @return modification action
- * @see NodeModification#getModificationAction()
- */
- @Override
- public ModifyAction getModificationAction() {
- return modifyAction;
- }
-
- /**
- * @param modifyAction
- * the modifyAction to set
- */
- protected void setModificationAction(final ModifyAction modifyAction) {
- this.modifyAction = modifyAction;
- }
-
- @Override
- public String toString() {
- StringBuffer out = new StringBuffer();
- out.append(String.format("Node[%s], qName[%s], modify[%s]", getClass().getSimpleName(), getQName()
- .getLocalName(), getModificationAction() == null ? "n/a" : getModificationAction()));
- return out.toString();
- }
-
-
- @Override
- public final QName getKey() {
- return getNodeType();
- }
-
- /* */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((qName == null) ? 0 : qName.hashCode());
- result = prime * result + ((value == null) ? 0 : value.hashCode());
- return result % 2;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- @SuppressWarnings("unchecked")
- AbstractNodeTO<T> other = (AbstractNodeTO<T>) obj;
- if (parent == null) {
- if (other.parent != null) {
- return false;
- }
- } else if (other.parent == null) {
- return false;
- }
- if (qName == null) {
- if (other.qName != null) {
- return false;
- }
- } else if (!qName.equals(other.qName)) {
- return false;
- }
- if (value == null) {
- if (other.value != null) {
- return false;
- }
- } else if (!value.equals(other.value)) {
- return false;
- }
- return true;
- }
- /* */
-
-
- //Serialization related
-
- protected final void init(final QName qName, final CompositeNode parent, final T value, final ModifyAction modifyAction){
- this.qName = qName;
- this.modifyAction = modifyAction;
- this.parent = parent;
- this.value = value;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.util.List;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use one of the {@link NormalizedNode} implementations.
- */
-@Deprecated
-public class CompositeNodeModificationTOImpl extends CompositeNodeTOImpl {
- private static final long serialVersionUID = 1L;
-
- /**
- * @param qname
- * @param parent
- * @param value
- * @param modifyAction
- */
- public CompositeNodeModificationTOImpl(final QName qname, final CompositeNode parent,
- final List<Node<?>> value, final ModifyAction modifyAction) {
- super(qname, parent, value);
- super.setModificationAction(modifyAction);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use one of the {@link NormalizedNodeContainer} implementations.
- */
-@Deprecated
-public class CompositeNodeTOImpl extends AbstractNodeTO<List<Node<?>>> implements CompositeNode, Serializable {
-
- private static final long serialVersionUID = 100L;
-
- private Map<QName, List<Node<?>>> nodeMap = new HashMap<>();
-
- /**
- * @param qname
- * @param parent
- * use null to create top composite node (without parent)
- * @param value
- */
- public CompositeNodeTOImpl(final QName qname, final CompositeNode parent, final List<Node<?>> value) {
- super(qname, parent, value);
- init();
- }
-
- /**
- * @param qname
- * @param parent
- * use null to create top composite node (without parent)
- * @param value
- * @param modifyAction
- */
- public CompositeNodeTOImpl(final QName qname, final CompositeNode parent, final List<Node<?>> value, final ModifyAction modifyAction) {
- super(qname, parent, value, modifyAction);
- init();
- }
-
- protected void init() {
- if (getValue() != null) {
- nodeMap = NodeUtils.buildNodeMap(getValue());
- }
- }
-
- protected Map<QName, List<Node<?>>> getNodeMap() {
- return nodeMap;
- }
-
- @Override
- public List<Node<?>> getChildren() {
- return Collections.unmodifiableList(getValue() == null ? new ArrayList<Node<?>>() : getValue());
- }
-
- @Override
- public SimpleNode<?> getFirstSimpleByName(final QName leafQName) {
- List<SimpleNode<?>> list = getSimpleNodesByName(leafQName);
- if (list.isEmpty()) {
- return null;
- }
- return list.get(0);
- }
-
- @Override
- public List<CompositeNode> getCompositesByName(final QName children) {
- List<Node<?>> toFilter = getNodeMap().get(children);
- if(toFilter == null) {
- return Collections.emptyList();
- }
- List<CompositeNode> list = new ArrayList<CompositeNode>();
- for (Node<?> node : toFilter) {
- if (node instanceof CompositeNode) {
- list.add((CompositeNode) node);
- }
- }
- return list;
- }
-
- @Override
- public List<SimpleNode<?>> getSimpleNodesByName(final QName children) {
- List<Node<?>> toFilter = getNodeMap().get(children);
- if(toFilter == null) {
- return Collections.emptyList();
- }
- List<SimpleNode<?>> list = new ArrayList<SimpleNode<?>>();
-
- for (Node<?> node : toFilter) {
- if (node instanceof SimpleNode<?>) {
- list.add((SimpleNode<?>) node);
- }
- }
- return list;
- }
-
- @Override
- public CompositeNode getFirstCompositeByName(final QName container) {
- List<CompositeNode> list = getCompositesByName(container);
- if (list.isEmpty()) {
- return null;
- }
- return list.get(0);
- }
-
- /**
- * @param leaf
- * @return TODO:: do we need this method?
- */
- public SimpleNode<?> getFirstLeafByName(final QName leaf) {
- List<SimpleNode<?>> list = getSimpleNodesByName(leaf);
- if (list.isEmpty()) {
- return null;
- }
- return list.get(0);
- }
-
- @Override
- public List<CompositeNode> getCompositesByName(final String children) {
- return getCompositesByName(QName.create(getNodeType(), children));
- }
-
- @Override
- public List<SimpleNode<?>> getSimpleNodesByName(final String children) {
- return getSimpleNodesByName(QName.create(getNodeType(), children));
- }
-
- @Override
- public MutableCompositeNode asMutable() {
- throw new IllegalAccessError("cast to mutable is not supported - " + getClass().getSimpleName());
- }
-
- @Override
- public String toString() {
- return super.toString() + ", children.size = " + (!getChildren().isEmpty() ? getChildren().size() : "n/a");
- }
-
- @Override
- public void clear() {
- nodeMap.clear();
- }
-
- @Override
- public boolean containsKey(final Object key) {
- return nodeMap.containsKey(key);
- }
-
- @Override
- public boolean containsValue(final Object value) {
- return nodeMap.containsValue(value);
- }
-
- @Override
- public Set<java.util.Map.Entry<QName, List<Node<?>>>> entrySet() {
- return nodeMap.entrySet();
- }
-
- @Override
- public int size() {
- return nodeMap.size();
- }
-
- @Override
- public boolean isEmpty() {
- return nodeMap.isEmpty();
- }
-
- @Override
- public List<Node<?>> get(final Object key) {
- return nodeMap.get(key);
- }
-
- @Override
- public List<Node<?>> put(final QName key, final List<Node<?>> value) {
- return nodeMap.put(key, value);
- }
-
- @Override
- public List<Node<?>> remove(final Object key) {
- return nodeMap.remove(key);
- }
-
- @Override
- public void putAll(final Map<? extends QName, ? extends List<Node<?>>> m) {
- nodeMap.putAll(m);
- }
-
- @Override
- public Set<QName> keySet() {
- return nodeMap.keySet();
- }
-
- @Override
- public Collection<List<Node<?>>> values() {
- return nodeMap.values();
- }
-
- // Serialization related
-
- private void readObject(final ObjectInputStream aStream) throws IOException, ClassNotFoundException {
- aStream.defaultReadObject();
- QName qName = (QName)aStream.readObject();
- CompositeNode parent = (CompositeNode) aStream.readObject();
- @SuppressWarnings("unchecked")
- List<Node<?>> value = (List<Node<?>>) aStream.readObject();
- ModifyAction modifyAction = (ModifyAction) aStream.readObject();
-
- init(qName, parent, value, modifyAction);
- }
-
- private void writeObject(final ObjectOutputStream aStream) throws IOException {
- aStream.defaultWriteObject();
- //manually serialize superclass
- aStream.writeObject(getQName());
- aStream.writeObject(getParent());
- aStream.writeObject(getValue());
- aStream.writeObject(getModificationAction());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.yangtools.concepts.Immutable;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-import org.opendaylight.yangtools.yang.data.impl.util.AbstractCompositeNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
-
-/**
- * @deprecated Use one of the {@link NormalizedNodeContainer} implementations.
- */
-@Deprecated
-public final class ImmutableCompositeNode extends AbstractNodeTO<List<Node<?>>> implements Immutable, CompositeNode, AttributesContainer, Serializable {
-
- private static final long serialVersionUID = 100L;
-
- private Map<QName, List<Node<?>>> nodeMap = new HashMap<>();
-
- private final Map<QName, String> attributes;
-
-
-
- /**
- * @param qname
- * @param parent
- * use null to create top composite node (without parent)
- * @param value
- */
- private ImmutableCompositeNode(final QName qname, final Map<QName,String> attributes,final List<Node<?>> value) {
- super(qname, null, ImmutableList.copyOf(value));
- if(attributes == null) {
- this.attributes = ImmutableMap.<QName, String>of();
- } else {
- this.attributes = ImmutableMap.copyOf(attributes);
- }
- init();
- }
-
- /**
- * @param qname
- * @param value
- * @param modifyAction
- */
- public ImmutableCompositeNode(final QName qname, final List<Node<?>> value, final ModifyAction modifyAction) {
- super(qname, null, value, modifyAction);
- attributes = ImmutableMap.of();
- init();
- }
-
- protected void init() {
- if (getValue() != null) {
- nodeMap = NodeUtils.buildNodeMap(getValue());
- }
- }
-
- protected Map<QName, List<Node<?>>> getNodeMap() {
- return nodeMap;
- }
-
- @Override
- public List<Node<?>> getChildren() {
- return Collections.unmodifiableList(getValue() == null ? new ArrayList<Node<?>>() : getValue());
- }
-
- @Override
- public SimpleNode<?> getFirstSimpleByName(final QName leafQName) {
- List<SimpleNode<?>> list = getSimpleNodesByName(leafQName);
- if (list.isEmpty()) {
- return null;
- }
- return list.get(0);
- }
-
- @Override
- public List<CompositeNode> getCompositesByName(final QName children) {
- List<Node<?>> toFilter = getNodeMap().get(children);
- if (toFilter == null) {
- return Collections.emptyList();
- }
- List<CompositeNode> list = new ArrayList<CompositeNode>();
- for (Node<?> node : toFilter) {
- if (node instanceof CompositeNode) {
- list.add((CompositeNode) node);
- }
- }
- return list;
- }
-
- @Override
- public List<SimpleNode<?>> getSimpleNodesByName(final QName children) {
- List<Node<?>> toFilter = getNodeMap().get(children);
- if (toFilter == null) {
- return Collections.emptyList();
- }
- List<SimpleNode<?>> list = new ArrayList<SimpleNode<?>>();
-
- for (Node<?> node : toFilter) {
- if (node instanceof SimpleNode<?>) {
- list.add((SimpleNode<?>) node);
- }
- }
- return list;
- }
-
- @Override
- public CompositeNode getFirstCompositeByName(final QName container) {
- List<CompositeNode> list = getCompositesByName(container);
- if (list.isEmpty()) {
- return null;
- }
- return list.get(0);
- }
-
- @Override
- public Map<QName, String> getAttributes() {
- return attributes;
- }
-
- @Override
- public String getAttributeValue(final QName key) {
- return attributes.get(key);
- }
-
- /**
- * @param leaf
- * @return TODO:: do we need this method?
- */
- public SimpleNode<?> getFirstLeafByName(final QName leaf) {
- List<SimpleNode<?>> list = getSimpleNodesByName(leaf);
- if (list.isEmpty()) {
- return null;
- }
- return list.get(0);
- }
-
- @Override
- public List<CompositeNode> getCompositesByName(final String children) {
- return getCompositesByName(QName.create(getNodeType(), children));
- }
-
- @Override
- public List<SimpleNode<?>> getSimpleNodesByName(final String children) {
- return getSimpleNodesByName(QName.create(getNodeType(), children));
- }
-
- @Override
- public MutableCompositeNode asMutable() {
- throw new IllegalAccessError("cast to mutable is not supported - " + getClass().getSimpleName());
- }
-
- @Override
- public String toString() {
- return super.toString() + ", children.size = " + (!getChildren().isEmpty() ? getChildren().size() : "n/a");
- }
-
- @Override
- public void clear() {
- nodeMap.clear();
- }
-
- @Override
- public boolean containsKey(final Object key) {
- return nodeMap.containsKey(key);
- }
-
- @Override
- public boolean containsValue(final Object value) {
- return nodeMap.containsValue(value);
- }
-
- @Override
- public Set<java.util.Map.Entry<QName, List<Node<?>>>> entrySet() {
- return nodeMap.entrySet();
- }
-
- @Override
- public int size() {
- return nodeMap.size();
- }
-
- @Override
- public boolean isEmpty() {
- return nodeMap.isEmpty();
- }
-
- @Override
- public List<Node<?>> get(final Object key) {
- return nodeMap.get(key);
- }
-
- @Override
- public List<Node<?>> put(final QName key, final List<Node<?>> value) {
- return nodeMap.put(key, value);
- }
-
- @Override
- public List<Node<?>> remove(final Object key) {
- return nodeMap.remove(key);
- }
-
- @Override
- public void putAll(final Map<? extends QName, ? extends List<Node<?>>> m) {
- nodeMap.putAll(m);
- }
-
- @Override
- public Set<QName> keySet() {
- return nodeMap.keySet();
- }
-
- @Override
- public Collection<List<Node<?>>> values() {
- return nodeMap.values();
- }
-
- // Serialization related
-
- private void readObject(final ObjectInputStream aStream) throws IOException, ClassNotFoundException {
- aStream.defaultReadObject();
- QName qName = (QName) aStream.readObject();
- CompositeNode parent = (CompositeNode) aStream.readObject();
- @SuppressWarnings("unchecked")
- List<Node<?>> value = (List<Node<?>>) aStream.readObject();
- ModifyAction modifyAction = (ModifyAction) aStream.readObject();
-
- init(qName, parent, value, modifyAction);
- }
-
- private void writeObject(final ObjectOutputStream aStream) throws IOException {
- aStream.defaultWriteObject();
- // manually serialize superclass
- aStream.writeObject(getQName());
- aStream.writeObject(getParent());
- aStream.writeObject(getValue());
- aStream.writeObject(getModificationAction());
- }
-
- public static CompositeNodeBuilder<ImmutableCompositeNode> builder() {
- return new ImmutableCompositeNodeBuilder();
- }
-
- private static class ImmutableCompositeNodeBuilder extends AbstractCompositeNodeBuilder<ImmutableCompositeNode> {
-
- @Override
- public AbstractCompositeNodeBuilder<ImmutableCompositeNode> addLeaf(final QName leafName, final Object leafValue) {
- add(new SimpleNodeTOImpl<Object>(leafName, null, leafValue));
- return this;
- }
-
- @Override
- public ImmutableCompositeNode build() {
- return ImmutableCompositeNode.create(this.getQName(), this.getAttributes(), this.getChildNodes());
- }
-
- @Deprecated
- public ImmutableCompositeNode toInstance() {
- return ImmutableCompositeNode.create(this.getQName(), this.getAttributes(), this.getChildNodes());
- }
-
- }
-
- public static ImmutableCompositeNode create(final QName qName, final List<Node<?>> childNodes) {
- return new ImmutableCompositeNode(qName, ImmutableMap.<QName, String>of(),childNodes);
- }
-
- public static ImmutableCompositeNode create(final QName qName, final Map<QName, String> attributes, final List<Node<?>> childNodes) {
- return new ImmutableCompositeNode(qName, attributes,childNodes);
- }
-
- public static ImmutableCompositeNode create(final QName qName, final List<Node<?>> childNodes, final ModifyAction modifyAction) {
- return new ImmutableCompositeNode(qName, childNodes, modifyAction);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModification;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-
-/**
- * @author michal.rehak
- *
- */
-@Deprecated
-public class LazyNodeToNodeMap {
-
- private final Map<Node<?>, Node<?>> node2node = new HashMap<>();
- private CompositeNode originalRoot;
- private MutableCompositeNode mutableRoot;
-
- /**
- * @param originalNode
- * @return mutable twin
- */
- public Node<?> getMutableEquivalent(final Node<?> originalNode) {
- Node<?> mutableNode = node2node.get(originalNode);
- if (mutableNode == null) {
- addPathMembers(originalNode);
- mutableNode = node2node.get(originalNode);
- }
-
- return mutableNode;
- }
-
- /**
- * @param originalNode
- */
- private void addPathMembers(final Node<?> originalNode) {
- final Deque<Node<?>> jobQueue = new ArrayDeque<>();
- jobQueue.push(originalNode);
- while (!jobQueue.isEmpty()) {
- Node<?> node2add = jobQueue.pop();
- boolean fixChildrenRefOnly = false;
- if (node2node.containsKey(node2add)) {
- if (node2add instanceof SimpleNode<?>) {
- continue;
- }
- fixChildrenRefOnly = true;
- }
-
- CompositeNode nextParent = node2add.getParent();
- MutableNode<?> mutableEquivalent = null;
-
- if (node2add instanceof SimpleNode<?>) {
- SimpleNode<?> node2addSimple = (SimpleNode<?>) node2add;
- MutableSimpleNode<?> nodeMutant = NodeFactory.createMutableSimpleNode(
- node2add.getNodeType(), null, node2addSimple.getValue(),
- node2addSimple.getModificationAction(), node2addSimple);
- mutableEquivalent = nodeMutant;
- } else if (node2add instanceof CompositeNode) {
- MutableCompositeNode nodeMutant = null;
- if (fixChildrenRefOnly) {
- nodeMutant = (MutableCompositeNode) node2node.get(node2add);
- } else {
- CompositeNode node2addComposite = (CompositeNode) node2add;
- nodeMutant = NodeFactory.createMutableCompositeNode(node2add.getNodeType(),
- null, null,
- ((NodeModification) node2add).getModificationAction(), node2addComposite);
- }
-
- mutableEquivalent = nodeMutant;
-
- // tidy up children
- if (nodeMutant.getValue() == null) {
- nodeMutant.setValue(new ArrayList<Node<?>>());
- }
- for (Node<?> originalChildNode : ((CompositeNode) node2add).getValue()) {
- MutableNode<?> mutableChild = (MutableNode<?>) node2node.get(originalChildNode);
- fixChildrenRef(nodeMutant, mutableChild);
- }
-
- if (nodeMutant.getValue() != null && !nodeMutant.getValue().isEmpty()) {
- nodeMutant.init();
- }
-
- // store tree root, if occured
- if (nextParent == null) {
- if (originalRoot == null) {
- originalRoot = (CompositeNode) node2add;
- mutableRoot = nodeMutant;
- } else {
- if (!originalRoot.equals(node2add)) {
- throw new IllegalStateException("Different tree root node obtained - " +
- "perhaps nodes of different trees are getting mixed up.");
- }
- }
- }
- }
-
- // feed jobQueue
- node2node.put(node2add, mutableEquivalent);
- if (nextParent != null) {
- jobQueue.push(nextParent);
- }
- }
- }
-
- /**
- * @param nodeMutant
- * @param mutableChild
- */
- private static void fixChildrenRef(final MutableCompositeNode nodeMutant,
- final MutableNode<?> mutableChild) {
- if (mutableChild != null) {
- if (!nodeMutant.getValue().contains(mutableChild)) {
- nodeMutant.getValue().add(mutableChild);
- }
- CompositeNode parentOfChild = mutableChild.getParent();
- if (parentOfChild == null) {
- mutableChild.setParent(nodeMutant);
- } else {
- if (!parentOfChild.equals(nodeMutant)) {
- throw new IllegalStateException("Different parent node obtained - " +
- "perhaps nodes of different trees are getting mixed up.");
- }
- }
- }
- }
-
- /**
- * @return the mutableRoot
- */
- public MutableCompositeNode getMutableRoot() {
- return mutableRoot;
- }
-
- /**
- * @return set of original nodes, registered in map as keys
- */
- public Set<Node<?>> getKeyNodes() {
- return node2node.keySet();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use one of the {@link NormalizedNodeContainer} implementations instead.
- */
-@Deprecated
-public class MutableCompositeNodeTOImpl extends AbstractNodeTO<List<Node<?>>> implements MutableCompositeNode, Serializable {
-
- private static final long serialVersionUID = 100L;
-
- private Map<QName, List<Node<?>>> nodeMap = new HashMap<>();
- private CompositeNode original;
-
- public MutableCompositeNodeTOImpl(final QName qname, final CompositeNode parent, final List<Node<?>> value, final ModifyAction modifyAction) {
- super(qname, parent, value, modifyAction);
- init();
- }
-
- /**
- * update nodeMap - it should be invoked after children was changed
- */
- @Override
- public void init() {
- if (!getChildren().isEmpty()) {
- nodeMap = NodeUtils.buildNodeMap(getChildren());
- }
- }
-
- @Override
- public List<Node<?>> getChildren() {
- return getValue() == null ? new ArrayList<Node<?>>() : getValue();
- }
-
- @Override
- public List<Node<?>> setValue(final List<Node<?>> value) {
- List<Node<?>> oldVal = super.setValue(value);
- init();
- return oldVal;
- }
-
- @Override
- public void setModifyAction(final ModifyAction action) {
- super.setModificationAction(action);
- }
-
- protected Map<QName, List<Node<?>>> getNodeMap() {
- return nodeMap;
- }
-
- @Override
- public MutableCompositeNode asMutable() {
- return this;
- }
-
- @Override
- public CompositeNode getOriginal() {
- return original;
- }
-
- /**
- * @param original
- * the original to set
- */
- public void setOriginal(final CompositeNode original) {
- this.original = original;
- }
-
- @Override
- public SimpleNode<?> getFirstSimpleByName(final QName leafQName) {
- List<SimpleNode<?>> list = getSimpleNodesByName(leafQName);
- if (list.isEmpty()) {
- return null;
- }
- return list.get(0);
- }
-
- @Override
- public List<CompositeNode> getCompositesByName(final QName children) {
- List<Node<?>> toFilter = getNodeMap().get(children);
- if (toFilter == null) {
- return Collections.emptyList();
- }
- List<CompositeNode> list = new ArrayList<CompositeNode>();
- for (Node<?> node : toFilter) {
- if (node instanceof CompositeNode) {
- list.add((CompositeNode) node);
- }
- }
- return list;
- }
-
- @Override
- public List<SimpleNode<?>> getSimpleNodesByName(final QName children) {
- List<Node<?>> toFilter = getNodeMap().get(children);
- if (toFilter == null) {
- return Collections.emptyList();
- }
- List<SimpleNode<?>> list = new ArrayList<SimpleNode<?>>();
-
- for (Node<?> node : toFilter) {
- if (node instanceof SimpleNode<?>) {
- list.add((SimpleNode<?>) node);
- }
- }
- return list;
- }
-
- @Override
- public CompositeNode getFirstCompositeByName(final QName container) {
- List<CompositeNode> list = getCompositesByName(container);
- if (list.isEmpty()) {
- return null;
- }
- return list.get(0);
- }
-
- /**
- * @param leaf
- * @return TODO:: do we need this method?
- */
- public SimpleNode<?> getFirstLeafByName(final QName leaf) {
- List<SimpleNode<?>> list = getSimpleNodesByName(leaf);
- if (list.isEmpty()) {
- return null;
- }
- return list.get(0);
- }
-
- @Override
- public List<CompositeNode> getCompositesByName(final String children) {
- return getCompositesByName(QName.create(getNodeType(), children));
- }
-
- @Override
- public List<SimpleNode<?>> getSimpleNodesByName(final String children) {
- return getSimpleNodesByName(QName.create(getNodeType(), children));
- }
-
- @Override
- public String toString() {
- return super.toString() + ", children.size = " + (getChildren() != null ? getChildren().size() : "n/a");
- }
-
- @Override
- public void clear() {
- nodeMap.clear();
- }
-
- @Override
- public boolean containsKey(final Object key) {
- return nodeMap.containsKey(key);
- }
-
- @Override
- public boolean containsValue(final Object value) {
- return nodeMap.containsValue(value);
- }
-
- @Override
- public Set<java.util.Map.Entry<QName, List<Node<?>>>> entrySet() {
- return nodeMap.entrySet();
- }
-
- @Override
- public int size() {
- return nodeMap.size();
- }
-
- @Override
- public boolean isEmpty() {
- return nodeMap.isEmpty();
- }
-
- @Override
- public List<Node<?>> get(final Object key) {
- return nodeMap.get(key);
- }
-
- @Override
- public List<Node<?>> put(final QName key, final List<Node<?>> value) {
- return nodeMap.put(key, value);
- }
-
- @Override
- public List<Node<?>> remove(final Object key) {
- return nodeMap.remove(key);
- }
-
- @Override
- public void putAll(final Map<? extends QName, ? extends List<Node<?>>> m) {
- nodeMap.putAll(m);
- }
-
- @Override
- public Set<QName> keySet() {
- return nodeMap.keySet();
- }
-
- @Override
- public Collection<List<Node<?>>> values() {
- return nodeMap.values();
- }
-
- // Serialization related
-
- private void readObject(final ObjectInputStream aStream) throws IOException, ClassNotFoundException {
- aStream.defaultReadObject();
- QName qName = (QName)aStream.readObject();
- CompositeNode parent = (CompositeNode) aStream.readObject();
- @SuppressWarnings("unchecked")
- List<Node<?>> value = (List<Node<?>>) aStream.readObject();
- ModifyAction modifyAction = (ModifyAction) aStream.readObject();
-
- init(qName, parent, value, modifyAction);
- }
-
- private void writeObject(final ObjectOutputStream aStream) throws IOException {
- aStream.defaultWriteObject();
- //manually serialize superclass
- aStream.writeObject(getQName());
- aStream.writeObject(getParent());
- aStream.writeObject(getValue());
- aStream.writeObject(getModificationAction());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @author michal.rehak
- * @param <T>
- * type of simple node value
- *
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
-@Deprecated
-public class MutableSimpleNodeTOImpl<T> extends SimpleNodeTOImpl<T> implements MutableSimpleNode<T> {
- private static final long serialVersionUID = 1L;
- private SimpleNode<T> original;
-
- /**
- * @param qname
- * @param parent
- * @param value
- * @param modifyAction
- */
- public MutableSimpleNodeTOImpl(final QName qname, final CompositeNode parent, final T value, final ModifyAction modifyAction) {
- super(qname, parent, value, modifyAction);
- }
-
- @Override
- public void setModifyAction(final ModifyAction action) {
- super.setModificationAction(action);
- }
-
- @Override
- public MutableSimpleNode<T> asMutable() {
- return this;
- }
-
- @Override
- public SimpleNode<T> getOriginal() {
- return original;
- }
-
- /**
- * @param original
- * the original to set
- */
- public void setOriginal(final SimpleNode<T> original) {
- this.original = original;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.util.AbstractMap.SimpleEntry;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModification;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use {@link Builders} instead.
- */
-@Deprecated
-public abstract class NodeFactory {
-
- /**
- * @param qName
- * @param parent
- * @param value
- * @return simple node modification, based on given qname, value and parent
- */
- public static <T> SimpleNode<T> createImmutableSimpleNode(final QName qName,
- final CompositeNode parent, final T value) {
- return createImmutableSimpleNode(qName, parent, value, null);
- }
-
- /**
- * @param qName
- * @param parent
- * @param value
- * @param modifyAction
- * @param original originating node, if available
- * @return simple node modification, based on given qname, value and parent
- */
- public static <T> MutableSimpleNode<T> createMutableSimpleNode(final QName qName,
- final CompositeNode parent, final Object value, final ModifyAction modifyAction, final SimpleNode<T> original) {
- @SuppressWarnings("unchecked")
- MutableSimpleNodeTOImpl<T> simpleNodeTOImpl = new MutableSimpleNodeTOImpl<>(qName, parent, (T) value, modifyAction);
- simpleNodeTOImpl.setOriginal(original);
- return simpleNodeTOImpl;
- }
-
- /**
- * @param qName
- * @param parent
- * @param value
- * @return composite node modification, based on given qname, value (children), parent and modifyAction
- */
- public static CompositeNode createImmutableCompositeNode(final QName qName,
- final CompositeNode parent, final List<Node<?>> value) {
- return createImmutableCompositeNode(qName, parent, value, null);
- }
-
- /**
- * @param qName
- * @param parent
- * @param valueArg
- * @param modifyAction
- * @param original originating node, if available
- * @return composite node modification, based on given qName, value (children), parent and modifyAction
- */
- public static MutableCompositeNode createMutableCompositeNode(final QName qName,
- final CompositeNode parent, final List<Node<?>> valueArg, final ModifyAction modifyAction, final CompositeNode original) {
- List<Node<?>> value = valueArg;
- if (value == null) {
- value = new ArrayList<>();
- }
- MutableCompositeNodeTOImpl compositeNodeTOImpl =
- new MutableCompositeNodeTOImpl(qName, parent, value, modifyAction);
- compositeNodeTOImpl.setOriginal(original);
- return compositeNodeTOImpl;
- }
-
-
- /**
- * @param qName
- * @param parent
- * @param value
- * @param modifyAction
- * @return simple node modification, based on given qname, value, parent and modifyAction
- */
- public static <T> SimpleNode<T> createImmutableSimpleNode(final QName qName,
- final CompositeNode parent, final T value, final ModifyAction modifyAction) {
- SimpleNodeTOImpl<T> simpleNodeModTOImpl =
- new SimpleNodeTOImpl<T>(qName, parent, value, modifyAction);
- return simpleNodeModTOImpl;
- }
-
- /**
- * @param qName
- * @param parent
- * @param value
- * @param modifyAction
- * @return composite node modification, based on given qname, value (children), parent and modifyAction
- */
- public static CompositeNode createImmutableCompositeNode(final QName qName,
- final CompositeNode parent, final List<Node<?>> value, final ModifyAction modifyAction) {
- return new CompositeNodeTOImpl(qName, parent, value, modifyAction);
- }
-
- /**
- * @param node
- * @return copy of given node, parent and value are the same, but parent
- * has no reference to this copy
- */
- public static <T> SimpleNode<T> copyNode(final SimpleNode<T> node) {
- return createImmutableSimpleNode(node.getNodeType(), node.getParent(), node.getValue());
- }
-
- /**
- * @param node
- * @return copy of given node, parent and value are the same, but parent
- * has no reference to this copy
- */
- public static <T> MutableSimpleNode<T> copyNodeAsMutable(final SimpleNode<T> node) {
- return createMutableSimpleNode(
- node.getNodeType(), node.getParent(), node.getValue(),
- node.getModificationAction(), null);
- }
-
- /**
- * @param node
- * @param children
- * @return copy of given node, parent and children are the same, but parent and children
- * have no reference to this copy
- */
- public static CompositeNode copyNode(final CompositeNode node, final Node<?>... children) {
- CompositeNode twinNode = createImmutableCompositeNode(
- node.getNodeType(), node.getParent(), Arrays.asList(children), node.getModificationAction());
- return twinNode;
- }
-
- /**
- * @param node
- * @return copy of given node, parent and children are the same, but parent and children
- * have no reference to this copy
- */
- public static CompositeNode copyNode(final CompositeNode node) {
- return copyNode(node, node.getValue().toArray(new Node<?>[0]));
- }
-
- /**
- * @param node root of original tree
- * @param originalToCopyArg (optional) empty map, where binding between original and copy
- * will be stored
- * @return copy of given node and all subnodes recursively
- */
- public static MutableCompositeNode copyDeepAsMutable(final CompositeNode node,
- final Map<Node<?>, Node<?>> originalToCopyArg) {
-
- Map<Node<?>, Node<?>> originalToCopy = originalToCopyArg;
- if (originalToCopy == null) {
- originalToCopy = new HashMap<>();
- }
-
- MutableCompositeNode mutableRoot = createMutableCompositeNode(node.getNodeType(), null, null,
- node.getModificationAction(), null);
- final Deque<SimpleEntry<CompositeNode, MutableCompositeNode>> jobQueue = new ArrayDeque<>();
- jobQueue.push(new SimpleEntry<CompositeNode, MutableCompositeNode>(node, mutableRoot));
- originalToCopy.put(node, mutableRoot);
-
- while (!jobQueue.isEmpty()) {
- SimpleEntry<CompositeNode, MutableCompositeNode> job = jobQueue.pop();
- CompositeNode originalNode = job.getKey();
- MutableCompositeNode mutableNode = job.getValue();
- mutableNode.setValue(new ArrayList<Node<?>>());
-
- for (Node<?> child : originalNode.getValue()) {
- Node<?> mutableAscendant = null;
- if (child instanceof CompositeNode) {
- MutableCompositeNode newMutable =
- createMutableCompositeNode(child.getNodeType(), mutableNode, null,
- ((NodeModification) child).getModificationAction(), null);
- jobQueue.push(new SimpleEntry<CompositeNode, MutableCompositeNode>(
- (CompositeNode) child, newMutable));
- mutableAscendant = newMutable;
- } else if (child instanceof SimpleNode<?>) {
- mutableAscendant =
- createMutableSimpleNode(child.getNodeType(), mutableNode,
- child.getValue(),
- ((NodeModification) child).getModificationAction(), null);
- } else {
- throw new IllegalStateException("Node class deep copy not supported: "
- +child.getClass().getName());
- }
-
- mutableNode.getValue().add(mutableAscendant);
- originalToCopy.put(child, mutableAscendant);
- }
- mutableNode.init();
- }
-
- return mutableRoot;
- }
-
- /**
- * @param node root of original tree
- * @param originalToCopyArg (optional) empty map, where binding between original and copy
- * will be stored
- * @return copy of given node and all subnodes recursively
- */
- public static CompositeNode copyDeepAsImmutable(final CompositeNode node,
- final Map<Node<?>, Node<?>> originalToCopyArg) {
- final Deque<CompositeNode> jobQueue = new ArrayDeque<>();
- jobQueue.push(node);
-
- Map<Node<?>, Node<?>> originalToCopy = originalToCopyArg;
- if (originalToCopy == null) {
- originalToCopy = new HashMap<>();
- }
-
- while (!jobQueue.isEmpty()) {
- CompositeNode jobNode = jobQueue.peek();
- if (!originalToCopy.isEmpty()
- && originalToCopy.keySet().containsAll(jobNode.getValue())) {
- jobQueue.pop();
- List<Node<?>> newChildren = NodeUtils.collectMapValues(jobNode.getValue(), originalToCopy);
- CompositeNode nodeCopy = createImmutableCompositeNode(jobNode.getNodeType(), null,
- newChildren, jobNode.getModificationAction());
- NodeUtils.fixChildrenRelation(nodeCopy);
- originalToCopy.put(jobNode, nodeCopy);
- } else {
- for (Node<?> child : jobNode.getValue()) {
- if (child instanceof SimpleNode<?>) {
- originalToCopy.put(child, createImmutableSimpleNode(
- child.getNodeType(), null, child.getValue(),
- ((NodeModification) child).getModificationAction()));
- } else if (child instanceof CompositeNode) {
- jobQueue.push((CompositeNode) child);
- }
- }
- }
- }
-
- return (CompositeNode) originalToCopy.get(node);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModificationBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use {@link Builders} instead.
- */
-@Deprecated
-public class NodeModificationBuilderImpl implements NodeModificationBuilder {
-
- private final SchemaContext context;
-
- private final Set<MutableNode<?>> changeLog;
- private final LazyNodeToNodeMap originalToMutable;
-
- /**
- * @param context
- */
- public NodeModificationBuilderImpl(final SchemaContext context) {
- this.context = context;
- originalToMutable = new LazyNodeToNodeMap();
- changeLog = new HashSet<>();
- }
-
- /**
- * @param modNode
- * @param action
- */
- private void addModificationToLog(final MutableNode<?> modNode, final ModifyAction action) {
- modNode.setModifyAction(action);
- changeLog.add(modNode);
- }
-
- @Override
- public void addNode(final MutableSimpleNode<?> newNode) {
- NodeUtils.fixParentRelation(newNode);
- addModificationToLog(newNode, ModifyAction.CREATE);
- }
-
- @Override
- public void addNode(final MutableCompositeNode newNode) {
- NodeUtils.fixParentRelation(newNode);
- addModificationToLog(newNode, ModifyAction.CREATE);
- }
-
- @Override
- public void replaceNode(final MutableSimpleNode<?> replacementNode) {
- addModificationToLog(replacementNode, ModifyAction.REPLACE);
- }
-
- @Override
- public void replaceNode(final MutableCompositeNode replacementNode) {
- addModificationToLog(replacementNode, ModifyAction.REPLACE);
- }
-
- @Override
- public void deleteNode(final MutableCompositeNode deadNode) {
- addModificationToLog(deadNode, ModifyAction.DELETE);
- }
-
- @Override
- public void deleteNode(final MutableSimpleNode<?> deadNode) {
- addModificationToLog(deadNode, ModifyAction.DELETE);
- }
-
- @Override
- public void removeNode(final MutableSimpleNode<?> deadNode) {
- addModificationToLog(deadNode, ModifyAction.REMOVE);
- }
-
- @Override
- public void removeNode(final MutableCompositeNode deadNode) {
- addModificationToLog(deadNode, ModifyAction.REMOVE);
- }
-
- @Override
- public void mergeNode(final MutableCompositeNode alteredNode) {
- addModificationToLog(alteredNode, ModifyAction.MERGE);
- }
-
- /**
- * @return minimalistic tree containing diffs only
- */
- @Override
- public CompositeNode buildDiffTree() {
- Set<Node<?>> wanted = new HashSet<>();
-
- // walk changeLog, collect all required nodes
- for (MutableNode<?> mutant : changeLog) {
- wanted.addAll(collectSelfAndAllParents(mutant));
- }
-
- // walk wanted and add relevant keys
- Map<String, ListSchemaNode> mapOfLists = NodeUtils.buildMapOfListNodes(context);
- for (Node<?> outlaw : wanted) {
- if (outlaw instanceof CompositeNode) {
- String path = NodeUtils.buildPath(outlaw);
- if (mapOfLists.containsKey(path)) {
- ListSchemaNode listSchema = mapOfLists.get(path);
- if (listSchema.getQName().equals(outlaw.getNodeType())) {
- // try to add key subnode to wanted list
- List<QName> supportedKeys = listSchema.getKeyDefinition();
- CompositeNode outlawOriginal = ((MutableCompositeNode) outlaw).getOriginal();
- for (Node<?> outlawOriginalChild : outlawOriginal.getValue()) {
- if (supportedKeys.contains(outlawOriginalChild.getNodeType())) {
- originalToMutable.getMutableEquivalent(outlawOriginalChild);
- }
- }
- }
- }
- }
- }
-
- return originalToMutable.getMutableRoot();
- }
-
- /**
- * @param focusedDescendant
- * @return set of parents and focusedAncestor itself
- */
- private static Set<Node<?>> collectSelfAndAllParents(final Node<?> focusedDescendant) {
- Set<Node<?>> family = new HashSet<>();
- Node<?> tmpNode = focusedDescendant;
- while (tmpNode != null) {
- family.add(tmpNode);
- tmpNode = tmpNode.getParent();
- }
- return family;
- }
-
- /**
- * @param originalNode
- * @return mutable version of given node
- */
- @Override
- public Node<?> getMutableEquivalent(final Node<?> originalNode) {
- return originalToMutable.getMutableEquivalent(originalNode);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import java.util.AbstractMap.SimpleEntry;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.annotation.Nonnull;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.xpath.XPath;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
-import javax.xml.xpath.XPathExpressionException;
-import javax.xml.xpath.XPathFactory;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModification;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Element;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use {@link NormalizedNodes} instead.
- */
-@Deprecated
-public abstract class NodeUtils {
- private static final Joiner DOT_JOINER = Joiner.on(".");
- private static final Logger LOG = LoggerFactory.getLogger(NodeUtils.class);
- private static final Function<QName, String> LOCALNAME_FUNCTION = new Function<QName, String>() {
- @Override
- public String apply(final @Nonnull QName input) {
- Preconditions.checkNotNull(input);
- return input.getLocalName();
- }
- };
-
- /**
- *
- */
- private static final String USER_KEY_NODE = "node";
-
- /**
- * @param node
- * @return node path up till root node
- */
- public static String buildPath(final Node<?> node) {
- List<String> breadCrumbs = new ArrayList<>();
- Node<?> tmpNode = node;
- while (tmpNode != null) {
- breadCrumbs.add(0, tmpNode.getNodeType().getLocalName());
- tmpNode = tmpNode.getParent();
- }
-
- return DOT_JOINER.join(breadCrumbs);
- }
-
- /**
- * @param treeRootNode
- * @return dom tree, containing same node structure, yang nodes are
- * associated to dom nodes as user data
- */
- public static org.w3c.dom.Document buildShadowDomTree(final CompositeNode treeRootNode) {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- org.w3c.dom.Document doc = null;
- try {
- DocumentBuilder bob = dbf.newDocumentBuilder();
- doc = bob.newDocument();
- } catch (ParserConfigurationException e) {
- LOG.error("documentBuilder problem", e);
- return null;
- }
-
- final Deque<SimpleEntry<org.w3c.dom.Node, Node<?>>> jobQueue = new ArrayDeque<>();
- jobQueue.push(new SimpleEntry<org.w3c.dom.Node, Node<?>>(doc, treeRootNode));
-
- while (!jobQueue.isEmpty()) {
- SimpleEntry<org.w3c.dom.Node, Node<?>> job = jobQueue.pop();
- org.w3c.dom.Node jointPlace = job.getKey();
- Node<?> item = job.getValue();
- QName nodeType = item.getNodeType();
- Element itemEl = doc.createElementNS(nodeType.getNamespace().toString(), item.getNodeType().getLocalName());
- itemEl.setUserData(USER_KEY_NODE, item, null);
- if (item instanceof SimpleNode<?>) {
- Object value = ((SimpleNode<?>) item).getValue();
- if(value != null) {
- itemEl.setTextContent(String.valueOf(value));
- }
- }
- if (item instanceof NodeModification) {
- ModifyAction modificationAction = ((NodeModification) item).getModificationAction();
- if (modificationAction != null) {
- itemEl.setAttribute("modifyAction", modificationAction.toString());
- }
- }
-
- jointPlace.appendChild(itemEl);
-
- if (item instanceof CompositeNode) {
- for (Node<?> child : ((CompositeNode) item).getValue()) {
- jobQueue.push(new SimpleEntry<org.w3c.dom.Node, Node<?>>(itemEl, child));
- }
- }
- }
-
- return doc;
- }
-
- /**
- * @param doc
- * @param xpathEx
- * @return user data value on found node
- * @throws XPathExpressionException
- */
- @SuppressWarnings("unchecked")
- public static <T> T findNodeByXpath(final org.w3c.dom.Document doc, final String xpathEx) throws XPathExpressionException {
- T userNode = null;
- XPathFactory xPathfactory = XPathFactory.newInstance();
- XPath xpath = xPathfactory.newXPath();
- XPathExpression expr = xpath.compile(xpathEx);
-
- org.w3c.dom.Node result = (org.w3c.dom.Node) expr.evaluate(doc, XPathConstants.NODE);
- if (result != null) {
- userNode = (T) result.getUserData(USER_KEY_NODE);
- }
-
- return userNode;
- }
-
- /**
- * build NodeMap, where key = qName; value = node
- *
- * @param value
- * @return map of children, where key = qName and value is list of children
- * groupped by qName
- */
- public static Map<QName, List<Node<?>>> buildNodeMap(final List<Node<?>> value) {
- Map<QName, List<Node<?>>> nodeMapTmp = Maps.newLinkedHashMap();
- if (value == null) {
- throw new IllegalStateException("nodeList should not be null or empty");
- }
- for (Node<?> node : value) {
- List<Node<?>> qList = nodeMapTmp.get(node.getNodeType());
- if (qList == null) {
- qList = new ArrayList<>();
- nodeMapTmp.put(node.getNodeType(), qList);
- }
- qList.add(node);
- }
- return nodeMapTmp;
- }
-
- /**
- * @param context
- * @return map of lists, where key = path; value = {@link DataSchemaNode}
- */
- public static Map<String, ListSchemaNode> buildMapOfListNodes(final SchemaContext context) {
- Map<String, ListSchemaNode> mapOfLists = new HashMap<>();
-
- final Deque<DataSchemaNode> jobQueue = new ArrayDeque<>();
- jobQueue.addAll(context.getDataDefinitions());
-
- while (!jobQueue.isEmpty()) {
- DataSchemaNode dataSchema = jobQueue.pop();
- if (dataSchema instanceof ListSchemaNode) {
- mapOfLists.put(schemaPathToPath(dataSchema.getPath().getPathFromRoot()), (ListSchemaNode) dataSchema);
- }
-
- if (dataSchema instanceof DataNodeContainer) {
- jobQueue.addAll(((DataNodeContainer) dataSchema).getChildNodes());
- }
- }
-
- return mapOfLists;
- }
-
- /**
- * @param qNamesPath
- * @return path
- */
- private static String schemaPathToPath(final Iterable<QName> qNamesPath) {
- return DOT_JOINER.join(Iterables.transform(qNamesPath, LOCALNAME_FUNCTION));
- }
-
- /**
- * add given node to it's parent's list of children
- *
- * @param newNode
- */
- public static void fixParentRelation(final Node<?> newNode) {
- if (newNode.getParent() != null) {
- List<Node<?>> siblings = newNode.getParent().getValue();
- if (!siblings.contains(newNode)) {
- siblings.add(newNode);
- }
- }
- }
-
- /**
- * crawl all children of given node and assign it as their parent
- *
- * @param parentNode
- */
- public static void fixChildrenRelation(final CompositeNode parentNode) {
- if (parentNode.getValue() != null) {
- for (Node<?> child : parentNode.getValue()) {
- if (child instanceof AbstractNodeTO<?>) {
- ((AbstractNodeTO<?>) child).setParent(parentNode);
- }
- }
- }
- }
-
- /**
- * @param keys
- * @param dataMap
- * @return list of values of map, found by given keys
- */
- public static <T, K> List<K> collectMapValues(final List<T> keys, final Map<T, K> dataMap) {
- List<K> valueSubList = new ArrayList<>();
- for (T key : keys) {
- valueSubList.add(dataMap.get(key));
- }
-
- return valueSubList;
- }
-
- /**
- * @param nodes
- * @return list of children in list of appropriate type
- */
- public static List<Node<?>> buildChildrenList(final Node<?>... nodes) {
- return Lists.newArrayList(nodes);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @author michal.rehak
- * @param <T> type of node value
- *
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
-@Deprecated
-public class SimpleNodeModificationTOImpl<T> extends SimpleNodeTOImpl<T> {
- private static final long serialVersionUID = 1L;
-
- /**
- * @param qname
- * @param parent
- * @param value
- * @param modifyAction
- */
- public SimpleNodeModificationTOImpl(final QName qname, final CompositeNode parent,
- final T value, final ModifyAction modifyAction) {
- super(qname, parent, value);
- setModificationAction(modifyAction);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @author michal.rehak
- * @param <T> type of simple node value
- *
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
-@Deprecated
-public class SimpleNodeTOImpl<T> extends AbstractNodeTO<T> implements SimpleNode<T>, Serializable {
-
- private static final long serialVersionUID = 100L;
-
- /**
- * @param qname
- * @param parent
- * @param value
- */
- public SimpleNodeTOImpl(final QName qname, final CompositeNode parent, final T value) {
- super(qname, parent, value);
- }
-
- /**
- * @param qname
- * @param parent
- * @param value
- * @param modifyAction
- */
- public SimpleNodeTOImpl(final QName qname, final CompositeNode parent, final T value, final ModifyAction modifyAction) {
- super(qname, parent, value, modifyAction);
- }
-
- @Override
- public MutableSimpleNode<T> asMutable() {
- throw new IllegalAccessError("cast to mutable is not supported - "+getClass().getSimpleName());
- }
-
- @Override
- public String toString() {
-
- return super.toString() + ", value = "+getValue();
- }
-
- // Serialization related
-
- private void readObject(final ObjectInputStream aStream) throws IOException, ClassNotFoundException {
- aStream.defaultReadObject();
- QName qName = (QName)aStream.readObject();
- CompositeNode parent = (CompositeNode) aStream.readObject();
- T value = (T) aStream.readObject();
- ModifyAction modifyAction = (ModifyAction) aStream.readObject();
-
- init(qName, parent, value, modifyAction);
- }
-
- private void writeObject(final ObjectOutputStream aStream) throws IOException {
- aStream.defaultWriteObject();
- //manually serialize superclass
- aStream.writeObject(getQName());
- aStream.writeObject(getParent());
- aStream.writeObject(getValue());
- aStream.writeObject(getModificationAction());
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import java.io.InputStream;
-import java.net.URI;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Deque;
-
-import javax.xml.stream.XMLEventReader;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.events.Characters;
-import javax.xml.stream.events.StartElement;
-import javax.xml.stream.events.XMLEvent;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-
-/**
- * The XML Tree Builder is builder utility class designed to facilitate of
- * loading, reading and parsing XML documents into YANG DOM represented by
- * yang-data-api. <br>
- * The method {@link #buildDataTree(InputStream)} is designed to take and parse
- * XML as {@link InputStream}. The output of the operation SHOULD be root
- * <code>CompositeNode</code> or <code>SimpleElement</code> depends by which
- * element XML begins. The XML header is omitted by XML parser.
- *
- * @author Lukas Sedlak
- *
- * @see CompositeNode
- * @see SimpleNode
- * @see Node
- */
-public final class XmlTreeBuilder {
- private final static XMLInputFactory XML_INPUT_FACTORY = XMLInputFactory.newInstance();
-
- private XmlTreeBuilder() {
- }
-
- /**
- * The method is designed to take and parse XML as {@link InputStream}. The
- * output of the operation SHOULD be root <code>CompositeNode</code> or
- * <code>SimpleElement</code> depends on element that XML document begins.
- * The XML header is omitted by XML parser.
- *
- * @param inputStream
- * XML Input Stream
- * @return root <code>Node</code> element conformant to XML start element in
- * most cases it will be CompositeNode which contains child Nodes
- * @throws XMLStreamException
- */
- public static Node<?> buildDataTree(final InputStream inputStream) throws XMLStreamException {
- final XMLEventReader eventReader = XML_INPUT_FACTORY.createXMLEventReader(inputStream);
-
- final Deque<Node<?>> processingQueue = new ArrayDeque<>();
- Node<?> parentNode = null;
- Node<?> root = null;
- while (eventReader.hasNext()) {
- final XMLEvent event = eventReader.nextEvent();
-
- if (event.isStartElement()) {
- final StartElement startElement = event.asStartElement();
- if (!processingQueue.isEmpty()) {
- parentNode = processingQueue.peek();
- }
- MutableCompositeNode compParentNode = null;
- if (parentNode instanceof MutableCompositeNode) {
- compParentNode = (MutableCompositeNode) parentNode;
- }
- Node<?> newNode = null;
- if (isCompositeNodeEvent(eventReader, event)) {
- newNode = resolveCompositeNodeFromStartElement(startElement, compParentNode);
- } else if (isSimpleNodeEvent(eventReader, event)) {
- newNode = resolveSimpleNodeFromStartElement(eventReader, startElement, compParentNode);
- }
-
- if (newNode != null) {
- processingQueue.push(newNode);
- if (compParentNode != null) {
- compParentNode.getValue().add(newNode);
- }
- }
- } else if (event.isEndElement()) {
- root = processingQueue.pop();
- if (root instanceof MutableCompositeNode) {
- ((MutableCompositeNode) root).init();
- }
- }
- }
- return root;
- }
-
- /**
- * Checks if the XMLEvent is compliant to SimpleNode tag that contains only
- * characters value. If the SimpleNode is composed only by empty XML tag
- * (i.e. {@code <emptyTag />} or {@code<emptyTag></emptyTag>}) the result
- * will be also <code>true</code>.
- *
- * @param event
- * actual XMLEvent that is processed
- * @return <code>true</code> only and only if the XMLEvent Start Element is
- * Simple element tag and contains character values or is empty XML
- * tag.
- * @throws XMLStreamException
- *
- * @see SimpleNode
- */
- private static boolean isSimpleNodeEvent(final XMLEventReader eventReader, final XMLEvent event) throws XMLStreamException {
- checkArgument(event != null, "XML Event cannot be NULL!");
- if (event.isStartElement()) {
- if (eventReader.hasNext()) {
- final XMLEvent innerEvent;
- innerEvent = eventReader.peek();
- if (innerEvent.isCharacters()) {
- final Characters chars = innerEvent.asCharacters();
- if (!chars.isWhiteSpace()) {
- return true;
- }
- } else if (innerEvent.isEndElement()) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Checks if XMLEvent is equivalent to CompositeNode Event. The
- * CompositeNode Event is XML element that conforms to the XML element that
- * contains 1..N XML child elements. (i.e. {@code <compositeNode>
- * <simpleNode>data</simpleNode>
- * </compositeNode>})
- *
- * @param event
- * actual XMLEvent that is processed
- * @return <code>true</code> only if XML Element contains 1..N child
- * elements, otherwise returns <code>false</code>
- * @throws XMLStreamException
- *
- * @see CompositeNode
- */
- private static boolean isCompositeNodeEvent(final XMLEventReader eventReader, final XMLEvent event) throws XMLStreamException {
- checkArgument(event != null, "XML Event cannot be NULL!");
- if (event.isStartElement()) {
- if (eventReader.hasNext()) {
- XMLEvent innerEvent;
- innerEvent = eventReader.peek();
- if (innerEvent.isCharacters()) {
- Characters chars = innerEvent.asCharacters();
- if (chars.isWhiteSpace()) {
- eventReader.nextEvent();
- innerEvent = eventReader.peek();
- }
- }
- if (innerEvent.isStartElement()) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Creates and returns <code>SimpleNode</code> instance from actually
- * processed XML Start Element.
- *
- * @param startElement
- * actual XML Start Element that is processed
- * @param parent
- * Parent CompositeNode
- * @return <code>new SimpleNode</code> instance from actually processed XML
- * Start Element
- * @throws XMLStreamException
- *
- * @see SimpleNode
- */
- private static SimpleNode<String> resolveSimpleNodeFromStartElement(final XMLEventReader eventReader,
- final StartElement startElement, final CompositeNode parent) throws XMLStreamException {
- checkArgument(startElement != null, "Start Element cannot be NULL!");
- String data = null;
-
- if (eventReader.hasNext()) {
- final XMLEvent innerEvent = eventReader.peek();
- if (innerEvent.isCharacters()) {
- final Characters chars = innerEvent.asCharacters();
- if (!chars.isWhiteSpace()) {
- data = innerEvent.asCharacters().getData();
- }
- } else if (innerEvent.isEndElement()) {
- data = "";
- }
- }
- return NodeFactory.createImmutableSimpleNode(resolveElementQName(startElement), parent, data);
- }
-
- /**
- * Creates and returns <code>MutableCompositeNode</code> instance from
- * actually processed XML Start Element.
- *
- * @param startElement
- * actual XML Start Element that is processed
- * @param parent
- * Parent CompositeNode
- * @return <code>new MutableCompositeNode</code> instance from actually
- * processed XML Start Element
- *
- * @see CompositeNode
- * @see MutableCompositeNode
- */
- private static MutableCompositeNode resolveCompositeNodeFromStartElement(final StartElement startElement,
- final CompositeNode parent) {
- checkArgument(startElement != null, "Start Element cannot be NULL!");
-
- return NodeFactory.createMutableCompositeNode(resolveElementQName(startElement), parent,
- new ArrayList<Node<?>>(), ModifyAction.CREATE, null);
- }
-
- /**
- * Extract and retrieve XML Element QName to OpenDaylight QName.
- *
- * @param element
- * Start Element
- * @return QName instance composed of <code>elements</code> Namespace and
- * Local Part.
- *
- * @see QName
- */
- private static QName resolveElementQName(final StartElement element) {
- checkArgument(element != null, "Start Element cannot be NULL!");
-
- final String nsURI = element.getName().getNamespaceURI();
- final String localName = element.getName().getLocalPart();
- return new QName(URI.create(nsURI), localName);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface AugmentationCodec<A extends Augmentation<?>> extends DomCodec<A> {
- @Override
- CompositeNode serialize(ValueWithQName<A> input);
-
- @Override
- ValueWithQName<A> deserialize(Node<?> input);
-
- QName getAugmentationQName();
-
- /**
- * Check if this codec was created for augmentation with given target node
- * path.
- *
- * @param path
- * identifier of augmentation target node
- * @return true, if this codec is generated for augmentation pointing node
- * with given path, false otherwise
- */
- boolean isAcceptable(InstanceIdentifier<?> path);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import java.util.Map.Entry;
-import java.util.Set;
-
-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.RpcService;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-
-import com.google.common.base.Optional;
-
-public interface BindingIndependentMappingService {
-
- /**
- * Get codec registry.
- *
- * @return codec registry
- */
- CodecRegistry getCodecRegistry();
-
- /**
- * Convert given DataObject data to DOM-like node.
- *
- * @param data
- * DataObject instance
- * @return CompositeNode created from DataObject instance
- */
- CompositeNode toDataDom(DataObject data);
-
- /**
- * Create map entry representing node data (key = data schema node
- * identifier, value = value is node data representation as Composite node)
- * from entry representing node class (key = class object identifier, value
- * = class object).
- *
- * @param entry
- * map entry, where key is class object identifier and value
- * class object
- * @return data schema node identifier
- */
- Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> toDataDom(
- Entry<InstanceIdentifier<? extends DataObject>, DataObject> entry);
-
- /**
- * Create data schema node identifier from class object identifier.
- *
- * @param path
- * class object identifier
- * @return data schema node identifier
- */
- org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier toDataDom(InstanceIdentifier<? extends DataObject> path);
-
- /**
- * Create DataObject instance from CompositeNode data based on given path.
- *
- * @param path
- * node identifier
- * @param result
- * node data
- * @return inputClass instance created from composite node input
- */
- DataObject dataObjectFromDataDom(InstanceIdentifier<? extends DataObject> path, CompositeNode result)
- throws DeserializationException;
-
- /**
- * Create class object identifier from data schema node identifier.
- *
- * @param entry
- * data schema node identifier
- * @return class object identifier
- */
- InstanceIdentifier<?> fromDataDom(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier entry)
- throws DeserializationException;
-
- /**
- * Returns the list of currently-known QNames for instances of a service.
- *
- * @param service
- * RPC service
- * @return List of QNames. The user may not modify this list.
- */
- Set<QName> getRpcQNamesFor(Class<? extends RpcService> service);
-
- /**
- * Get RpcService by namespace and revision.
- *
- * @param namespace
- * rpc service namespace
- * @param revision
- * rpc service revision
- * @return Optional reference on RpcServices based on given namespace and
- * revision
- */
- Optional<Class<? extends RpcService>> getRpcServiceClassFor(String namespace, String revision);
-
- /**
- * Create inputClass instance from CompositeNode data.
- *
- * @param inputClass
- * expected type of resulting object
- * @param domInput
- * node data
- * @return inputClass instance created from composite node input
- */
- DataContainer dataObjectFromDataDom(Class<? extends DataContainer> inputClass, CompositeNode domInput);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface ChoiceCaseCodec<C extends DataContainer> extends DataContainerCodec<C> {
- @Override
- CompositeNode serialize(ValueWithQName<C> input);
-
- @Override
- ValueWithQName<C> deserialize(Node<?> input);
-
- boolean isAcceptable(Node<?> input);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface ChoiceCodec<C> extends DomCodec<C> {
- @Override
- Node<?> serialize(ValueWithQName<C> input);
-
- @Override
- ValueWithQName<C> deserialize(Node<?> input);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import java.util.List;
-
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.Identifier;
-import org.opendaylight.yangtools.yang.common.QName;
-
-public interface CodecRegistry {
-
- InstanceIdentifierCodec getInstanceIdentifierCodec();
-
- IdentityCodec<?> getIdentityCodec();
-
- <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(Class<T> object);
-
- <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(Class<T> object);
-
- <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(Class<T> object);
-
- <T extends Augmentation<?>> AugmentationCodec<T> getCodecForAugmentation(Class<T> object);
-
- <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(Class<T> codec);
-
- Class<?> getClassForPath(List<QName> names);
-
- IdentifierCodec<?> getKeyCodecForPath(List<QName> names);
-
-
- void bindingClassEncountered(Class<?> cls);
-
- void putPathToClass(List<QName> names, Class<?> cls);
-
- QName getQNameForAugmentation(Class<?> cls);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface DataContainerCodec<T extends DataContainer> extends DomCodec<T> {
-
- @Override
- CompositeNode serialize(ValueWithQName<T> input);
-
- @Override
- ValueWithQName<T> deserialize(Node<?> input);
-
- ValueWithQName<T> deserialize(Node<?> input, InstanceIdentifier<?> bindingIdentifier);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface DomCodec<I> extends BindingCodec<Node<?>, ValueWithQName<I>>{
- @Override
- Node<?> serialize(ValueWithQName<I> input);
-
- @Override
- ValueWithQName<I> deserialize(Node<?> input);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.Identifier;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface IdentifierCodec<I extends Identifier<?>> extends DomCodec<I> {
- @Override
- ValueWithQName<I> deserialize(Node<?> input);
-
- @Override
- CompositeNode serialize(ValueWithQName<I> input);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-
-public interface InstanceIdentifierCodec extends BindingCodec<YangInstanceIdentifier, InstanceIdentifier<?>> {
- @Override
- YangInstanceIdentifier serialize(InstanceIdentifier<?> input);
-
- @Override
- InstanceIdentifier<?> deserialize(YangInstanceIdentifier input);
-}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
if(child == null && current instanceof SchemaContext) {
child = tryFindNotification((SchemaContext) current, qname)
- .orNull();
+ .or(tryFindRpc(((SchemaContext) current), qname)).orNull();
+ }
+ } else if (current instanceof ChoiceSchemaNode) {
+ child = ((ChoiceSchemaNode) current).getCaseNodeByName(qname);
+ } else if (current instanceof RpcDefinition) {
+ switch (qname.getLocalName()) {
+ case "input":
+ child = ((RpcDefinition) current).getInput();
+ break;
+ case "output":
+ child = ((RpcDefinition) current).getOutput();
+ break;
+ default:
+ child = null;
+ break;
}
- } else if (current instanceof ChoiceNode) {
- child = ((ChoiceNode) current).getCaseNodeByName(qname);
} else {
throw new IllegalArgumentException(String.format("Schema node %s does not allow children.", current));
}
current = child;
}
- Preconditions.checkArgument(current instanceof DataNodeContainer,"Schema path must point to container or list. Supplied path %s pointed to: %s",path,current);
+ Preconditions.checkArgument(current instanceof DataNodeContainer,"Schema path must point to container or list or an rpc input/output. Supplied path %s pointed to: %s",path,current);
root = (DataNodeContainer) current;
}
return Optional.<SchemaNode> fromNullable(Iterables.find(ctx.getGroupings(), new SchemaNodePredicate(qname), null));
}
+ private Optional<SchemaNode> tryFindRpc(final SchemaContext ctx, final QName qname) {
+ return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getOperations(), new SchemaNodePredicate(qname), null));
+ }
+
private Optional<SchemaNode> tryFindNotification(final SchemaContext ctx, final QName qname) {
return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getNotifications(), new SchemaNodePredicate(qname), null));
}
if(schema == null && parent instanceof NotificationDefinition) {
schema = ((NotificationDefinition) parent);
}
- } else if(parent instanceof ChoiceNode) {
- for(final ChoiceCaseNode caze : ((ChoiceNode) parent).getCases()) {
- final DataSchemaNode potential = caze.getDataChildByName(qname);
- if(potential != null) {
- schema = potential;
- break;
- }
- }
+ } else if(parent instanceof ChoiceSchemaNode) {
+ schema = findChildInCases((ChoiceSchemaNode) parent, qname);
} else {
throw new IllegalStateException("Unsupported schema type "+ parent.getClass() +" on stack.");
}
return schema;
}
+ private SchemaNode findChildInCases(final ChoiceSchemaNode parent, final QName qname) {
+ DataSchemaNode schema = null;
+ for(final ChoiceCaseNode caze : parent.getCases()) {
+ final DataSchemaNode potential = caze.getDataChildByName(qname);
+ if(potential != null) {
+ schema = potential;
+ break;
+ }
+ }
+ return schema;
+ }
+
+ private SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
+ DataSchemaNode schema = null;
+ for(final ChoiceCaseNode caze : parent.getCases()) {
+ final DataSchemaNode potential = caze.getDataChildByName(qname);
+ if(potential != null) {
+ schema = caze;
+ break;
+ }
+ }
+ return schema;
+ }
+
public void startList(final PathArgument name) {
final SchemaNode schema = getSchema(name);
Preconditions.checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema.getPath());
return (LeafListSchemaNode) parent;
}
- public ChoiceNode startChoiceNode(final NodeIdentifier name) {
+ public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
LOG.debug("Enter choice {}", name);
final SchemaNode schema = getSchema(name);
- Preconditions.checkArgument(schema instanceof ChoiceNode, "Node %s is not a choice", schema.getPath());
+ Preconditions.checkArgument(schema instanceof ChoiceSchemaNode, "Node %s is not a choice", schema.getPath());
schemaStack.push(schema);
- return (ChoiceNode)schema;
+ return (ChoiceSchemaNode)schema;
}
public SchemaNode startContainerNode(final NodeIdentifier name) {
public AugmentationSchema startAugmentationNode(final AugmentationIdentifier identifier) {
LOG.debug("Enter augmentation {}", identifier);
- final Object parent = getParent();
+ Object parent = getParent();
Preconditions.checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
+ if(parent instanceof ChoiceSchemaNode) {
+ final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
+ parent = findCaseByChild((ChoiceSchemaNode) parent, name);
+ }
Preconditions.checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer",parent);
final AugmentationSchema schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent, identifier.getPossibleChildNames());
final HashSet<DataSchemaNode> realChildSchemas = new HashSet<>();
for(final DataSchemaNode child : schema.getChildNodes()) {
realChildSchemas.add(((DataNodeContainer) parent).getDataChildByName(child.getQName()));
}
- final AugmentationSchema resolvedSchema = new AugmentationSchemaProxy(schema, realChildSchemas);
+ final AugmentationSchema resolvedSchema = new EffectiveAugmentationSchema(schema, realChildSchemas);
schemaStack.push(resolvedSchema);
return resolvedSchema;
}
package org.opendaylight.yangtools.yang.data.impl.codec.xml;
import com.google.common.base.Preconditions;
-
import java.net.URI;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.util.AbstractStringInstanceIdentifierCodec;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.w3c.dom.Element;
final class ElementInstanceIdentifierParser extends AbstractStringInstanceIdentifierCodec {
private final SchemaContext schema;
private final Element element;
+ private final DataSchemaContextTree dataContextTree;
ElementInstanceIdentifierParser(final SchemaContext schema, final Element element) {
this.element = Preconditions.checkNotNull(element);
this.schema = Preconditions.checkNotNull(schema);
+ this.dataContextTree = DataSchemaContextTree.from(schema);
}
@Override
return QName.create(module.getQNameModule(), localName);
}
+ @Override
+ protected DataSchemaContextTree getDataContextTree() {
+ return dataContextTree;
+ }
+
}
return codec.deserialize(element.getTextContent().trim());
}
- public static Element serialize(final YangInstanceIdentifier id, final Element element) {
- final RandomPrefixInstanceIdentifierSerializer codec = new RandomPrefixInstanceIdentifierSerializer();
+ public static Element serialize(final YangInstanceIdentifier id, final Element element, SchemaContext context) {
+ final RandomPrefixInstanceIdentifierSerializer codec = new RandomPrefixInstanceIdentifierSerializer(context);
final String str = codec.serialize(id);
for (Entry<URI, String> e : codec.getPrefixes()) {
return element;
}
+ /**
+ *
+ * @deprecated USe {@link #serialize(YangInstanceIdentifier, Element, SchemaContext)} instead.
+ */
+ @Deprecated
+ public static Element serialize(final YangInstanceIdentifier id, final Element element) {
+ throw new UnsupportedOperationException("Not supported, due to buggy API contract.");
+ }
+
private static String getIdAndPrefixAsStr(final String pathPart) {
int predicateStartIndex = pathPart.indexOf('[');
return predicateStartIndex == -1 ? pathPart : pathPart.substring(0, predicateStartIndex);
import java.net.URI;
import java.util.Map;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.util.AbstractStringInstanceIdentifierCodec;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
final class RandomPrefixInstanceIdentifierSerializer extends AbstractStringInstanceIdentifierCodec {
private final RandomPrefix prefixes = new RandomPrefix();
+ private final DataSchemaContextTree schemaTree;
+
+
+ RandomPrefixInstanceIdentifierSerializer(SchemaContext ctx) {
+ schemaTree = DataSchemaContextTree.from(ctx);
+ }
Iterable<Map.Entry<URI, String>> getPrefixes() {
return prefixes.getPrefixes();
throw new UnsupportedOperationException("Not implemented");
}
+ @Override
+ protected DataSchemaContextTree getDataContextTree() {
+ return schemaTree;
+ }
+
}
*/
package org.opendaylight.yangtools.yang.data.impl.codec.xml;
-import static javax.xml.XMLConstants.DEFAULT_NS_PREFIX;
-
import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
import java.io.IOException;
+import java.io.StringWriter;
+import java.util.Map;
+import javax.xml.XMLConstants;
+import java.io.StringWriter;
+import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stax.StAXResult;
+import javax.xml.transform.stream.StreamResult;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
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.stream.NormalizedNodeStreamAttributeWriter;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.w3c.dom.Element;
/**
* A {@link NormalizedNodeStreamWriter} which translates the events into an
* {@link XMLStreamWriter}, resulting in a RFC 6020 XML encoding.
*/
-public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
+public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNodeStreamAttributeWriter {
+
+ private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
private final XMLStreamWriter writer;
private final SchemaTracker tracker;
private final XmlStreamUtils streamUtils;
+ private RandomPrefix randomPrefix;
private XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer, final SchemaContext context, final SchemaPath path) {
this.writer = Preconditions.checkNotNull(writer);
this.tracker = SchemaTracker.create(context, path);
this.streamUtils = XmlStreamUtils.create(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, context);
+ randomPrefix = new RandomPrefix();
}
/**
private void writeStartElement( QName qname) throws XMLStreamException {
String ns = qname.getNamespace().toString();
- writer.writeStartElement(DEFAULT_NS_PREFIX, qname.getLocalName(), ns);
+ writer.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, qname.getLocalName(), ns);
if(writer.getNamespaceContext() != null) {
- String parentNs = writer.getNamespaceContext().getNamespaceURI(DEFAULT_NS_PREFIX);
+ String parentNs = writer.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX);
if (!ns.equals(parentNs)) {
writer.writeDefaultNamespace(ns);
}
}
}
+ private void writeElement(final QName qname, final SchemaNode schemaNode, final Object value, final Map<QName, String> attributes) throws IOException {
+ try {
+ writeStartElement(qname);
+ writeAttributes(attributes);
+ if (value != null) {
+ streamUtils.writeValue(writer, schemaNode, value);
+ }
+ writer.writeEndElement();
+ } catch (XMLStreamException e) {
+ throw new IOException("Failed to emit element", e);
+ }
+ }
+
private void startElement(final QName qname) throws IOException {
try {
writeStartElement(qname);
writeElement(schema.getQName(), schema, value);
}
+ @Override
+ public void leafNode(final NodeIdentifier name, final Object value, final Map<QName, String> attributes) throws IOException {
+ final LeafSchemaNode schema = tracker.leafNode(name);
+ writeElement(schema.getQName(), schema, value, attributes);
+ }
+
+ @Override
+ public void leafSetEntryNode(final Object value, final Map<QName, String> attributes) throws IOException, IllegalArgumentException {
+ final LeafListSchemaNode schema = tracker.leafSetEntryNode();
+ writeElement(schema.getQName(), schema, value, attributes);
+ }
+
+ @Override
+ public void startContainerNode(final NodeIdentifier name, final int childSizeHint, final Map<QName, String> attributes) throws IOException, IllegalArgumentException {
+ startContainerNode(name, childSizeHint);
+ writeAttributes(attributes);
+ }
+
+ @Override
+ public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint, final Map<QName, String> attributes) throws IOException, IllegalStateException {
+ startUnkeyedListItem(name, childSizeHint);
+ writeAttributes(attributes);
+ }
+
+ @Override
+ public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint, final Map<QName, String> attributes) throws IOException, IllegalArgumentException {
+ startMapEntryNode(identifier, childSizeHint);
+ writeAttributes(attributes);
+ }
+
+ private void writeAttributes(final Map<QName, String> attributes) throws IOException {
+ for (final Map.Entry<QName, String> qNameStringEntry : attributes.entrySet()) {
+ try {
+ final String namespace = qNameStringEntry.getKey().getNamespace().toString();
+ if(Strings.isNullOrEmpty(namespace)) {
+ writer.writeAttribute(qNameStringEntry.getKey().getLocalName(), qNameStringEntry.getValue());
+ } else {
+ final String prefix = randomPrefix.encodePrefix(qNameStringEntry.getKey().getNamespace());
+ writer.writeAttribute(prefix, namespace, qNameStringEntry.getKey().getLocalName(), qNameStringEntry.getValue());
+ }
+ } catch (final XMLStreamException e) {
+ throw new IOException("Unable to emit attribute " + qNameStringEntry, e);
+ }
+ }
+ }
+
@Override
public void startLeafSet(final NodeIdentifier name, final int childSizeHint) {
tracker.startLeafSet(name);
@Override
public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
- final QName qname = schema.getQName();
- try {
- writeStartElement(qname);
- if (value != null) {
- streamUtils.writeValue(writer, (Node<?>)value, schema);
+ if (value != null) {
+ Preconditions.checkArgument(value instanceof DOMSource, "AnyXML value must be DOMSource, not %s", value);
+ final QName qname = schema.getQName();
+ final DOMSource domSource = (DOMSource) value;
+ Preconditions.checkNotNull(domSource.getNode());
+ Preconditions.checkArgument(domSource.getNode().getNodeName().equals(qname.getLocalName()));
+ Preconditions.checkArgument(domSource.getNode().getNamespaceURI().equals(qname.getNamespace().toString()));
+ try {
+ // TODO can the transformer be a constant ? is it thread safe ?
+ final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ // Writer has to be wrapped in a wrapper that ignores endDocument event
+ // EndDocument event forbids any other modification to the writer so a nested anyXml breaks serialization
+ transformer.transform(domSource, new StAXResult(new DelegateWriterNoEndDoc(writer)));
+ } catch (final TransformerException e) {
+ throw new IOException("Unable to transform anyXml(" + name + ") value: " + value, e);
}
- writer.writeEndElement();
- } catch (XMLStreamException e) {
- throw new IOException("Failed to emit element", e);
+ }
+ }
+
+ public static String toString(final Element xml) {
+ try {
+ final Transformer transformer = TransformerFactory.newInstance().newTransformer();
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+
+ final StreamResult result = new StreamResult(new StringWriter());
+ final DOMSource source = new DOMSource(xml);
+ transformer.transform(source, result);
+
+ return result.getWriter().toString();
+ } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
+ throw new RuntimeException("Unable to serialize xml element " + xml, e);
}
}
throw new IOException("Failed to flush writer", e);
}
}
+
+ /**
+ * Delegate writer that ignores writeEndDocument event. Used for AnyXml serialization.
+ */
+ private static final class DelegateWriterNoEndDoc implements XMLStreamWriter {
+ private final XMLStreamWriter writer;
+
+ public DelegateWriterNoEndDoc(final XMLStreamWriter writer) {
+ this.writer = writer;
+ }
+
+ @Override
+ public void writeStartElement(final String localName) throws XMLStreamException {
+ writer.writeStartElement(localName);
+ }
+
+ @Override
+ public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
+ writer.writeStartElement(namespaceURI, localName);
+ }
+
+ @Override
+ public void writeStartElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
+ writer.writeStartElement(prefix, localName, namespaceURI);
+ }
+
+ @Override
+ public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
+ writer.writeEmptyElement(namespaceURI, localName);
+ }
+
+ @Override
+ public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
+ writer.writeEmptyElement(prefix, localName, namespaceURI);
+ }
+
+ @Override
+ public void writeEmptyElement(final String localName) throws XMLStreamException {
+ writer.writeEmptyElement(localName);
+ }
+
+ @Override
+ public void writeEndElement() throws XMLStreamException {
+ writer.writeEndElement();
+
+ }
+
+ @Override
+ public void writeEndDocument() throws XMLStreamException {
+ // End document is disabled
+ }
+
+ @Override
+ public void close() throws XMLStreamException {
+ writer.close();
+ }
+
+ @Override
+ public void flush() throws XMLStreamException {
+ writer.flush();
+ }
+
+ @Override
+ public void writeAttribute(final String localName, final String value) throws XMLStreamException {
+ writer.writeAttribute(localName, value);
+ }
+
+ @Override
+ public void writeAttribute(final String prefix, final String namespaceURI, final String localName, final String value) throws XMLStreamException {
+ writer.writeAttribute(prefix, namespaceURI, localName, value);
+ }
+
+ @Override
+ public void writeAttribute(final String namespaceURI, final String localName, final String value) throws XMLStreamException {
+ writer.writeAttribute(namespaceURI, localName, value);
+ }
+
+ @Override
+ public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
+ // Workaround for default namespace
+ // If a namespace is not prefixed, it is is still treated as prefix namespace. This results in the NamespaceSupport class ignoring the namespace since xmlns is not a valid prefix
+ // Write the namespace at least as an attribute
+ // TODO this is a hotfix, the transformer itself should write namespaces passing the namespace in writeStartElement method
+ if (prefix.equals("xml") || prefix.equals("xmlns")) {
+ writer.writeAttribute(prefix, namespaceURI);
+ } else {
+ writer.writeNamespace(prefix, namespaceURI);
+ }
+ }
+
+ @Override
+ public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
+ writer.writeDefaultNamespace(namespaceURI);
+ }
+
+ @Override
+ public void writeComment(final String data) throws XMLStreamException {
+ writer.writeComment(data);
+ }
+
+ @Override
+ public void writeProcessingInstruction(final String target) throws XMLStreamException {
+ writer.writeProcessingInstruction(target);
+ }
+
+ @Override
+ public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
+ writer.writeProcessingInstruction(target, data);
+ }
+
+ @Override
+ public void writeCData(final String data) throws XMLStreamException {
+ writer.writeCData(data);
+ }
+
+ @Override
+ public void writeDTD(final String dtd) throws XMLStreamException {
+ writer.writeDTD(dtd);
+ }
+
+ @Override
+ public void writeEntityRef(final String name) throws XMLStreamException {
+ writer.writeEntityRef(name);
+ }
+
+ @Override
+ public void writeStartDocument() throws XMLStreamException {
+ }
+
+ @Override
+ public void writeStartDocument(final String version) throws XMLStreamException {
+ }
+
+ @Override
+ public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
+ }
+
+ @Override
+ public void writeCharacters(final String text) throws XMLStreamException {
+ writer.writeCharacters(text);
+ }
+
+ @Override
+ public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
+ writer.writeCharacters(text, start, len);
+ }
+
+ @Override
+ public String getPrefix(final String uri) throws XMLStreamException {
+ return writer.getPrefix(uri);
+ }
+
+ @Override
+ public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
+ // Disabled since it causes exceptions in the underlying writer
+ }
+
+ @Override
+ public void setDefaultNamespace(final String uri) throws XMLStreamException {
+ writer.setDefaultNamespace(uri);
+ }
+
+ @Override
+ public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
+ writer.setNamespaceContext(context);
+ }
+
+ @Override
+ public NamespaceContext getNamespaceContext() {
+ return writer.getNamespaceContext();
+ }
+
+ @Override
+ public Object getProperty(final String name) throws IllegalArgumentException {
+ return writer.getProperty(name);
+ }
+ }
}
*/
package org.opendaylight.yangtools.yang.data.impl.codec.xml;
-import static com.google.common.base.Preconditions.checkState;
-import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableList;
import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import java.util.Objects;
-import java.util.Set;
-import javax.activation.UnsupportedDataTypeException;
-import javax.annotation.Nonnull;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.stream.XMLOutputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamWriter;
-import javax.xml.transform.dom.DOMResult;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
-import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-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.NotificationDefinition;
-import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
-import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
public final class XmlDocumentUtils {
throw new UnsupportedOperationException("Utility class should not be instantiated");
}
- private static class ElementWithSchemaContext {
- Element element;
- SchemaContext schemaContext;
-
- ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
- this.schemaContext = schemaContext;
- this.element = element;
- }
-
- Element getElement() {
- return element;
- }
-
- SchemaContext getSchemaContext() {
- return schemaContext;
- }
- }
-
public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(SchemaContext.NAME, "operation");
- private static final QName RPC_REPLY_QNAME = QName.create(SchemaContext.NAME, "rpc-reply");
private static final Logger LOG = LoggerFactory.getLogger(XmlDocumentUtils.class);
- private static final XMLOutputFactory FACTORY = XMLOutputFactory.newFactory();
-
- /**
- * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
- * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
- * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
- * Node Container Schema and transformed accordingly.
- *
- * @param data Data DOM root element
- * @param schemaNode Data Node Container Schema
- * @param codecProvider XML Codec Provider
- * @return new instance of XML Document
- * @throws UnsupportedDataTypeException
- *
- * @deprecated Use {@link #toDocument(org.opendaylight.yangtools.yang.data.api.CompositeNode, com.google.common.base.Optional, org.opendaylight.yangtools.yang.model.api.DataNodeContainer, XmlCodecProvider)} instead.
- * The whole schema context allows for proper serialization of leafrefs.
- */
- @Deprecated
- public static Document toDocument(final CompositeNode data, final DataNodeContainer schemaNode, final XmlCodecProvider codecProvider)
- throws UnsupportedDataTypeException {
- return toDocument(data, Optional.<SchemaContext>absent(), schemaNode, codecProvider);
- }
-
- /**
- * Serializes data DOM node into a w3c DOM document. Whole schema context is used to resolve leafref elements.
- *
- * @param data Data DOM root element
- * @param schemaContext Entire schema context for correct leafref resolution
- * @param schemaNode Data Node Container Schema
- * @param codecProvider XML Codec Provider
- * @return serialized w3c DOM document
- * @throws UnsupportedDataTypeException
- */
- public static Document toDocument(final CompositeNode data, final SchemaContext schemaContext, final DataNodeContainer schemaNode, final XmlCodecProvider codecProvider)
- throws UnsupportedDataTypeException {
- return toDocument(data, Optional.of(schemaContext), schemaNode, codecProvider);
- }
-
- private static Document toDocument(final CompositeNode data, final Optional<SchemaContext> schemaContext, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
- throws UnsupportedDataTypeException {
- Preconditions.checkNotNull(data);
- Preconditions.checkNotNull(schema);
-
- if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
- throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
- }
-
- final DOMResult result = new DOMResult(getDocument());
- try {
- final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
- XmlStreamUtils xmlStreamUtils = schemaContext.isPresent() ? XmlStreamUtils.create(codecProvider, schemaContext.get()) : XmlStreamUtils.create(codecProvider);
- xmlStreamUtils.writeDocument(writer, data, (SchemaNode) schema);
- writer.close();
- return (Document)result.getNode();
- } catch (XMLStreamException e) {
- LOG.error("Failed to serialize data {}", data, e);
- return null;
- }
- }
public static Document getDocument() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
return doc;
}
- /**
- * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
- * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
- * nodes of Data Tree are transformed accordingly.
- *
- * @param data Data DOM root element
- * @param codecProvider XML Codec Provider
- * @return new instance of XML Document
- */
- public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider) {
- final DOMResult result = new DOMResult(getDocument());
- try {
- final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
- XmlStreamUtils.create(codecProvider).writeDocument(writer, data);
- writer.close();
- return (Document)result.getNode();
- } catch (XMLStreamException e) {
- LOG.error("Failed to serialize data {}", data, e);
- return null;
- }
- }
-
private static final Element createElementFor(final Document doc, final QName qname, final Object obj) {
final Element ret;
if (qname.getNamespace() != null) {
return ret;
}
- public static Element createElementFor(final Document doc, final Node<?> data) {
- return createElementFor(doc, data.getNodeType(), data);
- }
-
public static Element createElementFor(final Document doc, final NormalizedNode<?, ?> data) {
return createElementFor(doc, data.getNodeType(), data);
}
- public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
- final Optional<XmlCodecProvider> codecProvider) {
- return toDomNode(xmlElement, schema, codecProvider, Optional.<SchemaContext>absent());
- }
-
- public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
- final Optional<XmlCodecProvider> codecProvider, final Optional<SchemaContext> schemaContext) {
- if (schema.isPresent()) {
- if(schemaContext.isPresent()) {
- return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER), schemaContext.get());
- } else {
- return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER));
- }
- }
- return toDomNode(xmlElement);
- }
-
public static QName qNameFromElement(final Element xmlElement) {
String namespace = xmlElement.getNamespaceURI();
String localName = xmlElement.getLocalName();
return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
}
- private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
- checkQName(xmlElement, schema.getQName());
- if (schema instanceof DataNodeContainer) {
- return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
- } else if (schema instanceof LeafSchemaNode) {
- return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider,schemaCtx);
- } else if (schema instanceof LeafListSchemaNode) {
- return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider,schemaCtx);
- } else if (schema instanceof AnyXmlSchemaNode) {
- return toDomNode(xmlElement);
- }
- return null;
- }
-
- private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
- return toNodeWithSchema(xmlElement, schema, codecProvider, null);
- }
- protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
- final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
- final Object value = resolveValueFromSchemaType(xmlElement, schema, schema.getType(), codecProvider, schemaCtx);
- Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
- return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
- }
-
- private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
- final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
- final Object value = resolveValueFromSchemaType(xmlElement, schema, schema.getType(), codecProvider, schemaCtx);
- Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
- return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
- }
-
- private static Object resolveValueFromSchemaType(final Element xmlElement, final DataSchemaNode schema, final TypeDefinition<?> type,
- final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
-
- TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
- if (baseType instanceof LeafrefTypeDefinition) {
- final LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
- baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaCtx, schema);
- }
-
- final String text = xmlElement.getTextContent();
- final Object value;
-
- if (baseType instanceof InstanceIdentifierType) {
- value = InstanceIdentifierForXmlCodec.deserialize(xmlElement, schemaCtx);
- } else if (baseType instanceof IdentityrefTypeDefinition) {
- value = InstanceIdentifierForXmlCodec.toIdentity(text, xmlElement, schemaCtx);
- } else {
- final TypeDefinitionAwareCodec<?, ?> codec = codecProvider.codecFor(baseType);
- if (codec == null) {
- LOG.info("No codec for schema {}, falling back to text", schema);
- value = text;
- } else {
- value = codec.deserialize(text);
- }
- }
- return value;
- }
-
- private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
- final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
- List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
- Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
- return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
- }
public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
return Optional.of(action);
}
- private static void checkQName(final Element xmlElement, final QName qName) {
- checkState(Objects.equals(xmlElement.getNamespaceURI(), qName.getNamespace().toString()), "Not equal: %s to: %s for: %s and: %s", qName.getNamespace(), xmlElement.getNamespaceURI(), qName, xmlElement);
- checkState(qName.getLocalName().equals(xmlElement.getLocalName()), "Not equal: %s to: %s for: %s and: %s", qName.getLocalName(), xmlElement.getLocalName(), qName, xmlElement);
- }
public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Iterable<DataSchemaNode> dataSchemaNode) {
if (dataSchemaNode != null && qname != null) {
for (DataSchemaNode dsn : dataSchemaNode) {
if (qname.isEqualWithoutRevision(dsn.getQName())) {
return Optional.<DataSchemaNode> of(dsn);
- } else if (dsn instanceof ChoiceNode) {
- for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
+ } else if (dsn instanceof ChoiceSchemaNode) {
+ for (ChoiceCaseNode choiceCase : ((ChoiceSchemaNode) dsn).getCases()) {
Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
if (foundDsn != null && foundDsn.isPresent()) {
return foundDsn;
return Optional.absent();
}
- public static Node<?> toDomNode(final Document doc) {
- return toDomNode(doc.getDocumentElement());
- }
-
- private static Node<?> toDomNode(final Element element) {
- QName qname = qNameFromElement(element);
-
- ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
- NodeList nodes = element.getChildNodes();
- boolean isSimpleObject = true;
- String value = null;
- for (int i = 0; i < nodes.getLength(); i++) {
- org.w3c.dom.Node child = nodes.item(i);
- if (child instanceof Element) {
- isSimpleObject = false;
- values.add(toDomNode((Element) child));
- }
- if (isSimpleObject && child instanceof org.w3c.dom.Text) {
- value = element.getTextContent();
- if (!Strings.isNullOrEmpty(value)) {
- isSimpleObject = true;
- }
- }
- }
- if (isSimpleObject) {
- return new SimpleNodeTOImpl<>(qname, null, value);
- }
- return ImmutableCompositeNode.create(qname, values.build());
- }
-
- public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context, final SchemaContext schemaCtx) {
- return forEachChild(element.getChildNodes(), schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
-
- @Override
- public Optional<Node<?>> apply(final @Nonnull ElementWithSchemaContext input) {
- if (context.isPresent()) {
- Preconditions.checkNotNull(input);
- QName partialQName = qNameFromElement(input.getElement());
- Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
- if (schemaNode.isPresent()) {
- return Optional.<Node<?>> fromNullable(
- toNodeWithSchema(input.getElement(), schemaNode.get(), XmlUtils.DEFAULT_XML_CODEC_PROVIDER, input.getSchemaContext()));
- }
- }
- return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
- }
-
- });
- }
-
- public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context) {
- return toDomNodes(element, context, null);
- }
-
- /**
- * Converts XML Document containing notification data from Netconf device to
- * Data DOM Nodes. <br>
- * By specification defined in <a
- * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
- * there are xml elements containing notifications metadata, like eventTime
- * or root notification element which specifies namespace for which is
- * notification defined in yang model. Those elements MUST be stripped off
- * notifications body. This method returns pure notification body which
- * begins in element which is equal to notifications name defined in
- * corresponding yang model. Rest of notification metadata are obfuscated,
- * thus Data DOM contains only pure notification body.
- *
- * @param document
- * XML Document containing notification body
- * @param notifications
- * Notifications Definition Schema
- * @return Data DOM Nodes containing xml notification body definition or
- * <code>null</code> if there is no NotificationDefinition with
- * Element with equal notification QName defined in XML Document.
- */
- public static CompositeNode notificationToDomNodes(final Document document,
- final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
- if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
- final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
- for (int i = 0; i < originChildNodes.getLength(); i++) {
- org.w3c.dom.Node child = originChildNodes.item(i);
- if (child instanceof Element) {
- final Element childElement = (Element) child;
- final QName partialQName = qNameFromElement(childElement);
- final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
- notifications.get());
- if (notificationDef.isPresent()) {
- final Iterable<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
- final List<Node<?>> domNodes = toDomNodes(childElement,
- Optional.<Iterable<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
- return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
- }
- }
- }
- }
- return null;
- }
-
- /**
- * Transforms XML Document representing Rpc output body into Composite Node structure based on Rpc definition
- * within given Schema Context. The transformation is based on Rpc Definition which is defined in provided Schema Context.
- * If Rpc Definition is missing from given Schema Context the method will return <code>null</code>
- *
- * @param document XML Document containing Output RPC message
- * @param rpcName Rpc QName
- * @param context Schema Context
- * @return Rpc message in Composite Node data structures if Rpc definition is present within provided Schema Context, otherwise
- * returns <code>null</code>
- */
- public static CompositeNode rpcReplyToDomNodes(final Document document, final QName rpcName,
- final SchemaContext context) {
- Preconditions.checkNotNull(document);
- Preconditions.checkNotNull(rpcName);
- Preconditions.checkNotNull(context);
-
- Optional<RpcDefinition> rpcDefinition = findRpc(rpcName, context);
- if (rpcDefinition.isPresent()) {
- RpcDefinition rpc = rpcDefinition.get();
-
- final Collection<DataSchemaNode> outputNode = rpc.getOutput() != null ? rpc.getOutput().getChildNodes() : null;
- final Element rpcReplyElement = document.getDocumentElement();
- final QName partialQName = qNameFromElement(rpcReplyElement);
-
- if (RPC_REPLY_QNAME.equals(partialQName)) {
- final List<Node<?>> domNodes = toDomNodes(rpcReplyElement, Optional.fromNullable(outputNode), context);
- QName qName = rpc.getOutput() != null ? rpc.getOutput().getQName() : QName.cachedReference(QName.create(rpcName, "output"));
- List<Node<?>> rpcOutNodes = Collections.<Node<?>>singletonList(ImmutableCompositeNode.create(
- qName, domNodes));
- return ImmutableCompositeNode.create(rpcName, rpcOutNodes);
- }
- }
- return null;
- }
-
- /**
- * Method searches given schema context for Rpc Definition with given QName.
- * Returns Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
- *
- * @param rpc Rpc QName
- * @param context Schema Context
- * @return Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
- */
- private static Optional<RpcDefinition> findRpc(final QName rpc, final SchemaContext context) {
- Preconditions.checkNotNull(rpc);
- Preconditions.checkNotNull(context);
- for (final RpcDefinition rpcDefinition : context.getOperations()) {
- if ((rpcDefinition != null) && rpc.equals(rpcDefinition.getQName())) {
- return Optional.of(rpcDefinition);
- }
- }
- return Optional.absent();
- }
-
- public static CompositeNode notificationToDomNodes(final Document document,
- final Optional<Set<NotificationDefinition>> notifications) {
- return notificationToDomNodes(document, notifications,null);
- }
-
- private static Optional<NotificationDefinition> findNotification(final QName notifName,
- final Set<NotificationDefinition> notifications) {
- if ((notifName != null) && (notifications != null)) {
- for (final NotificationDefinition notification : notifications) {
- if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
- return Optional.<NotificationDefinition>fromNullable(notification);
- }
- }
- }
- return Optional.<NotificationDefinition>absent();
- }
-
- private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
- final int l = nodes.getLength();
- if (l == 0) {
- return ImmutableList.of();
- }
-
- final List<T> list = new ArrayList<>(l);
- for (int i = 0; i < l; i++) {
- org.w3c.dom.Node child = nodes.item(i);
- if (child instanceof Element) {
- Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
- if (result.isPresent()) {
- list.add(result.get());
- }
- }
- }
- return ImmutableList.copyOf(list);
- }
-
public static final XmlCodecProvider defaultValueCodecProvider() {
return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;
}
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.net.URI;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
-import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
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.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
return new XmlStreamUtils(codecProvider);
}
- /**
- * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
- * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
- *
- * @param data Data node
- * @return True if the data node will result in empty element body.
- */
- public static boolean isEmptyElement(final Node<?> data) {
- if (data == null) {
- return true;
- }
-
- if (data instanceof CompositeNode) {
- return ((CompositeNode) data).getValue().isEmpty();
- }
- if (data instanceof SimpleNode) {
- return data.getValue() == null;
- }
-
- // Safe default
- return false;
- }
-
/**
* Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
* and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
* @param writer XML Stream writer
* @param id InstanceIdentifier
* @throws XMLStreamException
+ *
+ * @deprecated Use {@link #writeInstanceIdentifier(XMLStreamWriter, YangInstanceIdentifier)} instead.
*/
+ @Deprecated
public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
Preconditions.checkNotNull(writer, "Writer may not be null");
Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
final RandomPrefix prefixes = new RandomPrefix();
final String str = XmlUtils.encodeIdentifier(prefixes, id);
-
- for (Entry<URI, String> e: prefixes.getPrefixes()) {
- final String ns = e.getKey().toString();
- final String p = e.getValue();
-
- writer.writeNamespace(p, ns);
- }
+ writeNamespaceDeclarations(writer,prefixes.getPrefixes());
writer.writeCharacters(str);
}
- /**
- * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
- *
- * @param writer XML Stream writer
- * @param data data node
- * @param schema corresponding schema node, may be null
- * @throws XMLStreamException if an encoding problem occurs
- */
- public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
- // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
- // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
-
- writer.writeStartDocument();
- writeElement(writer, data, schema);
- writer.writeEndDocument();
- writer.flush();
- }
-
- /**
- * Short-hand for {@link #writeDocument(XMLStreamWriter, CompositeNode, SchemaNode)})} with
- * null SchemaNode.
- *
- * @param writer XML Stream writer
- * @param data data node
- * @throws XMLStreamException if an encoding problem occurs
- */
- public void writeDocument(final XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
- writeDocument(writer, data, null);
- }
-
- /**
- * Write an element into a XML stream writer. This includes the element start/end tags and
- * the value of the element.
- *
- * @param writer XML Stream writer
- * @param data data node
- * @param schema Schema node
- * @throws XMLStreamException if an encoding problem occurs
- */
- public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
- final QName qname = data.getNodeType();
- final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
- final String pfx = "";
-
- if (isEmptyElement(data)) {
- if (hasAttributes(data)) {
- writer.writeStartElement(pfx, qname.getLocalName(), ns);
- final RandomPrefix randomPrefix = new RandomPrefix();
- writeAttributes(writer, (AttributesContainer) data, randomPrefix);
- writer.writeEndElement();
- } else {
- writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
- }
- return;
- }
-
- writer.writeStartElement(pfx, qname.getLocalName(), ns);
- writeValue(writer, data, schema);
- writer.writeEndElement();
- }
-
- /**
- * Write a value into a XML stream writer. This method assumes the start and end of element is
- * emitted by the caller.
- *
- * @param writer XML Stream writer
- * @param data data node
- * @param schema Schema node
- * @throws XMLStreamException if an encoding problem occurs
- */
- public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
- if (hasAttributes(data)) {
- RandomPrefix randomPrefix = new RandomPrefix();
- writeAttributes(writer, (AttributesContainer) data, randomPrefix);
- }
-
- if (data instanceof SimpleNode<?>) {
- // Simple node
- if (schema instanceof LeafListSchemaNode || schema instanceof LeafSchemaNode) {
- writeValue(writer, schema, data.getValue());
- } else {
- Object value = data.getValue();
- if (value != null) {
- writer.writeCharacters(String.valueOf(value));
- }
- }
- } else {
- // CompositeNode
- final CompositeNode castedData = ((CompositeNode) data);
- final DataNodeContainer castedSchema;
- if (schema instanceof DataNodeContainer) {
- castedSchema = (DataNodeContainer) schema;
- } else {
- castedSchema = null;
- }
- final Collection<QName> keyLeaves;
- if (schema instanceof ListSchemaNode) {
- keyLeaves = ((ListSchemaNode) schema).getKeyDefinition();
-
- } else {
- keyLeaves = Collections.emptyList();
-
- }
- for (QName key : keyLeaves) {
- SimpleNode<?> keyLeaf = castedData.getFirstSimpleByName(key);
- if(keyLeaf != null) {
- writeChildElement(writer,keyLeaf,castedSchema);
- }
- }
-
- for (Node<?> child : castedData.getValue()) {
- if(keyLeaves.contains(child.getNodeType())) {
- // Skip key leaf which was written by previous for loop.
- continue;
- }
- writeChildElement(writer,child,castedSchema);
- }
- }
- }
-
- private void writeChildElement(final XMLStreamWriter writer, final Node<?> child, final DataNodeContainer parentSchema) throws XMLStreamException {
- DataSchemaNode childSchema = null;
- if (parentSchema != null) {
- childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), parentSchema.getChildNodes()).orNull();
- if ((childSchema == null) && LOG.isDebugEnabled()) {
- LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
- }
- }
- writeElement(writer, child, childSchema);
- }
-
- private static void writeAttributes(final XMLStreamWriter writer, final AttributesContainer data, final RandomPrefix randomPrefix) throws XMLStreamException {
- for (Entry<QName, String> attribute : data.getAttributes().entrySet()) {
- writeAttribute(writer, attribute, randomPrefix);
- }
- }
-
- private static boolean hasAttributes(final Node<?> data) {
- if (data instanceof AttributesContainer) {
- final Map<QName, String> c = ((AttributesContainer) data).getAttributes();
- return c != null && !c.isEmpty();
- } else {
- return false;
- }
- }
-
@VisibleForTesting
static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
throws XMLStreamException {
}
}
- private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
+ private void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
if (value instanceof YangInstanceIdentifier) {
- write(writer, (YangInstanceIdentifier)value);
+ writeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
} else {
LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
writer.writeCharacters(String.valueOf(value));
}
}
+ public void writeInstanceIdentifier(XMLStreamWriter writer, YangInstanceIdentifier value) throws XMLStreamException {
+ if(schemaContext.isPresent()) {
+ RandomPrefixInstanceIdentifierSerializer iiCodec = new RandomPrefixInstanceIdentifierSerializer(schemaContext.get());
+ String serializedValue = iiCodec.serialize(value);
+ writeNamespaceDeclarations(writer,iiCodec.getPrefixes());
+ writer.writeCharacters(serializedValue);
+ } else {
+ LOG.warn("Schema context not present in {}, serializing {} without schema.",this,value);
+ write(writer,value);
+ }
+ }
+
+ private static void writeNamespaceDeclarations(XMLStreamWriter writer, Iterable<Entry<URI, String>> prefixes) throws XMLStreamException {
+ for (Entry<URI, String> e: prefixes) {
+ final String ns = e.getKey().toString();
+ final String p = e.getValue();
+ writer.writeNamespace(p, ns);
+ }
+ }
+
public static XmlStreamUtils create(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
return new XmlStreamUtils(codecProvider, schemaContext);
}
package org.opendaylight.yangtools.yang.data.impl.codec.xml;
import java.util.Map;
-
import javax.annotation.Nonnull;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
return superType;
}
+ /**
+ *
+ * @deprecated Use {@link RandomPrefixInstanceIdentifierSerializer} instead.
+ */
+ @Deprecated
static String encodeIdentifier(final RandomPrefix prefixes, final YangInstanceIdentifier id) {
StringBuilder textContent = new StringBuilder();
for (PathArgument pathArgument : id.getPathArguments()) {
*/
package org.opendaylight.yangtools.yang.data.impl.schema;
-import org.opendaylight.yangtools.yang.data.api.Node;
+import javax.xml.transform.dom.DOMSource;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
return ImmutableLeafSetEntryNodeSchemaAwareBuilder.create(schema);
}
- public static <T> NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> anyXmlBuilder() {
+ public static <T> NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder() {
return ImmutableAnyXmlNodeBuilder.create();
}
- public static <T> NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> anyXmlBuilder(
+ public static <T> NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder(
final AnyXmlSchemaNode schema) {
return ImmutableAnyXmlNodeSchemaAwareBuilder.create(schema);
}
return ImmutableChoiceNodeBuilder.create();
}
- public static DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> choiceBuilder(final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
+ public static DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> choiceBuilder(final ChoiceSchemaNode schema) {
return ImmutableChoiceNodeSchemaAwareBuilder.create(schema);
}
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableChoiceNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
return ImmutableMapEntryNodeBuilder.create();
}
- public static NormalizedNode<?, ?> containerNode(final QName name) {
+ public static ContainerNode containerNode(final QName name) {
return ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(name)).build();
}
+ public static ChoiceNode choiceNode(final QName name) {
+ return ImmutableChoiceNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(name)).build();
+ }
}
package org.opendaylight.yangtools.yang.data.impl.schema;
import com.google.common.base.Preconditions;
-import java.io.IOException;
import java.util.ArrayDeque;
+import java.util.Collection;
import java.util.Deque;
-import java.util.List;
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;
}
@Override
- public NormalizedNodeContainerBuilder withValue(final List value) {
+ public NormalizedNodeContainerBuilder withValue(final Collection value) {
throw new UnsupportedOperationException();
}
}
@Override
- public void close() throws IOException {
- // TODO Auto-generated method stub
-
+ public void close() {
+ // no-op
}
-
}
*/
package org.opendaylight.yangtools.yang.data.impl.schema;
-
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
for (DataSchemaNode dsn : dataSchemaNode) {
if (qname.isEqualWithoutRevision(dsn.getQName())) {
return Optional.<DataSchemaNode> of(dsn);
- } else if (dsn instanceof ChoiceNode) {
- for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
+ } else if (dsn instanceof ChoiceSchemaNode) {
+ for (ChoiceCaseNode choiceCase : ((ChoiceSchemaNode) dsn).getCases()) {
Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
if (foundDsn != null && foundDsn.isPresent()) {
return foundDsn;
return schemaForAugment.get();
}
- public static AugmentationSchema findSchemaForAugment(final ChoiceNode schema, final Set<QName> qNames) {
+ public static AugmentationSchema findSchemaForAugment(final ChoiceSchemaNode schema, final Set<QName> qNames) {
Optional<AugmentationSchema> schemaForAugment = Optional.absent();
for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
return Optional.absent();
}
- public static DataSchemaNode findSchemaForChild(final ChoiceNode schema, final QName childPartialQName) {
+ public static DataSchemaNode findSchemaForChild(final ChoiceSchemaNode schema, final QName childPartialQName) {
for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
Optional<DataSchemaNode> childSchema = findFirstSchema(childPartialQName, choiceCaseNode.getChildNodes());
if (childSchema.isPresent()) {
*
* @return Map with all child nodes, to their most top augmentation
*/
- public static Map<QName, ChoiceNode> mapChildElementsFromChoices(final DataNodeContainer schema) {
+ public static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema) {
return mapChildElementsFromChoices(schema, schema.getChildNodes());
}
- private static Map<QName, ChoiceNode> mapChildElementsFromChoices(final DataNodeContainer schema, final Iterable<DataSchemaNode> childNodes) {
- Map<QName, ChoiceNode> mappedChoices = Maps.newLinkedHashMap();
+ private static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema, final Iterable<DataSchemaNode> childNodes) {
+ Map<QName, ChoiceSchemaNode> mappedChoices = Maps.newLinkedHashMap();
for (final DataSchemaNode childSchema : childNodes) {
- if(childSchema instanceof ChoiceNode) {
+ if (childSchema instanceof ChoiceSchemaNode) {
- if(isFromAugment(schema, childSchema)) {
+ if (isFromAugment(schema, childSchema)) {
continue;
}
- for (ChoiceCaseNode choiceCaseNode : ((ChoiceNode) childSchema).getCases()) {
+ for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
for (QName qName : getChildNodesRecursive(choiceCaseNode)) {
- mappedChoices.put(qName, (ChoiceNode) childSchema);
+ mappedChoices.put(qName, (ChoiceSchemaNode) childSchema);
}
}
}
for (QName qName : getChildNodesRecursive((DataNodeContainer) child)) {
childNodesToAugmentation.put(qName, mostTopAugmentation);
}
- } else if (child instanceof ChoiceNode) {
- for (ChoiceCaseNode choiceCaseNode : ((ChoiceNode) child).getCases()) {
+ } else if (child instanceof ChoiceSchemaNode) {
+ for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) child).getCases()) {
for (QName qName : getChildNodesRecursive(choiceCaseNode)) {
childNodesToAugmentation.put(qName, mostTopAugmentation);
}
}
// Choice Node has to map child nodes from all its cases
- if (schema instanceof ChoiceNode) {
- for (ChoiceCaseNode choiceCaseNode : ((ChoiceNode) schema).getCases()) {
+ if (schema instanceof ChoiceSchemaNode) {
+ for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) schema).getCases()) {
if (!(augments.containsKey(choiceCaseNode.getQName()))) {
continue;
}
Set<QName> allChildNodes = Sets.newHashSet();
for (DataSchemaNode childSchema : nodeContainer.getChildNodes()) {
- if(childSchema instanceof ChoiceNode) {
- for (ChoiceCaseNode choiceCaseNode : ((ChoiceNode) childSchema).getCases()) {
+ if(childSchema instanceof ChoiceSchemaNode) {
+ for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
allChildNodes.addAll(getChildNodesRecursive(choiceCaseNode));
}
} else if(childSchema instanceof AugmentationSchema || childSchema instanceof ChoiceCaseNode) {
if(targetSchema instanceof DataNodeContainer) {
realChildNodes = getRealSchemasForAugment((DataNodeContainer)targetSchema, augmentSchema);
- } else if(targetSchema instanceof ChoiceNode) {
+ } else if(targetSchema instanceof ChoiceSchemaNode) {
for (DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
- for (ChoiceCaseNode choiceCaseNode : ((ChoiceNode) targetSchema).getCases()) {
+ for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) targetSchema).getCases()) {
if(getChildNodesRecursive(choiceCaseNode).contains(dataSchemaNode.getQName())) {
realChildNodes.add(choiceCaseNode.getDataChildByName(dataSchemaNode.getQName()));
}
return realChildNodes;
}
- public static Optional<ChoiceCaseNode> detectCase(final ChoiceNode schema, final DataContainerChild<?, ?> child) {
+ public static Optional<ChoiceCaseNode> detectCase(final ChoiceSchemaNode schema, final DataContainerChild<?, ?> child) {
for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
if (child instanceof AugmentationNode
&& belongsToCaseAugment(choiceCaseNode,
*/
package org.opendaylight.yangtools.yang.data.impl.schema.builder.api;
-import java.util.List;
-
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
extends NormalizedNodeContainerBuilder<NodeIdentifier,PathArgument, V, R> {
@Override
- CollectionNodeBuilder<V, R> withValue(List<V> value);
+ CollectionNodeBuilder<V, R> withValue(Collection<V> value);
@Override
CollectionNodeBuilder<V, R> withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier nodeIdentifier);
*/
package org.opendaylight.yangtools.yang.data.impl.schema.builder.api;
-import java.util.List;
-
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
AttributesBuilder<DataContainerNodeAttrBuilder<I, R>> {
@Override
- DataContainerNodeAttrBuilder<I, R> withValue(List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value);
+ DataContainerNodeAttrBuilder<I, R> withValue(Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value);
@Override
DataContainerNodeAttrBuilder<I, R> withNodeIdentifier(I nodeIdentifier);
+ @Override
DataContainerNodeAttrBuilder<I, R> withChild(DataContainerChild<?, ?> child);
}
*/
package org.opendaylight.yangtools.yang.data.impl.schema.builder.api;
-import java.util.List;
-
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
extends NormalizedNodeContainerBuilder<I, PathArgument, DataContainerChild<? extends PathArgument, ?>, R> {
@Override
- DataContainerNodeBuilder<I, R> withValue(List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value);
+ DataContainerNodeBuilder<I, R> withValue(Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value);
@Override
DataContainerNodeBuilder<I, R> withNodeIdentifier(I nodeIdentifier);
*/
package org.opendaylight.yangtools.yang.data.impl.schema.builder.api;
-import java.util.List;
+import java.util.Collection;
import java.util.Map;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
ListNodeBuilder<T, V> withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier nodeIdentifier);
@Override
- ListNodeBuilder<T, V> withValue(List<LeafSetEntryNode<T>> value);
+ ListNodeBuilder<T, V> withValue(Collection<LeafSetEntryNode<T>> value);
@Override
ListNodeBuilder<T, V> withChild(LeafSetEntryNode<T> child);
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
package org.opendaylight.yangtools.yang.data.impl.schema.builder.api;
-import java.util.List;
-
+import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-public interface NormalizedNodeContainerBuilder<K extends PathArgument,CK extends PathArgument,CV extends NormalizedNode<? extends CK, ?>,P extends NormalizedNode<K, ?>>
-extends NormalizedNodeBuilder<K,List<CV>,P>{
+public interface NormalizedNodeContainerBuilder<K extends PathArgument,CK extends PathArgument,CV extends NormalizedNode<? extends CK, ?>,P extends NormalizedNode<K, ?>> extends NormalizedNodeBuilder<K,Collection<CV>,P>{
@Override
NormalizedNodeContainerBuilder<K,CK,CV,P> withNodeIdentifier(K nodeIdentifier);
@Override
- NormalizedNodeContainerBuilder<K,CK,CV,P> withValue(List<CV> value);
+ NormalizedNodeContainerBuilder<K,CK,CV,P> withValue(Collection<CV> value);
NormalizedNodeContainerBuilder<K,CK,CV,P> addChild(CV child);
NormalizedNodeContainerBuilder<K,CK,CV,P> removeChild(CK key);
*/
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
+import java.util.Collection;
import java.util.Collections;
-import java.util.List;
import java.util.Map;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
}
@Override
- public DataContainerNodeAttrBuilder<I, R> withValue(final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
+ public DataContainerNodeAttrBuilder<I, R> withValue(final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
return (DataContainerNodeAttrBuilder<I, R>) super.withValue(value);
}
*/
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
+import java.util.Collection;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
}
@Override
- public DataContainerNodeBuilder<I, R> withValue(final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
+ public DataContainerNodeBuilder<I, R> withValue(final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
// TODO Replace or putAll ?
for (final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild : value) {
withChild(dataContainerChild);
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
import java.util.Map;
+import javax.xml.transform.dom.DOMSource;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedValueAttrNode;
-public class ImmutableAnyXmlNodeBuilder extends AbstractImmutableNormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> {
+public class ImmutableAnyXmlNodeBuilder extends AbstractImmutableNormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> {
- public static NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> create() {
+ public static NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> create() {
return new ImmutableAnyXmlNodeBuilder();
}
return new ImmutableXmlNode(getNodeIdentifier(), getValue(), getAttributes());
}
- private static final class ImmutableXmlNode extends AbstractImmutableNormalizedValueAttrNode<YangInstanceIdentifier.NodeIdentifier, Node<?>> implements AnyXmlNode {
+ private static final class ImmutableXmlNode extends AbstractImmutableNormalizedValueAttrNode<YangInstanceIdentifier.NodeIdentifier, DOMSource> implements AnyXmlNode {
- ImmutableXmlNode(final YangInstanceIdentifier.NodeIdentifier nodeIdentifier, final Node<?> value, final Map<QName, String> attributes) {
+ ImmutableXmlNode(final YangInstanceIdentifier.NodeIdentifier nodeIdentifier, final DOMSource value, final Map<QName, String> attributes) {
super(nodeIdentifier, value, attributes);
}
}
*/
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
+import javax.xml.transform.dom.DOMSource;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
super.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(schema.getQName()));
}
- public static NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> create(AnyXmlSchemaNode schema) {
+ public static NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> create(AnyXmlSchemaNode schema) {
return new ImmutableAnyXmlNodeSchemaAwareBuilder(schema);
}
@Override
- public NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> withValue(Node<?> value) {
+ public NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> withValue(DOMSource value) {
return super.withValue(value);
}
@Override
- public NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier nodeIdentifier) {
+ public NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier nodeIdentifier) {
throw new UnsupportedOperationException("Node identifier created from schema");
}
}
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.valid.DataNodeContainerValidator;
-import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.valid.DataValidationException;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-
-import com.google.common.base.Preconditions;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
public class ImmutableChoiceNodeSchemaAwareBuilder extends ImmutableChoiceNodeBuilder {
- private final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema;
+ private final ChoiceSchemaNode schema;
private DataNodeContainerValidator validator;
- protected ImmutableChoiceNodeSchemaAwareBuilder(org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
+ protected ImmutableChoiceNodeSchemaAwareBuilder(final ChoiceSchemaNode schema) {
this.schema = Preconditions.checkNotNull(schema, "Schema was null");
super.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(schema.getQName()));
}
@Override
- public DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier nodeIdentifier) {
+ public DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> withNodeIdentifier(final YangInstanceIdentifier.NodeIdentifier nodeIdentifier) {
throw new UnsupportedOperationException("Node identifier created from schema");
}
return super.build();
}
- public static DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> create(org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
+ public static DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> create(final ChoiceSchemaNode schema) {
return new ImmutableChoiceNodeSchemaAwareBuilder(schema);
}
}
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
import com.google.common.base.Optional;
-import com.google.common.collect.Iterables;
+import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.util.MapAdaptor;
+import org.opendaylight.yangtools.util.UnmodifiableCollection;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
}
@Override
- public ListNodeBuilder<T, LeafSetEntryNode<T>> withValue(final List<LeafSetEntryNode<T>> value) {
+ public ListNodeBuilder<T, LeafSetEntryNode<T>> withValue(final Collection<LeafSetEntryNode<T>> value) {
for (final LeafSetEntryNode<T> leafSetEntry : value) {
withChild(leafSetEntry);
}
}
protected final static class ImmutableLeafSetNode<T> extends
- AbstractImmutableNormalizedValueNode<YangInstanceIdentifier.NodeIdentifier, Iterable<LeafSetEntryNode<T>>> implements
+ AbstractImmutableNormalizedValueNode<YangInstanceIdentifier.NodeIdentifier, Collection<LeafSetEntryNode<T>>> implements
Immutable, LeafSetNode<T> {
private final Map<YangInstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> children;
ImmutableLeafSetNode(final YangInstanceIdentifier.NodeIdentifier nodeIdentifier,
final Map<YangInstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> children) {
- super(nodeIdentifier, Iterables.unmodifiableIterable(children.values()));
+ super(nodeIdentifier, UnmodifiableCollection.create(children.values()));
this.children = children;
}
*/
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
+import java.util.Collection;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Map;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
@Override
- public DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> withValue(final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
+ public DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> withValue(final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
fillQnames(value, childrenQNamesToPaths);
return super.withValue(value);
}
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
import com.google.common.base.Optional;
-import com.google.common.collect.Iterables;
+import java.util.Collection;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.util.MapAdaptor;
+import org.opendaylight.yangtools.util.UnmodifiableCollection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
}
@Override
- public CollectionNodeBuilder<MapEntryNode, MapNode> withValue(final List<MapEntryNode> value) {
+ public CollectionNodeBuilder<MapEntryNode, MapNode> withValue(final Collection<MapEntryNode> value) {
// TODO replace or putAll ?
for (final MapEntryNode mapEntryNode : value) {
withChild(mapEntryNode);
return withoutChild(key);
}
- protected static final class ImmutableMapNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Iterable<MapEntryNode>> implements Immutable,MapNode {
+ protected static final class ImmutableMapNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Collection<MapEntryNode>> implements Immutable,MapNode {
private final Map<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> children;
}
@Override
- public Iterable<MapEntryNode> getValue() {
- return Iterables.unmodifiableIterable(children.values());
+ public Collection<MapEntryNode> getValue() {
+ return UnmodifiableCollection.create(children.values());
}
@Override
*/
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
+import com.google.common.base.Optional;
+import com.google.common.collect.Iterables;
+import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Map;
-
import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.util.UnmodifiableCollection;
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.impl.schema.builder.api.NormalizedNodeContainerBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedNode;
-import com.google.common.base.Optional;
-import com.google.common.collect.Iterables;
-
public class ImmutableOrderedLeafSetNodeBuilder<T> implements ListNodeBuilder<T, LeafSetEntryNode<T>> {
private Map<YangInstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> value;
}
@Override
- public ListNodeBuilder<T, LeafSetEntryNode<T>> withValue(final List<LeafSetEntryNode<T>> value) {
+ public ListNodeBuilder<T, LeafSetEntryNode<T>> withValue(final Collection<LeafSetEntryNode<T>> value) {
checkDirty();
for (final LeafSetEntryNode<T> leafSetEntry : value) {
withChild(leafSetEntry);
return this;
}
-
@Override
public ListNodeBuilder<T, LeafSetEntryNode<T>> withChildValue(final T value, final Map<QName, String> attributes) {
final ImmutableLeafSetEntryNodeBuilder<T> b = ImmutableLeafSetEntryNodeBuilder.create();
return withChildValue(value, Collections.<QName,String>emptyMap());
}
- protected final static class ImmutableOrderedLeafSetNode<T> extends
- AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Iterable<LeafSetEntryNode<T>>> implements
+ protected static final class ImmutableOrderedLeafSetNode<T> extends
+ AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Collection<LeafSetEntryNode<T>>> implements
Immutable, OrderedLeafSetNode<T> {
private final Map<YangInstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> children;
@Override
public LeafSetEntryNode<T> getChild(final int position) {
- return Iterables.get(getValue(), position);
+ return Iterables.get(children.values(), position);
}
@Override
public int getSize() {
- // TODO Auto-generated method stub
- return 0;
+ return children.size();
}
- @Override
- public Iterable<LeafSetEntryNode<T>> getValue() {
- return Iterables.unmodifiableIterable(children.values());
- }
+ @Override
+ public Collection<LeafSetEntryNode<T>> getValue() {
+ return UnmodifiableCollection.create(children.values());
+ }
}
@Override
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
+import java.util.Collection;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Map;
import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.util.UnmodifiableCollection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
}
@Override
- public CollectionNodeBuilder<MapEntryNode, OrderedMapNode> withValue(final List<MapEntryNode> value) {
+ public CollectionNodeBuilder<MapEntryNode, OrderedMapNode> withValue(final Collection<MapEntryNode> value) {
// TODO replace or putAll ?
for (final MapEntryNode mapEntryNode : value) {
withChild(mapEntryNode);
return withoutChild(key);
}
- protected static final class ImmutableOrderedMapNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Iterable<MapEntryNode>> implements Immutable,OrderedMapNode {
+ protected static final class ImmutableOrderedMapNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Collection<MapEntryNode>> implements Immutable,OrderedMapNode {
private final Map<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> children;
@Override
public MapEntryNode getChild(final int position) {
- return Iterables.get(getValue(), position);
+ return Iterables.get(children.values(), position);
}
@Override
}
@Override
- public Iterable<MapEntryNode> getValue() {
- return Iterables.unmodifiableIterable(children.values());
+ public Collection<MapEntryNode> getValue() {
+ return UnmodifiableCollection.create(children.values());
}
}
}
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
+import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
}
@Override
- public CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> withValue(final List<UnkeyedListEntryNode> value) {
+ public CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> withValue(final Collection<UnkeyedListEntryNode> value) {
// TODO replace or putAll ?
for (final UnkeyedListEntryNode UnkeyedListEntryNode : value) {
withChild(UnkeyedListEntryNode);
return withoutChild(key);
}
- protected static final class EmptyImmutableUnkeyedListNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Iterable<UnkeyedListEntryNode>> implements Immutable, UnkeyedListNode {
+ protected static final class EmptyImmutableUnkeyedListNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Collection<UnkeyedListEntryNode>> implements Immutable, UnkeyedListNode {
protected EmptyImmutableUnkeyedListNode(final NodeIdentifier nodeIdentifier) {
super(nodeIdentifier);
}
@Override
- public Iterable<UnkeyedListEntryNode> getValue() {
- return Collections.emptyList();
+ public Collection<UnkeyedListEntryNode> getValue() {
+ return Collections.emptySet();
}
@Override
public UnkeyedListEntryNode getChild(final int position) {
- return null;
+ throw new IndexOutOfBoundsException();
}
@Override
}
protected static final class ImmutableUnkeyedListNode extends
- AbstractImmutableNormalizedValueNode<YangInstanceIdentifier.NodeIdentifier, Iterable<UnkeyedListEntryNode>>
+ AbstractImmutableNormalizedValueNode<YangInstanceIdentifier.NodeIdentifier, Collection<UnkeyedListEntryNode>>
implements Immutable, UnkeyedListNode {
private final ImmutableList<UnkeyedListEntryNode> children;
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.valid;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
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.schema.DataContainerChild;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
}
}
- public static void checkLegalChild(final boolean isLegal, final YangInstanceIdentifier.PathArgument child, final ChoiceNode schema) {
+ public static void checkLegalChild(final boolean isLegal, final YangInstanceIdentifier.PathArgument child, final ChoiceSchemaNode schema) {
if (!isLegal) {
throw new IllegalChildException(child, schema);
}
}
public static void checkListKey(final DataContainerChild<?, ?> childNode, final Map<QName, Object> keyValues, final QName keyQName,
- final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeId) {
+ final NodeIdentifierWithPredicates nodeId) {
checkListKey(childNode, keyQName, nodeId);
- Object expectedValue = nodeId.getKeyValues().get(keyQName);
- Object actualValue = childNode.getValue();
+ final Object expected = nodeId.getKeyValues().get(keyQName);
+ final Object actual = childNode.getValue();
+
+ // Objects.equals() does not deal with arrays, but is faster
+ if (!Objects.equals(expected, actual) && !Objects.deepEquals(expected, actual)) {
+ throw new IllegalListKeyException(keyQName, nodeId, actual, expected);
+ }
}
- public static void checkListKey(final DataContainerChild<?, ?> childNode, final QName keyQName, final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeId) {
+ public static void checkListKey(final DataContainerChild<?, ?> childNode, final QName keyQName, final NodeIdentifierWithPredicates nodeId) {
if (childNode == null) {
throw new IllegalListKeyException(keyQName, nodeId);
}
}
- static final class IllegalChildException extends DataValidationException {
+ private static final class IllegalChildException extends DataValidationException {
private static final long serialVersionUID = 1L;
- public IllegalChildException(final YangInstanceIdentifier.PathArgument child, final DataNodeContainer schema,
+ private IllegalChildException(final YangInstanceIdentifier.PathArgument child, final DataNodeContainer schema,
final Set<QName> childNodes, final Set<YangInstanceIdentifier.AugmentationIdentifier> augments) {
super(String.format("Unknown child node: %s, does not belong to: %s as a direct child. "
+ "Direct child nodes: %s, augmented child nodes: %s", child, schema, childNodes, augments));
}
- public IllegalChildException(final YangInstanceIdentifier.PathArgument child, final ChoiceNode schema) {
+ private IllegalChildException(final YangInstanceIdentifier.PathArgument child, final ChoiceSchemaNode schema) {
super(String.format("Unknown child node: %s, not detected in choice: %s", child, schema));
}
- public IllegalChildException(final YangInstanceIdentifier.PathArgument child, final DataSchemaNode schema, final Set<QName> childNodes) {
+ private IllegalChildException(final YangInstanceIdentifier.PathArgument child, final DataSchemaNode schema, final Set<QName> childNodes) {
super(String.format("Unknown child node: %s, does not belong to: %s as a child. "
+ "Child nodes: %s", child, schema, childNodes));
}
}
- static final class IllegalListKeyException extends DataValidationException {
+ private static final class IllegalListKeyException extends DataValidationException {
private static final long serialVersionUID = 1L;
- public IllegalListKeyException(final QName keyQName, final YangInstanceIdentifier.NodeIdentifierWithPredicates id) {
+ private IllegalListKeyException(final QName keyQName, final NodeIdentifierWithPredicates id) {
super(String.format("Key value not present for key: %s, in: %s", keyQName, id));
}
- public IllegalListKeyException(final QName keyQName, final YangInstanceIdentifier.NodeIdentifierWithPredicates id, final Object actualValue, final Object expectedValue) {
+ private IllegalListKeyException(final QName keyQName, final NodeIdentifierWithPredicates id, final Object actualValue, final Object expectedValue) {
super(String.format("Illegal value for key: %s, in: %s, actual value: %s, expected value from key: %s", keyQName, id, actualValue, expectedValue));
}
}
package org.opendaylight.yangtools.yang.data.impl.schema.nodes;
import com.google.common.base.Optional;
+import java.util.Collection;
import java.util.Map;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
-public abstract class AbstractImmutableDataContainerNode<K extends PathArgument> extends AbstractImmutableNormalizedNode<K, Iterable<DataContainerChild<? extends PathArgument, ?>>> implements Immutable, DataContainerNode<K> {
+public abstract class AbstractImmutableDataContainerNode<K extends PathArgument> extends AbstractImmutableNormalizedNode<K, Collection<DataContainerChild<? extends PathArgument, ?>>> implements Immutable, DataContainerNode<K> {
private final Map<PathArgument, DataContainerChild<? extends PathArgument, ?>> children;
public AbstractImmutableDataContainerNode(
}
@Override
- public final Iterable<DataContainerChild<? extends PathArgument, ?>> getValue() {
+ public final Collection<DataContainerChild<? extends PathArgument, ?>> getValue() {
return children.values();
}
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
* type of resulting/serialized element from NormalizedNode
*/
public interface FromNormalizedNodeSerializerFactory<E> {
- FromNormalizedNodeSerializer<E, AugmentationNode, AugmentationSchema> getAugmentationNodeSerializer();
- FromNormalizedNodeSerializer<E, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeSerializer();
- FromNormalizedNodeSerializer<E, ContainerNode, ContainerSchemaNode> getContainerNodeSerializer();
- FromNormalizedNodeSerializer<E, LeafNode<?>, LeafSchemaNode> getLeafNodeSerializer();
- FromNormalizedNodeSerializer<E, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer();
- FromNormalizedNodeSerializer<E, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeSerializer();
- FromNormalizedNodeSerializer<E, MapEntryNode, ListSchemaNode> getMapEntryNodeSerializer();
- FromNormalizedNodeSerializer<E, MapNode, ListSchemaNode> getMapNodeSerializer();
- FromNormalizedNodeSerializer<E, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeSerializer();
+ FromNormalizedNodeSerializer<E, AugmentationNode, AugmentationSchema> getAugmentationNodeSerializer();
+ FromNormalizedNodeSerializer<E, ChoiceNode, ChoiceSchemaNode> getChoiceNodeSerializer();
+ FromNormalizedNodeSerializer<E, ContainerNode, ContainerSchemaNode> getContainerNodeSerializer();
+ FromNormalizedNodeSerializer<E, LeafNode<?>, LeafSchemaNode> getLeafNodeSerializer();
+ FromNormalizedNodeSerializer<E, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer();
+ FromNormalizedNodeSerializer<E, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeSerializer();
+ FromNormalizedNodeSerializer<E, MapEntryNode, ListSchemaNode> getMapEntryNodeSerializer();
+ FromNormalizedNodeSerializer<E, MapNode, ListSchemaNode> getMapNodeSerializer();
+ FromNormalizedNodeSerializer<E, UnkeyedListNode, ListSchemaNode> getUnkeyedListNodeSerializer();
+ FromNormalizedNodeSerializer<E, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeSerializer();
}
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
* type of element to be parsed into NormalizedNode
*/
public interface ToNormalizedNodeParserFactory<E> {
- ToNormalizedNodeParser<E, AugmentationNode, AugmentationSchema> getAugmentationNodeParser();
- ToNormalizedNodeParser<E, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeParser();
- ToNormalizedNodeParser<E, ContainerNode, ContainerSchemaNode> getContainerNodeParser();
- ToNormalizedNodeParser<E, LeafNode<?>, LeafSchemaNode> getLeafNodeParser();
- ToNormalizedNodeParser<E, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeParser();
- ToNormalizedNodeParser<E, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeParser();
- ToNormalizedNodeParser<E, MapEntryNode, ListSchemaNode> getMapEntryNodeParser();
- ToNormalizedNodeParser<E, MapNode, ListSchemaNode> getMapNodeParser();
- ToNormalizedNodeParser<E, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeParser();
+ ToNormalizedNodeParser<E, AugmentationNode, AugmentationSchema> getAugmentationNodeParser();
+ ToNormalizedNodeParser<E, ChoiceNode, ChoiceSchemaNode> getChoiceNodeParser();
+ ToNormalizedNodeParser<E, ContainerNode, ContainerSchemaNode> getContainerNodeParser();
+ ToNormalizedNodeParser<E, LeafNode<?>, LeafSchemaNode> getLeafNodeParser();
+ ToNormalizedNodeParser<E, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeParser();
+ ToNormalizedNodeParser<E, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeParser();
+ ToNormalizedNodeParser<E, MapEntryNode, ListSchemaNode> getMapEntryNodeParser();
+ ToNormalizedNodeParser<E, MapNode, ListSchemaNode> getMapNodeParser();
+ ToNormalizedNodeParser<E, UnkeyedListNode, ListSchemaNode> getUnkeyedListNodeParser();
+ ToNormalizedNodeParser<E, UnkeyedListEntryNode, ListSchemaNode> getUnkeyedListEntryNodeParser();
+ ToNormalizedNodeParser<E, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeParser();
+ ToNormalizedNodeParser<E, OrderedMapNode, ListSchemaNode> getOrderedListNodeParser();
}
*/
package org.opendaylight.yangtools.yang.data.impl.schema.transform.base;
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableMap;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
import java.util.Set;
-
-import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
-import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.api.Status;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.UsesNode;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
/**
* Proxy for AugmentationSchema. Child node schemas are replaced with actual schemas from parent.
+ *
+ * @deprecated Replaced with {@link EffectiveAugmentationSchema}.
*/
-public final class AugmentationSchemaProxy implements AugmentationSchema {
- private final AugmentationSchema delegate;
- private final Set<DataSchemaNode> realChildSchemas;
- private final Map<QName, DataSchemaNode> mappedChildSchemas;
-
- public AugmentationSchemaProxy(final AugmentationSchema augmentSchema, final Set<DataSchemaNode> realChildSchemas) {
- this.delegate = augmentSchema;
- this.realChildSchemas = realChildSchemas;
-
- final Map<QName, DataSchemaNode> m = new HashMap<>(realChildSchemas.size());
- for (DataSchemaNode realChildSchema : realChildSchemas) {
- m.put(realChildSchema.getQName(), realChildSchema);
- }
-
- this.mappedChildSchemas = ImmutableMap.copyOf(m);
- }
+@Deprecated
+public final class AugmentationSchemaProxy extends EffectiveAugmentationSchema {
- @Override
- public RevisionAwareXPath getWhenCondition() {
- return delegate.getWhenCondition();
- }
-
- @Override
- public String getDescription() {
- return delegate.getDescription();
- }
-
- @Override
- public String getReference() {
- return delegate.getReference();
- }
-
- @Override
- public Status getStatus() {
- return delegate.getStatus();
- }
- @Override
- public SchemaPath getTargetPath() {
- return delegate.getTargetPath();
- }
-
- @Override
- public List<UnknownSchemaNode> getUnknownSchemaNodes() {
- return delegate.getUnknownSchemaNodes();
- }
-
- @Override
- public Set<TypeDefinition<?>> getTypeDefinitions() {
- return delegate.getTypeDefinitions();
- }
-
- @Override
- public Set<DataSchemaNode> getChildNodes() {
- return realChildSchemas;
- }
-
- @Override
- public Set<GroupingDefinition> getGroupings() {
- return delegate.getGroupings();
- }
-
- @Override
- public DataSchemaNode getDataChildByName(final QName name) {
- return mappedChildSchemas.get(name);
- }
-
- @Override
- public DataSchemaNode getDataChildByName(final String name) {
- // Unused
- throw new UnsupportedOperationException("Unable to retrieve child node by name");
- }
-
- @Override
- public Set<UsesNode> getUses() {
- return delegate.getUses();
+ public AugmentationSchemaProxy(final AugmentationSchema augmentSchema, final Set<DataSchemaNode> realChildSchemas) {
+ super(augmentSchema,realChildSchemas);
}
- @Override
- public Optional<AugmentationSchema> getOriginalDefinition() {
- return delegate.getOriginalDefinition();
- }
}
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
-import org.opendaylight.yangtools.yang.data.api.Node;
+import javax.xml.transform.dom.DOMSource;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
Preconditions.checkArgument(size == 1, "Elements mapped to any-xml node illegal count: %s", size);
final E e = elements.iterator().next();
- Node<?> value = parseAnyXml(e, schema);
+ DOMSource value = parseAnyXml(e, schema);
- NormalizedNodeAttrBuilder<NodeIdentifier, Node<?>, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder(schema);
+ NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder(schema);
return anyXmlBuilder.withValue(value).build();
}
* @param schema schema for leaf
* @return parsed element as an Object
*/
- protected abstract Node<?> parseAnyXml(E element, AnyXmlSchemaNode schema);
+ protected abstract DOMSource parseAnyXml(E element, AnyXmlSchemaNode schema);
}
import java.util.Collections;
import java.util.Map;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
/**
BaseDispatcherParser<E,AugmentationNode, AugmentationSchema> {
@Override
- protected final DataContainerNodeBuilder<YangInstanceIdentifier.AugmentationIdentifier, AugmentationNode> getBuilder(AugmentationSchema schema) {
+ protected final DataContainerNodeBuilder<YangInstanceIdentifier.AugmentationIdentifier, AugmentationNode> getBuilder(final AugmentationSchema schema) {
return Builders.augmentationBuilder(schema);
}
@Override
- protected final Set<DataSchemaNode> getRealSchemasForAugment(AugmentationSchema schema, AugmentationSchema augmentSchema) {
+ protected final Set<DataSchemaNode> getRealSchemasForAugment(final AugmentationSchema schema, final AugmentationSchema augmentSchema) {
return SchemaUtils.getRealSchemasForAugment(schema, augmentSchema);
}
@Override
- protected final DataSchemaNode getSchemaForChild(AugmentationSchema schema, QName childQName) {
+ protected final DataSchemaNode getSchemaForChild(final AugmentationSchema schema, final QName childQName) {
return SchemaUtils.findSchemaForChild(schema, childQName);
}
@Override
- protected final Map<QName, ChoiceNode> mapChildElementsFromChoices(AugmentationSchema schema) {
+ protected final Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final AugmentationSchema schema) {
return SchemaUtils.mapChildElementsFromChoices(schema);
}
@Override
- protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(AugmentationSchema schema) {
+ protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(final AugmentationSchema schema) {
return Collections.emptyMap();
}
}
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.AttributesBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
/**
* Abstract(base) Parser for DataContainerNodes e.g. ContainerNode, AugmentationNode.
* @return map from QName to ChoiceNode schema of child nodes that are
* contained within a choice statement under current schema.
*/
- protected abstract Map<QName, ChoiceNode> mapChildElementsFromChoices(S schema);
+ protected abstract Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(S schema);
/**
*
protected abstract NodeParserDispatcher<E> getDispatcher();
@Override
- public N parse(Iterable<E> elements, S schema) {
+ public N parse(final Iterable<E> elements, final S schema) {
checkAtLeastOneNode(schema, elements);
LinkedListMultimap<AugmentationSchema, E> augmentsToElements = LinkedListMultimap.create();
// Map child nodes from choices
- Map<QName, ChoiceNode> mappedChoiceChildNodes = mapChildElementsFromChoices(schema);
- LinkedListMultimap<ChoiceNode, E> choicesToElements = LinkedListMultimap.create();
+ Map<QName, ChoiceSchemaNode> mappedChoiceChildNodes = mapChildElementsFromChoices(schema);
+ LinkedListMultimap<ChoiceSchemaNode, E> choicesToElements = LinkedListMultimap.create();
// process Child nodes
for (QName childPartialQName : mappedChildElements.keySet()) {
augmentsToElements.putAll(augmentationSchema, childrenForQName);
// Choices
} else if (isMarkedAs(mappedChoiceChildNodes, childSchema.getQName())) {
- ChoiceNode choiceSchema = mappedChoiceChildNodes.get(childSchema.getQName());
+ ChoiceSchemaNode choiceSchema = mappedChoiceChildNodes.get(childSchema.getQName());
choicesToElements.putAll(choiceSchema, childrenForQName);
// Regular child nodes
} else {
}
// TODO ordering is not preserved for choice and augment elements
- for (ChoiceNode choiceSchema : choicesToElements.keySet()) {
+ for (ChoiceSchemaNode choiceSchema : choicesToElements.keySet()) {
containerBuilder.withChild(getDispatcher().dispatchChildElement(choiceSchema,
choicesToElements.get(choiceSchema)));
}
for (AugmentationSchema augmentSchema : augmentsToElements.keySet()) {
Set<DataSchemaNode> realChildSchemas = getRealSchemasForAugment(schema, augmentSchema);
- AugmentationSchemaProxy augSchemaProxy = new AugmentationSchemaProxy(augmentSchema, realChildSchemas);
+ EffectiveAugmentationSchema augSchemaProxy = new EffectiveAugmentationSchema(augmentSchema, realChildSchemas);
containerBuilder.withChild(getDispatcher().dispatchChildElement(augSchemaProxy, augmentsToElements.get(augmentSchema)));
}
return containerBuilder.build();
}
- protected Map<QName, String> getAttributes(E e) {
+ protected Map<QName, String> getAttributes(final E e) {
return Collections.emptyMap();
}
- private boolean isMarkedAs(Map<QName, ?> mappedAugmentChildNodes, QName qName) {
+ private boolean isMarkedAs(final Map<QName, ?> mappedAugmentChildNodes, final QName qName) {
return mappedAugmentChildNodes.containsKey(qName);
}
- protected void checkOnlyOneNode(S schema, Iterable<E> childNodes) {
+ protected void checkOnlyOneNode(final S schema, final Iterable<E> childNodes) {
final int size = Iterables.size(childNodes);
Preconditions.checkArgument(size == 1,
"Node detected multiple times, should be 1, identified by: %s, found: %s", schema, childNodes);
}
- private void checkAtLeastOneNode(S schema, Iterable<E> childNodes) {
+ private void checkAtLeastOneNode(final S schema, final Iterable<E> childNodes) {
Preconditions.checkArgument(!Iterables.isEmpty(childNodes),
"Node detected 0 times, should be at least 1, identified by: %s, found: %s", schema, childNodes);
}
*/
package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
+import com.google.common.collect.Sets;
+import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
/**
* Abstract(base) parser for ChoiceNodes, parses elements of type E.
*
* @param <E> type of elements to be parsed
*/
-public abstract class ChoiceNodeBaseParser<E> extends
- BaseDispatcherParser<E, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> {
+public abstract class ChoiceNodeBaseParser<E> extends BaseDispatcherParser<E, ChoiceNode, ChoiceSchemaNode> {
@Override
protected final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> getBuilder(
- org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
+ final ChoiceSchemaNode schema) {
return Builders.choiceBuilder(schema);
}
@Override
- protected final Set<DataSchemaNode> getRealSchemasForAugment(org.opendaylight.yangtools.yang.model.api.ChoiceNode schema,
- AugmentationSchema augmentSchema) {
+ protected final Set<DataSchemaNode> getRealSchemasForAugment(final ChoiceSchemaNode schema, final AugmentationSchema augmentSchema) {
Set<DataSchemaNode> fromAllCases = Sets.newHashSet();
fromAllCases.addAll(SchemaUtils.getRealSchemasForAugment(schema, augmentSchema));
}
@Override
- protected final DataSchemaNode getSchemaForChild(org.opendaylight.yangtools.yang.model.api.ChoiceNode schema,
- QName childQName) {
+ protected final DataSchemaNode getSchemaForChild(final ChoiceSchemaNode schema,
+ final QName childQName) {
return SchemaUtils.findSchemaForChild(schema, childQName);
}
@Override
- protected final Map<QName, org.opendaylight.yangtools.yang.model.api.ChoiceNode> mapChildElementsFromChoices(
- org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
- Map<QName, org.opendaylight.yangtools.yang.model.api.ChoiceNode> mappedChoices = Maps.newLinkedHashMap();
+ protected final Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final ChoiceSchemaNode schema) {
+ Map<QName, ChoiceSchemaNode> mappedChoices = new LinkedHashMap<>();
for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
mappedChoices.putAll(SchemaUtils.mapChildElementsFromChoices(choiceCaseNode));
}
@Override
- protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(
- org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
- Map<QName, AugmentationSchema> mappedAugments = Maps.newLinkedHashMap();
+ protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(final ChoiceSchemaNode schema) {
+ Map<QName, AugmentationSchema> mappedAugments = new LinkedHashMap<>();
for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
mappedAugments.putAll(SchemaUtils.mapChildElementsFromAugments(choiceCaseNode));
import java.util.Map;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@Override
protected final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> getBuilder(
- ContainerSchemaNode schema) {
+ final ContainerSchemaNode schema) {
return Builders.containerBuilder(schema);
}
@Override
- public final ContainerNode parse(Iterable<E> elements, ContainerSchemaNode schema) {
+ public final ContainerNode parse(final Iterable<E> elements, final ContainerSchemaNode schema) {
checkOnlyOneNode(schema, elements);
return super.parse(elements, schema);
}
@Override
- protected final Set<DataSchemaNode> getRealSchemasForAugment(ContainerSchemaNode schema, AugmentationSchema augmentSchema) {
+ protected final Set<DataSchemaNode> getRealSchemasForAugment(final ContainerSchemaNode schema, final AugmentationSchema augmentSchema) {
return SchemaUtils.getRealSchemasForAugment((AugmentationTarget) schema, augmentSchema);
}
@Override
- protected final DataSchemaNode getSchemaForChild(ContainerSchemaNode schema, QName childQName) {
+ protected final DataSchemaNode getSchemaForChild(final ContainerSchemaNode schema, final QName childQName) {
return SchemaUtils.findSchemaForChild(schema, childQName);
}
@Override
- protected final Map<QName, ChoiceNode> mapChildElementsFromChoices(ContainerSchemaNode schema) {
+ protected final Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final ContainerSchemaNode schema) {
return SchemaUtils.mapChildElementsFromChoices(schema);
}
@Override
- protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(ContainerSchemaNode schema) {
+ protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(final ContainerSchemaNode schema) {
return SchemaUtils.mapChildElementsFromAugments(schema);
}
import java.util.Map;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
/**
- * Abstract(base) parser for MapEntryNodes, parses elements of type E.
+ * Abstract(base) parser for ListNodes (MapNode, UnkeyedListNode), parses elements of type E.
*
- * @param <E> type of elements to be parsed
+ * @param <E>
+ * type of elements to be parsed
*/
-public abstract class MapEntryNodeBaseParser<E> extends BaseDispatcherParser<E, MapEntryNode, ListSchemaNode> {
-
- @Override
- protected final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> getBuilder(
- ListSchemaNode schema) {
- return Builders.mapEntryBuilder(schema);
- }
-
- @Override
- public final MapEntryNode parse(Iterable<E> elements, ListSchemaNode schema) {
- checkOnlyOneNode(schema, elements);
- return super.parse(elements, schema);
- }
+public abstract class ListEntryNodeBaseParser<E, N extends DataContainerNode<?>> extends
+ BaseDispatcherParser<E, N, ListSchemaNode> {
@Override
- protected final Set<DataSchemaNode> getRealSchemasForAugment(ListSchemaNode schema, AugmentationSchema augmentSchema) {
+ protected final Set<DataSchemaNode> getRealSchemasForAugment(final ListSchemaNode schema, final AugmentationSchema augmentSchema) {
return SchemaUtils.getRealSchemasForAugment((AugmentationTarget) schema, augmentSchema);
}
@Override
- protected final DataSchemaNode getSchemaForChild(ListSchemaNode schema, QName childQName) {
+ protected final DataSchemaNode getSchemaForChild(final ListSchemaNode schema, final QName childQName) {
return SchemaUtils.findSchemaForChild(schema, childQName);
}
@Override
- protected final Map<QName, ChoiceNode> mapChildElementsFromChoices(ListSchemaNode schema) {
+ protected final Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final ListSchemaNode schema) {
return SchemaUtils.mapChildElementsFromChoices(schema);
}
@Override
- protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(ListSchemaNode schema) {
+ protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(final ListSchemaNode schema) {
return SchemaUtils.mapChildElementsFromAugments(schema);
}
+ @Override
+ public final N parse(final Iterable<E> elements, final ListSchemaNode schema) {
+ checkOnlyOneNode(schema, elements);
+ return super.parse(elements, schema);
+ }
+
@Override
protected abstract Map<QName, String> getAttributes(E e);
-}
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
+
+import java.util.Collections;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+/**
+ * Abstract(base) parser for ListNodes (MapNode, UnkeyedListNode), parses elements of type E.
+ *
+ * @param <E>
+ * type of elements to be parsed
+ */
+public abstract class ListNodeBaseParser<E, N extends NormalizedNode<?, ?>, O extends NormalizedNode<YangInstanceIdentifier.NodeIdentifier, ?>, S extends ListSchemaNode>
+ implements ToNormalizedNodeParser<E, O, S> {
+
+ @Override
+ public final O parse(Iterable<E> childNodes, S schema) {
+ CollectionNodeBuilder<N, O> listBuilder = provideBuilder(schema);
+ for (E childNode : childNodes) {
+ N listChild = getListEntryNodeParser().parse(Collections.singletonList(childNode), schema);
+ listBuilder.withChild(listChild);
+ }
+
+ return listBuilder.build();
+ }
+
+ /**
+ *
+ * @return parser for inner ListEntryNodes used to parse every entry of ListNode, might be the same instance in case
+ * its immutable
+ */
+ protected abstract ToNormalizedNodeParser<E, N, S> getListEntryNodeParser();
+
+ /**
+ *
+ * @return prepares builder which will contain entries of list according to concrete list type
+ */
+ protected abstract CollectionNodeBuilder<N, O> provideBuilder(S schema);
+}
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import java.util.Collections;
-
/**
* Abstract(base) parser for MapNodes, parses elements of type E.
*
- * @param <E> type of elements to be parsed
+ * @param <E>
+ * type of elements to be parsed
*/
-public abstract class MapNodeBaseParser<E> implements ToNormalizedNodeParser<E, MapNode, ListSchemaNode> {
-
- @Override
- public final MapNode parse(Iterable<E> childNodes, ListSchemaNode schema) {
- if (schema.isUserOrdered()) {
- CollectionNodeBuilder<MapEntryNode, OrderedMapNode> listBuilder = Builders.orderedMapBuilder(schema);
-
- for (E childNode : childNodes) {
- MapEntryNode listChild = getMapEntryNodeParser().parse(Collections.singletonList(childNode), schema);
- listBuilder.withChild(listChild);
- }
+public abstract class MapNodeBaseParser<E> extends ListNodeBaseParser<E, MapEntryNode, MapNode, ListSchemaNode> {
- return listBuilder.build();
- } else {
- CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder(schema);
-
- for (E childNode : childNodes) {
- MapEntryNode listChild = getMapEntryNodeParser().parse(Collections.singletonList(childNode), schema);
- listBuilder.withChild(listChild);
- }
-
- return listBuilder.build();
- }
+ protected CollectionNodeBuilder<MapEntryNode, MapNode> provideBuilder(ListSchemaNode schema) {
+ return Builders.mapBuilder(schema);
}
- /**
- *
- * @return parser for inner MapEntryNodes used to parse every entry of MapNode, might be the same instance in case its immutable
- */
- protected abstract ToNormalizedNodeParser<E, MapEntryNode, ListSchemaNode> getMapEntryNodeParser();
-
-}
+}
\ No newline at end of file
import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParserFactory;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
}
@Override
- public final DataContainerChild<?, ?> dispatchChildElement(Object schema, List<E> childNodes) {
+ public final DataContainerChild<?, ?> dispatchChildElement(final Object schema, final List<E> childNodes) {
Preconditions.checkArgument(!childNodes.isEmpty());
if (schema instanceof ContainerSchemaNode) {
} else if (schema instanceof LeafListSchemaNode) {
return factory.getLeafSetNodeParser().parse(childNodes, (LeafListSchemaNode) schema);
} else if (schema instanceof ListSchemaNode) {
- return factory.getMapNodeParser().parse(childNodes, (ListSchemaNode) schema);
- } else if (schema instanceof ChoiceNode) {
- return factory.getChoiceNodeParser().parse(childNodes, (ChoiceNode) schema);
+ final ListSchemaNode listSchemaNode = (ListSchemaNode)schema;
+ if (listSchemaNode.isUserOrdered()) {
+ return factory.getOrderedListNodeParser().parse(childNodes, listSchemaNode);
+ } else if (listSchemaNode.getKeyDefinition().isEmpty()) {
+ return factory.getUnkeyedListNodeParser().parse(childNodes, listSchemaNode);
+ } else {
+ return factory.getMapNodeParser().parse(childNodes, listSchemaNode);
+ }
+ } else if (schema instanceof ChoiceSchemaNode) {
+ return factory.getChoiceNodeParser().parse(childNodes, (ChoiceSchemaNode) schema);
} else if (schema instanceof AugmentationSchema) {
return factory.getAugmentationNodeParser().parse(childNodes, (AugmentationSchema) schema);
} else if (schema instanceof AnyXmlSchemaNode) {
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
+
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+/**
+ * Abstract(base) parser for OrderedListNodes, parses elements of type E.
+ *
+ * @param <E>
+ * type of elements to be parsed
+ */
+public abstract class OrderedListNodeBaseParser<E> extends
+ ListNodeBaseParser<E, MapEntryNode, OrderedMapNode, ListSchemaNode> {
+ @Override
+ protected CollectionNodeBuilder<MapEntryNode, OrderedMapNode> provideBuilder(ListSchemaNode schema) {
+ return Builders.orderedMapBuilder(schema);
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+/**
+ * Abstract(base) parser for UnkeyedListNodes, parses elements of type E.
+ *
+ * @param <E>
+ * type of elements to be parsed
+ */
+public abstract class UnkeyedListNodeBaseParser<E> extends
+ ListNodeBaseParser<E, UnkeyedListEntryNode, UnkeyedListNode, ListSchemaNode> {
+ @Override
+ protected CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> provideBuilder(ListSchemaNode schema) {
+ CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> listBuilder = Builders.unkeyedListBuilder();
+ return listBuilder.withNodeIdentifier(new NodeIdentifier(schema.getQName()));
+ }
+}
*/
package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
import java.util.List;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
/**
* Abstract(base) Serializer for DataContainerNodes e.g. ContainerNode, AugmentationNode.
AugmentationSchema augSchema = getAugmentedCase(schema, (AugmentationNode) choiceChild);
Set<DataSchemaNode> realChildSchemas = getRealSchemasForAugment(schema, augSchema);
- childSchema = new AugmentationSchemaProxy(augSchema, realChildSchemas);
+ childSchema = new EffectiveAugmentationSchema(augSchema, realChildSchemas);
} else {
childSchema = getSchemaForChild(schema, choiceChild);
import java.util.HashSet;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
/**
*
* @param <E> type of serialized elements
*/
-public abstract class ChoiceNodeBaseSerializer<E>
- extends
- BaseDispatcherSerializer<E, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> {
+public abstract class ChoiceNodeBaseSerializer<E> extends BaseDispatcherSerializer<E, ChoiceNode, ChoiceSchemaNode> {
@Override
- protected final DataSchemaNode getSchemaForChild(final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema,
+ protected final DataSchemaNode getSchemaForChild(final ChoiceSchemaNode schema,
final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> childNode) {
return SchemaUtils.findSchemaForChild(schema, childNode.getNodeType());
}
@Override
- protected final AugmentationSchema getAugmentedCase(final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema,
+ protected final AugmentationSchema getAugmentedCase(final ChoiceSchemaNode schema,
final AugmentationNode augmentationNode) {
return SchemaUtils.findSchemaForAugment(schema, augmentationNode.getIdentifier().getPossibleChildNames());
}
@Override
- protected final Set<DataSchemaNode> getRealSchemasForAugment(final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema, final AugmentationSchema augmentationSchema) {
+ protected final Set<DataSchemaNode> getRealSchemasForAugment(final ChoiceSchemaNode schema, final AugmentationSchema augmentationSchema) {
Set<DataSchemaNode> aggregatedSchemas = new HashSet<>(SchemaUtils.getRealSchemasForAugment(schema, augmentationSchema));
for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
/**
- * Abstract(base) serializer for MapEntryNodes, serializes elements of type E.
+ * Abstract(base) serializer for ListEntryNodes (MapEntryNode, UnkeyedListEntryNode), serializes elements of type E.
*
- * @param <E> type of serialized elements
+ * @param <E>
+ * type of serialized elements
*/
-public abstract class MapEntryNodeBaseSerializer<E> extends
- BaseDispatcherSerializer<E, MapEntryNode, ListSchemaNode> {
+public abstract class ListEntryNodeBaseSerializer<E, N extends DataContainerNode<?>> extends
+ BaseDispatcherSerializer<E, N, ListSchemaNode> {
@Override
protected final DataSchemaNode getSchemaForChild(ListSchemaNode schema,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> childNode) {
+ DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> childNode) {
return SchemaUtils.findSchemaForChild(schema, childNode.getNodeType());
}
}
@Override
- protected final Set<DataSchemaNode> getRealSchemasForAugment(ListSchemaNode schema, AugmentationSchema augmentationSchema) {
+ protected final Set<DataSchemaNode> getRealSchemasForAugment(ListSchemaNode schema,
+ AugmentationSchema augmentationSchema) {
return SchemaUtils.getRealSchemasForAugment((AugmentationTarget) schema, augmentationSchema);
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer;
+
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+import java.util.Collection;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+/**
+ * Abstract(base) serializer for ListNodes (MapNode, UnkeyedListNode), serializes elements of type E.
+ *
+ * @param <E>
+ * type of serialized elements
+ * @param <N>
+ * containing node type
+ * @param <O>
+ * entry node type which is inside containing (N) type
+ */
+public abstract class ListNodeBaseSerializer<E, N extends DataContainerChild<NodeIdentifier, Collection<O>>, O extends DataContainerNode<?>>
+ implements FromNormalizedNodeSerializer<E, N, ListSchemaNode> {
+
+ @Override
+ public final Iterable<E> serialize(final ListSchemaNode schema, final N node) {
+ return Iterables.concat(Iterables.transform(node.getValue(), new Function<O, Iterable<E>>() {
+ @Override
+ public Iterable<E> apply(final O input) {
+ final Iterable<E> serializedChild = getListEntryNodeSerializer().serialize(schema, input);
+ final int size = Iterables.size(serializedChild);
+
+ Preconditions.checkState(size == 1,
+ "Unexpected count of entries for list serialized from: %s, should be 1, was: %s", input, size);
+ return serializedChild;
+ }
+ }));
+ }
+
+ /**
+ *
+ * @return serializer for inner ListEntryNodes (MapEntryNode, UnkeyedListEntryNode) used to serialize every entry of
+ * ListNode, might be the same instance in case its immutable
+ */
+ protected abstract FromNormalizedNodeSerializer<E, O, ListSchemaNode> getListEntryNodeSerializer();
+}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Iterables;
-
-/**
- * Abstract(base) serializer for MapNodes, serializes elements of type E.
- *
- * @param <E> type of serialized elements
- */
-public abstract class MapNodeBaseSerializer<E> implements FromNormalizedNodeSerializer<E, MapNode, ListSchemaNode> {
-
- @Override
- public final Iterable<E> serialize(final ListSchemaNode schema, final MapNode node) {
- return Iterables.concat(Iterables.transform(node.getValue(), new Function<MapEntryNode, Iterable<E>>() {
- @Override
- public Iterable<E> apply(MapEntryNode input) {
- final Iterable<E> serializedChild = getMapEntryNodeDomSerializer().serialize(schema, input);
- final int size = Iterables.size(serializedChild);
-
- Preconditions.checkState(size == 1,
- "Unexpected count of entries for list serialized from: %s, should be 1, was: %s",
- input, size);
- return serializedChild;
- }
- }));
- }
-
- /**
- *
- * @return serializer for inner MapEntryNodes used to serialize every entry of MapNode, might be the same instance in case its immutable
- */
- protected abstract FromNormalizedNodeSerializer<E, MapEntryNode, ListSchemaNode> getMapEntryNodeDomSerializer();
-}
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.MixinNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializerFactory;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
}
@Override
- public final Iterable<E> dispatchChildElement(Object childSchema,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ public final Iterable<E> dispatchChildElement(final Object childSchema,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
if (dataContainerChild instanceof ContainerNode) {
return onContainerNode(childSchema, dataContainerChild);
} else if (dataContainerChild instanceof LeafNode<?>) {
if (dataContainerChild instanceof LeafSetNode<?>) {
return onLeafListNode(childSchema, dataContainerChild);
} else if (dataContainerChild instanceof MapNode) {
- return onListNode(childSchema, dataContainerChild);
+ return onMapNode(childSchema, dataContainerChild);
+ } else if (dataContainerChild instanceof UnkeyedListNode) {
+ return onUnkeyedListNode(childSchema, dataContainerChild);
} else if (dataContainerChild instanceof ChoiceNode) {
return onChoiceNode(childSchema, dataContainerChild);
} else if (dataContainerChild instanceof AugmentationNode) {
throw new IllegalArgumentException("Unable to serialize " + childSchema);
}
- private Iterable<E> onAugmentationSchema(Object childSchema,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ private Iterable<E> onAugmentationSchema(final Object childSchema,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
checkSchemaCompatibility(childSchema, AugmentationSchema.class, dataContainerChild);
return factory.getAugmentationNodeSerializer().serialize((AugmentationSchema) childSchema,
(AugmentationNode) dataContainerChild);
}
- private Iterable<E> onChoiceNode(Object childSchema,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
- checkSchemaCompatibility(childSchema, org.opendaylight.yangtools.yang.model.api.ChoiceNode.class,
+ private Iterable<E> onChoiceNode(final Object childSchema,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ checkSchemaCompatibility(childSchema, ChoiceSchemaNode.class,
dataContainerChild);
return factory.getChoiceNodeSerializer()
- .serialize((org.opendaylight.yangtools.yang.model.api.ChoiceNode) childSchema,
- (ChoiceNode) dataContainerChild);
+ .serialize((ChoiceSchemaNode) childSchema, (ChoiceNode) dataContainerChild);
}
- private Iterable<E> onListNode(Object childSchema,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ private Iterable<E> onMapNode(final Object childSchema,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
checkSchemaCompatibility(childSchema, ListSchemaNode.class, dataContainerChild);
return factory.getMapNodeSerializer().serialize((ListSchemaNode) childSchema, (MapNode) dataContainerChild);
}
- private Iterable<E> onLeafListNode(Object childSchema,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ private Iterable<E> onUnkeyedListNode(final Object childSchema,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ checkSchemaCompatibility(childSchema, ListSchemaNode.class, dataContainerChild);
+ return factory.getUnkeyedListNodeSerializer().serialize((ListSchemaNode) childSchema, (UnkeyedListNode) dataContainerChild);
+ }
+
+ private Iterable<E> onLeafListNode(final Object childSchema,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
checkSchemaCompatibility(childSchema, LeafListSchemaNode.class, dataContainerChild);
return factory.getLeafSetNodeSerializer().serialize((LeafListSchemaNode) childSchema,
(LeafSetNode<?>) dataContainerChild);
}
- private Iterable<E> onLeafNode(Object childSchema,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ private Iterable<E> onLeafNode(final Object childSchema,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
checkSchemaCompatibility(childSchema, LeafSchemaNode.class, dataContainerChild);
Iterable<E> elements = factory.getLeafNodeSerializer().serialize((LeafSchemaNode) childSchema,
(LeafNode<?>) dataContainerChild);
return elements;
}
- private Iterable<E> onAnyXmlNode(Object childSchema,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ private Iterable<E> onAnyXmlNode(final Object childSchema,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
checkSchemaCompatibility(childSchema, AnyXmlSchemaNode.class, dataContainerChild);
Iterable<E> elements = factory.getAnyXmlNodeSerializer().serialize((AnyXmlSchemaNode) childSchema,
(AnyXmlNode) dataContainerChild);
return elements;
}
- private static void checkOnlyOneSerializedElement(Iterable<?> elements,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ private static void checkOnlyOneSerializedElement(final Iterable<?> elements,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
final int size = Iterables.size(elements);
Preconditions.checkArgument(size == 1,
"Unexpected count of elements for entry serialized from: %s, should be 1, was: %s",
dataContainerChild, size);
}
- private Iterable<E> onContainerNode(Object childSchema,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ private Iterable<E> onContainerNode(final Object childSchema,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
checkSchemaCompatibility(childSchema, ContainerSchemaNode.class, dataContainerChild);
Iterable<E> elements = factory.getContainerNodeSerializer().serialize((ContainerSchemaNode) childSchema,
return elements;
}
- private static void checkSchemaCompatibility(Object childSchema, Class<?> containerSchemaNodeClass,
- DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+ private static void checkSchemaCompatibility(final Object childSchema, final Class<?> containerSchemaNodeClass,
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
Preconditions.checkArgument(containerSchemaNodeClass.isAssignableFrom(childSchema.getClass()),
"Incompatible schema: %s with node: %s, expected: %s", childSchema, dataContainerChild,
containerSchemaNodeClass);
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Lists;
-
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.xml.XMLConstants;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.InstanceIdentifierForXmlCodec;
import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlStreamUtils;
import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
+import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
}
return attributes;
}
+
+ public static Object parseXmlValue(final Element xml, final XmlCodecProvider codecProvider, final DataSchemaNode schema, final TypeDefinition<?> type, final SchemaContext schemaCtx) {
+ TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
+ if (baseType instanceof LeafrefTypeDefinition) {
+ final LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
+ baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaCtx, schema);
+ }
+
+ String text = xml.getTextContent();
+ text = text.trim();
+ final Object value;
+
+ if (baseType instanceof InstanceIdentifierType) {
+ value = InstanceIdentifierForXmlCodec.deserialize(xml, schemaCtx);
+ } else if (baseType instanceof IdentityrefTypeDefinition) {
+ value = InstanceIdentifierForXmlCodec.toIdentity(text, xml, schemaCtx);
+ } else {
+ value = parseXmlValue(xml, codecProvider, type);
+ }
+
+ return value;
+ }
}
--- /dev/null
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
+
+import com.google.common.base.Preconditions;
+import javax.xml.transform.dom.DOMSource;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.AnyXmlNodeBaseParser;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.w3c.dom.Element;
+
+public class AnyXmlDomParser extends AnyXmlNodeBaseParser<Element> {
+
+ @Override
+ protected DOMSource parseAnyXml(final Element element, final AnyXmlSchemaNode schema) {
+ final QName qName = schema.getQName();
+ Preconditions.checkArgument(element.getNodeName().equals(qName.getLocalName()));
+ Preconditions.checkArgument(element.getNamespaceURI().equals(qName.getNamespace().toString()));
+ return new DOMSource(element);
+ }
+}
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParserFactory;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
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.SchemaContext;
import org.w3c.dom.Element;
public final class DomToNormalizedNodeParserFactory implements ToNormalizedNodeParserFactory<Element> {
private final LeafSetNodeDomParser leafSetNodeParser;
private final MapNodeDomParser mapNodeParser;
private final MapEntryNodeDomParser mapEntryNodeParser;
+ private final UnkeyedListEntryNodeDomParser unkeyedListEntryNodeParser;
+ private final UnkeyedListNodeDomParser unkeyedListNodeParser;
+ private final OrderedListNodeDomParser orderedListNodeParser;
+ private final AnyXmlDomParser anyXmlNodeParser;
+
+ private DomToNormalizedNodeParserFactory(final XmlCodecProvider codecProvider, final SchemaContext schema) {
+ leafNodeParser = new LeafNodeDomParser(codecProvider, schema);
+ leafSetEntryNodeParser = new LeafSetEntryNodeDomParser(codecProvider, schema);
+ leafSetNodeParser = new LeafSetNodeDomParser(leafSetEntryNodeParser);
+ anyXmlNodeParser = new AnyXmlDomParser();
+
+ final NodeParserDispatcher<Element> dispatcher = new NodeParserDispatcher.BaseNodeParserDispatcher<Element>(this) {
+
+ };
+
+ containerNodeParser = new ContainerNodeDomParser(dispatcher);
+ mapEntryNodeParser = new MapEntryNodeDomParser(dispatcher);
+ mapNodeParser = new MapNodeDomParser(mapEntryNodeParser);
+ orderedListNodeParser = new OrderedListNodeDomParser(mapEntryNodeParser);
+ unkeyedListEntryNodeParser = new UnkeyedListEntryNodeDomParser(dispatcher);
+ unkeyedListNodeParser = new UnkeyedListNodeDomParser(unkeyedListEntryNodeParser);
+ choiceNodeParser = new ChoiceNodeDomParser(dispatcher);
+ augmentationNodeParser = new AugmentationNodeDomParser(dispatcher);
+ }
+ @Deprecated
private DomToNormalizedNodeParserFactory(final XmlCodecProvider codecProvider) {
leafNodeParser = new LeafNodeDomParser(codecProvider);
leafSetEntryNodeParser = new LeafSetEntryNodeDomParser(codecProvider);
leafSetNodeParser = new LeafSetNodeDomParser(leafSetEntryNodeParser);
+ anyXmlNodeParser = new AnyXmlDomParser();
final NodeParserDispatcher<Element> dispatcher = new NodeParserDispatcher.BaseNodeParserDispatcher<Element>(this) {
containerNodeParser = new ContainerNodeDomParser(dispatcher);
mapEntryNodeParser = new MapEntryNodeDomParser(dispatcher);
mapNodeParser = new MapNodeDomParser(mapEntryNodeParser);
+ orderedListNodeParser = new OrderedListNodeDomParser(mapEntryNodeParser);
+ unkeyedListEntryNodeParser = new UnkeyedListEntryNodeDomParser(dispatcher);
+ unkeyedListNodeParser = new UnkeyedListNodeDomParser(unkeyedListEntryNodeParser);
choiceNodeParser = new ChoiceNodeDomParser(dispatcher);
augmentationNodeParser = new AugmentationNodeDomParser(dispatcher);
}
+ public static DomToNormalizedNodeParserFactory getInstance(final XmlCodecProvider codecProvider, final SchemaContext schema) {
+ return new DomToNormalizedNodeParserFactory(codecProvider, schema);
+ }
+
+ @Deprecated
public static DomToNormalizedNodeParserFactory getInstance(final XmlCodecProvider codecProvider) {
return new DomToNormalizedNodeParserFactory(codecProvider);
}
}
@Override
- public ToNormalizedNodeParser<Element, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeParser() {
+ public ToNormalizedNodeParser<Element, ChoiceNode, ChoiceSchemaNode> getChoiceNodeParser() {
return choiceNodeParser;
}
return mapNodeParser;
}
+ @Override
+ public ToNormalizedNodeParser<Element, UnkeyedListNode, ListSchemaNode> getUnkeyedListNodeParser() {
+ return unkeyedListNodeParser;
+ }
+
+ @Override
+ public ToNormalizedNodeParser<Element, UnkeyedListEntryNode, ListSchemaNode> getUnkeyedListEntryNodeParser() {
+ return unkeyedListEntryNodeParser;
+ }
+
+ @Override
+ public ToNormalizedNodeParser<Element, OrderedMapNode, ListSchemaNode> getOrderedListNodeParser() {
+ return orderedListNodeParser;
+ }
+
@Override
public ToNormalizedNodeParser<Element, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeParser() {
- throw new UnsupportedOperationException();
+ return anyXmlNodeParser;
}
}
import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.LeafNodeBaseParser;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.w3c.dom.Element;
import com.google.common.base.Preconditions;
final class LeafNodeDomParser extends LeafNodeBaseParser<Element> {
private final XmlCodecProvider codecProvider;
+ private final SchemaContext ctx;
- LeafNodeDomParser(XmlCodecProvider codecProvider) {
+ LeafNodeDomParser(XmlCodecProvider codecProvider, final SchemaContext schema) {
+ this.ctx = schema;
this.codecProvider = Preconditions.checkNotNull(codecProvider);
}
+ @Deprecated
+ LeafNodeDomParser(XmlCodecProvider codecProvider) {
+ this(codecProvider, null);
+ }
+
@Override
protected Object parseLeaf(Element xmlElement, LeafSchemaNode schema) {
- return DomUtils.parseXmlValue(xmlElement, codecProvider, schema.getType());
+ return ctx == null ? DomUtils.parseXmlValue(xmlElement, codecProvider, schema.getType()) : DomUtils.parseXmlValue(xmlElement, codecProvider, schema, schema.getType(), ctx);
}
@Override
import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.LeafSetEntryNodeBaseParser;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.w3c.dom.Element;
import com.google.common.base.Preconditions;
final class LeafSetEntryNodeDomParser extends LeafSetEntryNodeBaseParser<Element> {
private final XmlCodecProvider codecProvider;
+ private final SchemaContext ctx;
- LeafSetEntryNodeDomParser(XmlCodecProvider codecProvider) {
+ LeafSetEntryNodeDomParser(XmlCodecProvider codecProvider, final SchemaContext schema) {
+ ctx = schema;
this.codecProvider = Preconditions.checkNotNull(codecProvider);
}
+ @Deprecated
+ public LeafSetEntryNodeDomParser(final XmlCodecProvider codecProvider) {
+ this(codecProvider, null);
+ }
+
@Override
protected Object parseLeafListEntry(Element xmlElement, LeafListSchemaNode schema) {
- return DomUtils.parseXmlValue(xmlElement, codecProvider, schema.getType());
+ return ctx == null ? DomUtils.parseXmlValue(xmlElement, codecProvider, schema.getType()) : DomUtils.parseXmlValue(xmlElement, codecProvider, schema, schema.getType(), ctx);
}
@Override
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.LinkedListMultimap;
+import java.util.Map;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.ListEntryNodeBaseParser;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
+import org.w3c.dom.Element;
+
+abstract class ListEntryNodeDomParser<N extends DataContainerNode<?>> extends ListEntryNodeBaseParser<Element, N> {
+
+ private final NodeParserDispatcher<Element> dispatcher;
+
+ ListEntryNodeDomParser(final NodeParserDispatcher<Element> dispatcher) {
+ this.dispatcher = Preconditions.checkNotNull(dispatcher);
+ }
+
+ @Override
+ protected LinkedListMultimap<QName, Element> mapChildElements(Iterable<Element> elements) {
+ return DomUtils.mapChildElementsForSingletonNode(elements.iterator().next());
+ }
+
+ @Override
+ protected NodeParserDispatcher<Element> getDispatcher() {
+ return dispatcher;
+ }
+
+ @Override
+ protected Map<QName, String> getAttributes(Element element) {
+ return DomUtils.toAttributes(element.getAttributes());
+ }
+}
*/
package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.MapEntryNodeBaseParser;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.w3c.dom.Element;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.LinkedListMultimap;
-
-final class MapEntryNodeDomParser extends MapEntryNodeBaseParser<Element> {
-
- private final NodeParserDispatcher<Element> dispatcher;
+final class MapEntryNodeDomParser extends ListEntryNodeDomParser<MapEntryNode> {
MapEntryNodeDomParser(final NodeParserDispatcher<Element> dispatcher) {
- this.dispatcher = Preconditions.checkNotNull(dispatcher);
- }
-
- @Override
- protected LinkedListMultimap<QName, Element> mapChildElements(Iterable<Element> elements) {
- return DomUtils.mapChildElementsForSingletonNode(elements.iterator().next());
- }
-
- @Override
- protected NodeParserDispatcher<Element> getDispatcher() {
- return dispatcher;
+ super(dispatcher);
}
@Override
- protected Map<QName, String> getAttributes(Element element) {
- return DomUtils.toAttributes(element.getAttributes());
+ protected final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> getBuilder(
+ ListSchemaNode schema) {
+ return Builders.mapEntryBuilder(schema);
}
}
}
@Override
- protected ToNormalizedNodeParser<Element, MapEntryNode, ListSchemaNode> getMapEntryNodeParser() {
+ protected ToNormalizedNodeParser<Element, MapEntryNode, ListSchemaNode> getListEntryNodeParser() {
return mapEntryParser;
}
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
-import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.MapNodeBaseParser;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.OrderedListNodeBaseParser;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.w3c.dom.Element;
-public final class MapNodeCnSnParser extends MapNodeBaseParser<Node<?>> {
+final class OrderedListNodeDomParser extends OrderedListNodeBaseParser<Element> {
- private final MapEntryNodeCnSnParser mapEntryNodeCnSnParser;
+ private final MapEntryNodeDomParser mapEntryNodeParser;
- public MapNodeCnSnParser(MapEntryNodeCnSnParser mapEntryNodeCnSnParser) {
- this.mapEntryNodeCnSnParser = mapEntryNodeCnSnParser;
+ OrderedListNodeDomParser(MapEntryNodeDomParser mapEntryNodeParser) {
+ this.mapEntryNodeParser = mapEntryNodeParser;
}
@Override
- protected ToNormalizedNodeParser<Node<?>, MapEntryNode, ListSchemaNode> getMapEntryNodeParser() {
- return mapEntryNodeCnSnParser;
+ protected ToNormalizedNodeParser<Element, MapEntryNode, ListSchemaNode> getListEntryNodeParser() {
+ return mapEntryNodeParser;
}
-
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
+
+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.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.w3c.dom.Element;
+
+final class UnkeyedListEntryNodeDomParser extends ListEntryNodeDomParser<UnkeyedListEntryNode> {
+
+ UnkeyedListEntryNodeDomParser(final NodeParserDispatcher<Element> dispatcher) {
+ super(dispatcher);
+ }
+
+ @Override
+ protected final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, UnkeyedListEntryNode> getBuilder(
+ ListSchemaNode schema) {
+ return Builders.unkeyedListEntryBuilder().withNodeIdentifier(new NodeIdentifier(schema.getQName()));
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
+
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.UnkeyedListNodeBaseParser;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.w3c.dom.Element;
+
+final class UnkeyedListNodeDomParser extends UnkeyedListNodeBaseParser<Element> {
+
+ private final UnkeyedListEntryNodeDomParser unkeyedListEntryNodeParser;
+
+ UnkeyedListNodeDomParser(UnkeyedListEntryNodeDomParser unkeyedListEntryNodeParser) {
+ this.unkeyedListEntryNodeParser = unkeyedListEntryNodeParser;
+ }
+
+ @Override
+ protected ToNormalizedNodeParser<Element, UnkeyedListEntryNode, ListSchemaNode> getListEntryNodeParser() {
+ return unkeyedListEntryNodeParser;
+ }
+}
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializerFactory;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
+// TODO Is this used anywhere ? it is replaced by the NormalizedNode stream writer, COuld this be removed ?
+
public final class DomFromNormalizedNodeSerializerFactory implements FromNormalizedNodeSerializerFactory<Element> {
private final ContainerNodeDomSerializer containerSerializer;
private final ChoiceNodeDomSerializer choiceSerializer;
private final LeafNodeDomSerializer leafNodeSerializer;
private final LeafSetNodeDomSerializer leafSetSerializer;
private final MapNodeDomSerializer mapNodeSerializer;
+ private final UnkeyedListNodeDomSerializer unkeyedListNodeSerializer;
private final LeafSetEntryNodeDomSerializer leafSetEntryNodeSerializer;
- private final MapEntryNodeDomSerializer mapEntryNodeSerializer;
+ private final MapEntryNodeDomSerializer mapEntryNodeSerializer;
+ private final UnkeyedListEntryNodeDomSerializer unkeyedListEntryNodeSerializer;
private DomFromNormalizedNodeSerializerFactory(final Document doc, final XmlCodecProvider codecProvider) {
final NodeSerializerDispatcher.BaseNodeSerializerDispatcher<Element> dispatcher = new NodeSerializerDispatcher.BaseNodeSerializerDispatcher<Element>(this) {
mapEntryNodeSerializer = new MapEntryNodeDomSerializer(doc, dispatcher);
mapNodeSerializer = new MapNodeDomSerializer(mapEntryNodeSerializer);
+
+ unkeyedListEntryNodeSerializer = new UnkeyedListEntryNodeDomSerializer(doc, dispatcher);
+ unkeyedListNodeSerializer = new UnkeyedListNodeDomSerializer(unkeyedListEntryNodeSerializer);
}
public static DomFromNormalizedNodeSerializerFactory getInstance(final Document doc, final XmlCodecProvider codecProvider) {
}
@Override
- public FromNormalizedNodeSerializer<Element, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeSerializer() {
+ public FromNormalizedNodeSerializer<Element, ChoiceNode, ChoiceSchemaNode> getChoiceNodeSerializer() {
return choiceSerializer;
}
return mapNodeSerializer;
}
+ @Override
+ public FromNormalizedNodeSerializer<Element, UnkeyedListNode, ListSchemaNode> getUnkeyedListNodeSerializer() {
+ return unkeyedListNodeSerializer;
+ }
+
@Override
public FromNormalizedNodeSerializer<Element, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeSerializer() {
throw new UnsupportedOperationException();
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ListEntryNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ *
+ * Common class for list entry node serialization (MapEntry, UnkeyedListEntry nodes)
+ *
+ * @param <N>
+ * concrete entry node type
+ */
+abstract class ListEntryNodeDomSerializer<N extends DataContainerNode<?>> extends
+ ListEntryNodeBaseSerializer<Element, N> {
+ private final NodeSerializerDispatcher<Element> dispatcher;
+ private final Document doc;
+
+ ListEntryNodeDomSerializer(final Document doc, final NodeSerializerDispatcher<Element> dispatcher) {
+ this.doc = Preconditions.checkNotNull(doc);
+ this.dispatcher = Preconditions.checkNotNull(dispatcher);
+ }
+
+ @Override
+ public Iterable<Element> serialize(ListSchemaNode schema, N node) {
+ Element itemEl = XmlDocumentUtils.createElementFor(doc, node);
+
+ for (Element element : super.serialize(schema, node)) {
+ itemEl.appendChild(element);
+ }
+
+ return Collections.singletonList(itemEl);
+ }
+
+ @Override
+ protected NodeSerializerDispatcher<Element> getNodeDispatcher() {
+ return dispatcher;
+ }
+}
*/
package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
-import java.util.Collections;
-
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.MapEntryNodeBaseSerializer;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Preconditions;
-
-final class MapEntryNodeDomSerializer extends MapEntryNodeBaseSerializer<Element> {
- private final NodeSerializerDispatcher<Element> dispatcher;
- private final Document doc;
-
+final class MapEntryNodeDomSerializer extends ListEntryNodeDomSerializer<MapEntryNode> {
MapEntryNodeDomSerializer(final Document doc, final NodeSerializerDispatcher<Element> dispatcher) {
- this.doc = Preconditions.checkNotNull(doc);
- this.dispatcher = Preconditions.checkNotNull(dispatcher);
- }
-
- @Override
- public Iterable<Element> serialize(ListSchemaNode schema, MapEntryNode node) {
- Element itemEl = XmlDocumentUtils.createElementFor(doc, node);
-
- for (Element element : super.serialize(schema, node)) {
- itemEl.appendChild(element);
- }
-
- return Collections.singletonList(itemEl);
- }
-
- @Override
- protected NodeSerializerDispatcher<Element> getNodeDispatcher() {
- return dispatcher;
+ super(doc, dispatcher);
}
}
package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.MapNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ListNodeBaseSerializer;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.w3c.dom.Element;
-final class MapNodeDomSerializer extends MapNodeBaseSerializer<Element> {
+final class MapNodeDomSerializer extends ListNodeBaseSerializer<Element, MapNode, MapEntryNode> {
private final FromNormalizedNodeSerializer<Element, MapEntryNode, ListSchemaNode> mapEntrySerializer;
}
@Override
- protected FromNormalizedNodeSerializer<Element, MapEntryNode, ListSchemaNode> getMapEntryNodeDomSerializer() {
+ protected FromNormalizedNodeSerializer<Element, MapEntryNode, ListSchemaNode> getListEntryNodeSerializer() {
return mapEntrySerializer;
}
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
+
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+final class UnkeyedListEntryNodeDomSerializer extends ListEntryNodeDomSerializer<UnkeyedListEntryNode> {
+
+ UnkeyedListEntryNodeDomSerializer(final Document doc, final NodeSerializerDispatcher<Element> dispatcher) {
+ super(doc, dispatcher);
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
+
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ListNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.w3c.dom.Element;
+
+final class UnkeyedListNodeDomSerializer extends ListNodeBaseSerializer<Element, UnkeyedListNode, UnkeyedListEntryNode> {
+
+ private final FromNormalizedNodeSerializer<Element, UnkeyedListEntryNode, ListSchemaNode> unkeyedListEntrySerializer;
+
+ UnkeyedListNodeDomSerializer(UnkeyedListEntryNodeDomSerializer unkeyedListEntrySerializer) {
+ this.unkeyedListEntrySerializer = unkeyedListEntrySerializer;
+ }
+
+ @Override
+ protected FromNormalizedNodeSerializer<Element, UnkeyedListEntryNode, ListSchemaNode> getListEntryNodeSerializer() {
+ return unkeyedListEntrySerializer;
+ }
+}
import static com.google.common.base.Preconditions.checkArgument;
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
-
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListEntryNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
/**
* Base strategy for applying changes to a ContainerNode, irrespective of its
return ImmutableAugmentationNodeBuilder.create((AugmentationNode) original);
}
-
private static AugmentationSchema createAugmentProxy(final AugmentationSchema schema, final DataNodeContainer resolved) {
Set<DataSchemaNode> realChildSchemas = new HashSet<>();
for(DataSchemaNode augChild : schema.getChildNodes()) {
realChildSchemas.add(resolved.getDataChildByName(augChild.getQName()));
}
- return new AugmentationSchemaProxy(schema, realChildSchemas);
+ return new EffectiveAugmentationSchema(schema, realChildSchemas);
}
}
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.slf4j.Logger;
public synchronized void setSchemaContext(final SchemaContext newSchemaContext) {
Preconditions.checkNotNull(newSchemaContext);
- LOG.info("Attempting to install schema contexts");
LOG.debug("Following schema contexts will be attempted {}", newSchemaContext);
final SchemaAwareApplyOperation operation = SchemaAwareApplyOperation.from(newSchemaContext);
final InMemoryDataTreeModification m = (InMemoryDataTreeModification)modification;
final ModifiedNode root = m.getRootModification();
- if (root.getType() == ModificationType.UNMODIFIED) {
+ if (root.getOperation() == LogicalOperation.NONE) {
return new NoopDataTreeCandidate(PUBLIC_ROOT_PATH, root);
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
@Override
public ModificationType getModificationType() {
- return mod.getType();
+ switch (mod.getOperation()) {
+ case DELETE:
+ return ModificationType.DELETE;
+ case MERGE:
+ // Merge into non-existing data is a write
+ if (oldMeta == null) {
+ return ModificationType.WRITE;
+ }
+
+ // Data-based checks to narrow down types
+ final NormalizedNode<?, ?> data = newMeta.getData();
+
+ // leaf or anyxml are always written
+ if (!(data instanceof NormalizedNodeContainer)) {
+ return ModificationType.WRITE;
+ }
+
+ // Unkeyed collections are always written
+ if (data instanceof UnkeyedListNode || data instanceof OrderedMapNode || data instanceof OrderedLeafSetNode) {
+ return ModificationType.WRITE;
+ }
+
+ // Everything else is subtree modified
+ return ModificationType.SUBTREE_MODIFIED;
+ case TOUCH:
+ return ModificationType.SUBTREE_MODIFIED;
+ case NONE:
+ return ModificationType.UNMODIFIED;
+ case WRITE:
+ return ModificationType.WRITE;
+ }
+
+ throw new IllegalStateException("Unhandled internal operation " + mod.getOperation());
}
private Optional<NormalizedNode<?, ?>> optionalData(final TreeNode meta) {
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
LOG.trace("Resolving modification apply strategy for {}", path);
- if (rootNode.getType() == ModificationType.UNMODIFIED) {
+ if (rootNode.getOperation() == LogicalOperation.NONE) {
strategyTree.upgradeIfPossible();
}
public DataTreeModification newModification() {
Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
- if (rootNode.getType() == ModificationType.UNMODIFIED) {
+ if (rootNode.getOperation() == LogicalOperation.NONE) {
// Simple fast case: just use the underlying modification
return snapshot.newModification();
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.tree;
+
+import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
+
+/**
+ * Enumeration of all possible node modification states. These are used in
+ * data tree modification context to quickly assess what sort of modification
+ * the node is undergoing. This is a superset of {@link ModificationType}:
+ * where this type represents a logical operation, {@link ModificationType}
+ * represents a physical operation.
+ */
+enum LogicalOperation {
+ /**
+ * Node is currently unmodified.
+ */
+ NONE,
+
+ /**
+ * A child node, either direct or indirect, has been modified. This means
+ * that the data representation of this node has potentially changed.
+ */
+ TOUCH,
+
+ /**
+ * This node has been placed into the tree, potentially completely replacing
+ * pre-existing contents.
+ */
+ WRITE,
+
+ /**
+ * This node has been deleted along with any of its child nodes.
+ */
+ DELETE,
+
+ /**
+ * Node has been written into the tree, but instead of replacing pre-existing
+ * contents, it has been merged. This means that any incoming nodes which
+ * were present in the tree have been replaced, but their child nodes have
+ * been retained.
+ */
+ MERGE,
+}
@Override
public boolean apply(final @Nonnull ModifiedNode input) {
Preconditions.checkNotNull(input);
- switch (input.getType()) {
+ switch (input.getOperation()) {
case DELETE:
case MERGE:
case WRITE:
return true;
- case SUBTREE_MODIFIED:
- case UNMODIFIED:
+ case TOUCH:
+ case NONE:
return false;
}
- throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getType()));
+ throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
}
};
private final Map<PathArgument, ModifiedNode> children;
private final Optional<TreeNode> original;
private final PathArgument identifier;
- private ModificationType modificationType = ModificationType.UNMODIFIED;
+ private LogicalOperation operation = LogicalOperation.NONE;
private Optional<TreeNode> snapshotCache;
private NormalizedNode<?, ?> value;
return identifier;
}
- /**
- *
- * Returns original store metadata
- * @return original store metadata
- */
@Override
Optional<TreeNode> getOriginal() {
return original;
}
- /**
- * Returns modification type
- *
- * @return modification type
- */
+
@Override
- ModificationType getType() {
- return modificationType;
+ LogicalOperation getOperation() {
+ return operation;
}
/**
*/
ModifiedNode modifyChild(final PathArgument child, final boolean isOrdered) {
clearSnapshot();
- if (modificationType == ModificationType.UNMODIFIED) {
- updateModificationType(ModificationType.SUBTREE_MODIFIED);
+ if (operation == LogicalOperation.NONE) {
+ updateModificationType(LogicalOperation.TOUCH);
}
final ModifiedNode potential = children.get(child);
if (potential != null) {
* Records a delete for associated node.
*/
void delete() {
- final ModificationType newType;
+ final LogicalOperation newType;
- switch (modificationType) {
+ switch (operation) {
case DELETE:
- case UNMODIFIED:
+ case NONE:
// We need to record this delete.
- newType = ModificationType.DELETE;
+ newType = LogicalOperation.DELETE;
break;
case MERGE:
- case SUBTREE_MODIFIED:
+ case TOUCH:
case WRITE:
/*
* We are canceling a previous modification. This is a bit tricky,
* As documented in BUG-2470, a delete of data introduced in this
* transaction needs to be turned into a no-op.
*/
- newType = original.isPresent() ? ModificationType.DELETE : ModificationType.UNMODIFIED;
+ newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
break;
default:
- throw new IllegalStateException("Unhandled deletion of node with " + modificationType);
+ throw new IllegalStateException("Unhandled deletion of node with " + operation);
}
clearSnapshot();
*/
void write(final NormalizedNode<?, ?> value) {
clearSnapshot();
- updateModificationType(ModificationType.WRITE);
+ updateModificationType(LogicalOperation.WRITE);
children.clear();
this.value = value;
}
void merge(final NormalizedNode<?, ?> value) {
clearSnapshot();
- updateModificationType(ModificationType.MERGE);
+ updateModificationType(LogicalOperation.MERGE);
/*
* Blind overwrite of any previous data is okay, no matter whether the node
final ModifiedNode child = it.next();
child.seal();
- if (child.modificationType == ModificationType.UNMODIFIED) {
+ if (child.operation == LogicalOperation.NONE) {
it.remove();
}
}
- // A SUBTREE_MODIFIED node without any children is a no-op
- if (modificationType == ModificationType.SUBTREE_MODIFIED && children.isEmpty()) {
- updateModificationType(ModificationType.UNMODIFIED);
+ // A TOUCH node without any children is a no-op
+ if (operation == LogicalOperation.TOUCH && children.isEmpty()) {
+ updateModificationType(LogicalOperation.NONE);
}
}
return snapshot;
}
- private void updateModificationType(final ModificationType type) {
- modificationType = type;
+ private void updateModificationType(final LogicalOperation type) {
+ operation = type;
clearSnapshot();
}
@Override
public String toString() {
return "NodeModification [identifier=" + identifier + ", modificationType="
- + modificationType + ", childModification=" + children + "]";
+ + operation + ", childModification=" + children + "]";
}
/**
*/
package org.opendaylight.yangtools.yang.data.impl.schema.tree;
-
import com.google.common.base.Optional;
import java.util.Collection;
import org.opendaylight.yangtools.concepts.Identifiable;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
/**
/**
* Get the type of modification.
*
- * @return Modification type.
+ * @return Operation type.
*/
- abstract ModificationType getType();
+ abstract LogicalOperation getOperation();
/**
* Get the original tree node to which the modification is to be applied.
protected NoopDataTreeCandidate(final YangInstanceIdentifier rootPath, final ModifiedNode modificationRoot) {
super(rootPath);
- Preconditions.checkArgument(modificationRoot.getType() == ModificationType.UNMODIFIED);
+ Preconditions.checkArgument(modificationRoot.getOperation() == LogicalOperation.NONE);
}
@Override
import com.google.common.collect.Iterables;
import java.util.Map;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
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.impl.schema.builder.impl.ImmutableOrderedLeafSetNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableOrderedMapNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
private final Map<YangInstanceIdentifier.PathArgument, ModificationApplyOperation> childNodes;
- public ChoiceModificationStrategy(final ChoiceNode schemaNode) {
- super(org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode.class);
+ public ChoiceModificationStrategy(final ChoiceSchemaNode schemaNode) {
+ super(ChoiceNode.class);
ImmutableMap.Builder<YangInstanceIdentifier.PathArgument, ModificationApplyOperation> child = ImmutableMap.builder();
for (ChoiceCaseNode caze : schemaNode.getCases()) {
@Override
@SuppressWarnings("rawtypes")
protected DataContainerNodeBuilder createBuilder(final NormalizedNode<?, ?> original) {
- checkArgument(original instanceof org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode);
- return ImmutableChoiceNodeBuilder.create((org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode) original);
+ checkArgument(original instanceof ChoiceNode);
+ return ImmutableChoiceNodeBuilder.create((ChoiceNode) original);
}
}
import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
import org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
return new DataNodeContainerModificationStrategy.ContainerModificationStrategy((ContainerSchemaNode) schemaNode);
} else if (schemaNode instanceof ListSchemaNode) {
return fromListSchemaNode((ListSchemaNode) schemaNode);
- } else if (schemaNode instanceof ChoiceNode) {
- return new NormalizedNodeContainerModificationStrategy.ChoiceModificationStrategy((ChoiceNode) schemaNode);
+ } else if (schemaNode instanceof ChoiceSchemaNode) {
+ return new NormalizedNodeContainerModificationStrategy.ChoiceModificationStrategy((ChoiceSchemaNode) schemaNode);
} else if (schemaNode instanceof LeafListSchemaNode) {
return fromLeafListSchemaNode((LeafListSchemaNode) schemaNode);
} else if (schemaNode instanceof LeafSchemaNode) {
@Override
public void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
- if (modification.getType() == ModificationType.WRITE) {
+ if (modification.getOperation() == LogicalOperation.WRITE) {
verifyWrittenStructure(modification.getWrittenValue());
}
}
@Override
public final void checkApplicable(final YangInstanceIdentifier path,final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
- switch (modification.getType()) {
+ switch (modification.getOperation()) {
case DELETE:
checkDeleteApplicable(modification, current);
- case SUBTREE_MODIFIED:
+ case TOUCH:
checkSubtreeModificationApplicable(path, modification, current);
return;
case WRITE:
case MERGE:
checkMergeApplicable(path, modification, current);
return;
- case UNMODIFIED:
+ case NONE:
return;
default:
- throw new UnsupportedOperationException("Suplied modification type "+ modification.getType()+ "is not supported.");
+ throw new UnsupportedOperationException("Suplied modification type "+ modification.getOperation()+ "is not supported.");
}
}
public final Optional<TreeNode> apply(final ModifiedNode modification,
final Optional<TreeNode> currentMeta, final Version version) {
- switch (modification.getType()) {
+ switch (modification.getOperation()) {
case DELETE:
return modification.setSnapshot(Optional.<TreeNode> absent());
- case SUBTREE_MODIFIED:
+ case TOUCH:
Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification",
modification);
return modification.setSnapshot(Optional.of(applySubtreeChange(modification, currentMeta.get(),
return modification.setSnapshot(Optional.of(result));
case WRITE:
return modification.setSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
- case UNMODIFIED:
+ case NONE:
return currentMeta;
default:
throw new IllegalArgumentException("Provided modification type is not supported.");
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.util;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import com.google.common.collect.Iterables;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
-
-/**
- * @deprecated Use one of the {@link NormalizedNodeContainerBuilder} implementations.
- */
-@Deprecated
-public abstract class AbstractCompositeNodeBuilder<P extends CompositeNode> extends AbstractNodeBuilder<P, CompositeNodeBuilder<P>> implements CompositeNodeBuilder<P> {
-
- final List<Node<?>> childNodes;
-
- public AbstractCompositeNodeBuilder() {
- super();
- childNodes = new ArrayList<>();
- }
-
- public AbstractCompositeNodeBuilder(final QName nodeType, final Map<QName, String> attributes) {
- super(nodeType, attributes);
- childNodes = new ArrayList<>();
- }
-
- public AbstractCompositeNodeBuilder(final QName nodeType, final Iterable<? extends Node<?>> nodes) {
- super(nodeType);
- childNodes = new ArrayList<>();
- }
-
- @Override
- public AbstractCompositeNodeBuilder<P> add(final Node<?> node) {
- childNodes.add(checkNotNull(node, "Node should not be null"));
- return this;
- }
-
- @Override
- public AbstractCompositeNodeBuilder<P> addAll(final Iterable<? extends Node<?>> nodes) {
- Iterables.addAll(childNodes, checkNotNull(nodes, "Node should not be null"));
- return this;
- }
-
- @Override
- public CompositeNodeBuilder<P> addLeaf(final String leafLocalName, final String leafValue) {
- return addLeaf(QName.create(getQName(), leafLocalName), leafValue);
- }
-
- public List<Node<?>> getChildNodes() {
- return childNodes;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.util;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public abstract class AbstractNodeBuilder<P extends Node<?>, T extends NodeBuilder<P, T>> implements NodeBuilder<P, T> {
-
- private final Map<QName, String> attributes;
- private QName qName;
-
- public AbstractNodeBuilder() {
- this.attributes = new ConcurrentHashMap<>();
- }
-
- public AbstractNodeBuilder(QName nodeType, Map<QName, String> attributes) {
- super();
- this.qName = nodeType;
- this.attributes = new ConcurrentHashMap<>(attributes);
- }
-
- public AbstractNodeBuilder(QName nodeType) {
- this.qName = nodeType;
- this.attributes = new ConcurrentHashMap<>();
- }
-
- @SuppressWarnings("unchecked")
- protected final T thisInstance() {
- return (T) this;
- }
-
- @Override
- public final T setQName(QName name) {
- this.qName = name;
- return thisInstance();
- }
-
- public QName getQName() {
- return qName;
- }
-
- @Override
- public final T setAttribute(QName attrName, String attrValue) {
- attributes.put(attrName, attrValue);
- return thisInstance();
- }
-
- public Map<QName, String> getAttributes() {
- return attributes;
- }
-
- @Override
- public T setAttribute(String attrName, String attrValue) {
- attributes.put(QName.create(qName, attrName), attrValue);
- return thisInstance();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.util;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-/*
- * @deprecated Use one of the NormalizedNode builders instead.
- */
-@Deprecated
-public interface CompositeNodeBuilder<P extends CompositeNode> extends NodeBuilder<P,CompositeNodeBuilder<P>> {
-
- CompositeNodeBuilder<P> addLeaf(QName leafName,Object leafValue);
- CompositeNodeBuilder<P> add(Node<?> node);
- CompositeNodeBuilder<P> addAll(Iterable<? extends Node<?>> nodes);
- CompositeNodeBuilder<P> addLeaf(String leafLocalName, String leafValue);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.util;
-
-import org.opendaylight.yangtools.concepts.Builder;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface NodeBuilder<P extends Node<?>, T extends NodeBuilder<P, T>> extends Builder<P> {
-
- T setQName(QName name);
-
- QName getQName();
-
- T setAttribute(QName attrName, String attrValue);
-
- T setAttribute(String attrName, String attrValue);
-
- /**
- * @deprecated use {@link #build()}.
- */
- @Deprecated
- P toInstance();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.codec.xml.test;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
-import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-/**
- *
- * @author Lukas Sedlak <lsedlak@cisco.com>
- */
-public class RpcReplyToDomTest {
-
- private static final DocumentBuilderFactory BUILDER_FACTORY;
- private static final String RES_SCHEMA_DIR = "/org/opendaylight/yangtools/yang/data/impl/schema";
-
- private final static String MODEL_NAMESPACE = "org:opendaylight:rpc-reply:test:ns:yang";
- private final static String MODEL_REVISION = "2014-07-17";
-
- private final static QName RPC_OUTPUT_QNAME = QName.create(MODEL_NAMESPACE, MODEL_REVISION, "output");
- private final static QName ROCK_THE_HOUSE_QNAME = QName.create(MODEL_NAMESPACE, MODEL_REVISION, "rock-the-house");
- private final static QName ACTIV_SW_IMAGE_QNAME = QName.create(MODEL_NAMESPACE, MODEL_REVISION, "activate-software-image");
-
- private SchemaContext schemaContext;
- private Document testPayload1;
- private Document testPayload2;
-
- static {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- factory.setCoalescing(true);
- factory.setIgnoringElementContentWhitespace(true);
- factory.setIgnoringComments(true);
- BUILDER_FACTORY = factory;
- }
-
- @Before
- public void setup() throws Exception {
- final List<InputStream> modelsToParse = Collections
- .singletonList(getClass().getResourceAsStream(RES_SCHEMA_DIR + "/rpc-test-model.yang"));
- assertNotNull(modelsToParse);
- assertNotNull(modelsToParse.get(0));
-
- final YangContextParser parser = new YangParserImpl();
- final Set<Module> modules = parser.parseYangModelsFromStreams(modelsToParse);
- assertTrue(!modules.isEmpty());
- schemaContext = parser.resolveSchemaContext(modules);
- assertNotNull(schemaContext);
-
- final InputStream rpcPayloadStream1 = getClass().getResourceAsStream(RES_SCHEMA_DIR + "/rpc-test-payload1.xml");
- InputStream rpcPayloadStream2 = getClass().getResourceAsStream(RES_SCHEMA_DIR + "/rpc-test-payload2.xml");
-
- assertNotNull(rpcPayloadStream1);
- assertNotNull(rpcPayloadStream2);
-
- testPayload1 = readXmlToDocument(rpcPayloadStream1);
- testPayload2 = readXmlToDocument(rpcPayloadStream2);
-
- assertNotNull(testPayload1);
- assertNotNull(testPayload2);
- }
-
- private static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
- DocumentBuilder dBuilder;
- try {
- dBuilder = BUILDER_FACTORY.newDocumentBuilder();
- } catch (ParserConfigurationException e) {
- throw new IllegalStateException("Failed to parse XML document", e);
- }
- Document doc = dBuilder.parse(xmlContent);
-
- doc.getDocumentElement().normalize();
- return doc;
- }
-
- @Test
- public void test() {
- final CompositeNode rockNode = XmlDocumentUtils
- .rpcReplyToDomNodes(testPayload1, ROCK_THE_HOUSE_QNAME, schemaContext);
- assertNotNull(rockNode);
-
- final String namespace = "org:opendaylight:rpc-reply:test:ns:yang";
- final String revision = "2014-07-17";
-
- CompositeNode output = rockNode.getFirstCompositeByName(RPC_OUTPUT_QNAME);
- assertNotNull(output);
-
- final SimpleNode<?> zipCode = output.getFirstSimpleByName(
- QName.create(namespace, revision, "zip-code"));
- assertNotNull(zipCode);
-
- final CompositeNode activNode = XmlDocumentUtils
- .rpcReplyToDomNodes(testPayload2, ACTIV_SW_IMAGE_QNAME, schemaContext);
- assertNotNull(activNode);
-
- output = activNode.getFirstCompositeByName(RPC_OUTPUT_QNAME);
- assertNotNull(output);
-
- final CompositeNode imgProps = output
- .getFirstCompositeByName(QName.create(namespace, revision, "image-properties"));
- assertNotNull(imgProps);
- final CompositeNode imgProperty = imgProps
- .getFirstCompositeByName(QName.create(namespace, revision, "image-property"));
- assertNotNull(imgProperty);
-
- final SimpleNode<?> imgId = imgProperty
- .getFirstSimpleByName(QName.create(namespace, revision, "image-id"));
- assertNotNull(imgId);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.lang.SerializationUtils;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-@Deprecated
-public class CompositeNodeTOImplTest {
- @Test
- public void testSerialization() throws Exception{
- CompositeNodeTOImpl child1 = new CompositeNodeTOImpl(QName.create("ns", "2013-12-09", "child1"), null, new ArrayList<Node<?>>(), ModifyAction.REPLACE);
- CompositeNodeTOImpl child2 = new CompositeNodeTOImpl(QName.create("ns", "2013-12-09", "child2"), null, new ArrayList<Node<?>>(), ModifyAction.REPLACE);
- SimpleNodeTOImpl child3 = new SimpleNodeTOImpl(QName.create("ns", "2013-12-09", "child2"), null, "foo");
-
- List<Node<?>> children = new ArrayList<Node<?>>();
- children.add(child1);
- children.add(child2);
- children.add(child3);
-
- CompositeNodeTOImpl parent = new CompositeNodeTOImpl(QName.create("ns", "2013-12-09", "parent"), null, new ArrayList<Node<?>>(), ModifyAction.REPLACE);
-
- CompositeNodeTOImpl object = new CompositeNodeTOImpl(QName.create("ns", "2013-12-09", "root"), parent, children , ModifyAction.MERGE);
-
- CompositeNodeTOImpl clone = (CompositeNodeTOImpl) SerializationUtils.clone(object);
-
- assertNotNull(clone.getNodeType());
- assertEquals(ModifyAction.MERGE, clone.getModificationAction());
- assertNotNull(clone.getParent());
- assertNotNull(clone.getParent().getNodeType());
- assertNotNull(clone.getValue());
- assertEquals(3, clone.getValue().size());
- assertNotNull(clone.getValue().get(0).getNodeType());
- assertNotNull(clone.getValue().get(1).getNodeType());
-
- SimpleNodeTOImpl child3Clone = (SimpleNodeTOImpl) clone.getValue().get(2);
-
- assertNotNull(child3Clone.getNodeType());
- assertTrue(child3Clone instanceof SimpleNodeTOImpl);
- assertEquals("foo", child3Clone.getValue());
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.net.URI;
-import java.util.Date;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-/**
- * @author michal.rehak
- *
- */
-@Deprecated
-public class LazyNodeToNodeMapTest {
-
- private LazyNodeToNodeMap lazyN2N;
- private CompositeNode tree;
-
- /**
- * prepare test values
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- lazyN2N = new LazyNodeToNodeMap();
-
- QName qName = QName.create(
- new URI("urn:ietf:params:xml:ns:netconf:base:1.0"),
- new Date(42), "yang-data-impl-mutableTest");
-
- tree = NodeHelper.buildTestConfigTree(qName);
- }
-
- /**
- * Test method for {@link org.opendaylight.yangtools.yang.data.impl.LazyNodeToNodeMap#getMutableEquivalent(org.opendaylight.yangtools.yang.data.api.Node)}.
- */
- @Test
- public void testGetMutableEquivalent() {
- MutableCompositeNode mutableTree = (MutableCompositeNode) lazyN2N.getMutableEquivalent(tree);
-
- Assert.assertNull(mutableTree.getParent());
- Assert.assertEquals(tree.getNodeType(), mutableTree.getNodeType());
- Assert.assertEquals(1, lazyN2N.getKeyNodes().size());
-
- Node<?> subNode = tree.getCompositesByName("topologies").iterator().next();
- Node<?> subMutant = lazyN2N.getMutableEquivalent(subNode);
-
- Assert.assertNotNull(subMutant.getParent());
- Assert.assertEquals(subNode.getNodeType(), subMutant.getNodeType());
- Assert.assertEquals(2, lazyN2N.getKeyNodes().size());
-
- Assert.assertEquals(mutableTree, subMutant.getParent());
- Assert.assertEquals(mutableTree.getValue().size(), 1);
- Assert.assertEquals(mutableTree.getValue().iterator().next(), subMutant);
- }
-
- /**
- * Test method for {@link org.opendaylight.yangtools.yang.data.impl.LazyNodeToNodeMap#getMutableRoot()}.
- */
- @Test
- public void testGetMutableRoot() {
- Node<?> subNode = tree.getCompositesByName("topologies").iterator().next();
- Node<?> subMutant = lazyN2N.getMutableEquivalent(subNode);
-
- Assert.assertNotNull(subMutant.getParent());
- Assert.assertEquals(subMutant.getParent(), lazyN2N.getMutableRoot());
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import groovy.util.BuilderSupport;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Date;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author michal.rehak
- */
-@Deprecated
-public class MyNodeBuilder extends BuilderSupport {
-
- private static final Logger LOG = LoggerFactory.getLogger(MyNodeBuilder.class);
-
- private URI qnNamespace;
- private final Date qnRevision;
-
- private CompositeNode rootNode;
-
- /**
- * @param baseQName
- */
- private MyNodeBuilder(final QName baseQName) {
- qnNamespace = baseQName.getNamespace();
- qnRevision = baseQName.getRevision();
- }
-
- /**
- * @return initialized singleton instance
- */
- public static MyNodeBuilder newInstance() {
- QName qName = null;
- try {
- qName = QName.create(
- new URI("urn:opendaylight:controller:network"),
- new Date(42), "node");
- } catch (URISyntaxException e) {
- LOG.error(e.getMessage(), e);
- }
- return new MyNodeBuilder(qName);
- }
-
- @Override
- protected void setParent(final Object parent, final Object child) {
- // do nothing
- if (child instanceof AbstractNodeTO<?>) {
- ((AbstractNodeTO<?>) child).setParent((CompositeNode) parent);
- } else {
- LOG.error("PARENTING FAILED: "+parent + " -> " + child);
- }
- }
-
- @Override
- protected Object createNode(final Object name) {
- MutableCompositeNode newNode = NodeFactory.createMutableCompositeNode(
- createQName(name), getCurrentNode(), null, null, null);
- NodeUtils.fixParentRelation(newNode);
- return newNode;
- }
-
- @Override
- protected Object createNode(final Object name, @SuppressWarnings("rawtypes") final Map attributes) {
- ModifyAction modifyAction = processAttributes(attributes);
- MutableCompositeNode newNode = NodeFactory.createMutableCompositeNode(
- createQName(name), getCurrentNode(), null, modifyAction, null);
- NodeUtils.fixParentRelation(newNode);
- return newNode;
- }
-
-
- @Override
- protected Object createNode(final Object name, @SuppressWarnings("rawtypes") final Map attributes, final Object value) {
- ModifyAction modifyAction = processAttributes(attributes);
- SimpleNode<Object> newNode = NodeFactory.createImmutableSimpleNode(
- createQName(name), (CompositeNode) getCurrent(), value, modifyAction);
- NodeUtils.fixParentRelation(newNode);
- return newNode;
- }
-
- /**
- * @param attributes
- * @return
- */
- private ModifyAction processAttributes(@SuppressWarnings("rawtypes") final Map attributes) {
- LOG.debug("attributes:" + attributes);
- ModifyAction modAction = null;
-
- @SuppressWarnings("unchecked")
- Map<String, String> attributesSane = attributes;
- for (Entry<String, String> attr : attributesSane.entrySet()) {
- switch (attr.getKey()) {
- case "xmlns":
- try {
- qnNamespace = new URI(attr.getValue());
- } catch (URISyntaxException e) {
- LOG.error(e.getMessage(), e);
- }
- break;
- case "modifyAction":
- modAction = ModifyAction.valueOf(attr.getValue());
- break;
-
- default:
- throw new IllegalArgumentException("Attribute not supported: "+attr.getKey());
- }
- }
- return modAction;
- }
-
- @Override
- protected Object createNode(final Object name, final Object value) {
- SimpleNode<Object> newNode = NodeFactory.createImmutableSimpleNode(createQName(name), (CompositeNode) getCurrent(), value);
- NodeUtils.fixParentRelation(newNode);
- return newNode;
- }
-
- private QName createQName(final Object localName) {
- LOG.debug("qname for: "+localName);
- return QName.create(qnNamespace, qnRevision, (String) localName);
- }
-
- protected CompositeNode getCurrentNode() {
- if (getCurrent() != null) {
- if (getCurrent() instanceof CompositeNode) {
- return (CompositeNode) getCurrent();
-
- } else {
- throw new IllegalAccessError("current node is not of type CompositeNode, but: "
- +getCurrent().getClass().getSimpleName());
- }
- }
-
- return null;
- }
-
- @Override
- protected Object postNodeCompletion(final Object parent, final Object node) {
- Node<?> nodeRevisited = (Node<?>) node;
- LOG.debug("postNodeCompletion at: \n "+ nodeRevisited+"\n "+parent);
- if (nodeRevisited instanceof MutableCompositeNode) {
- MutableCompositeNode mutant = (MutableCompositeNode) nodeRevisited;
- if (mutant.getValue().isEmpty()) {
- LOG.error("why is it having empty value? -- " + mutant);
- }
- nodeRevisited = NodeFactory.createImmutableCompositeNode(
- mutant.getNodeType(), mutant.getParent(), mutant.getValue(), mutant.getModificationAction());
- NodeUtils.fixChildrenRelation((CompositeNode) nodeRevisited);
-
- if (parent == null) {
- rootNode = (CompositeNode) nodeRevisited;
- } else {
- NodeUtils.fixParentRelation(nodeRevisited);
- nodeRevisited.getParent().getValue().remove(mutant);
- }
- }
-
-
- return nodeRevisited;
- }
-
- /**
- * @return tree root
- */
- public CompositeNode getRootNode() {
- return rootNode;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModification;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.w3c.dom.Document;
-
-/**
- * @author michal.rehak
- *
- */
-@Deprecated
-public class NodeFactoryTest {
-
- private QName qName;
- private CompositeNode network;
-
- private String ns;
- private Document networkShadow;
-
-
- /**
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- ns = "urn:ietf:params:xml:ns:netconf:base:1.0";
- qName = QName.create(
- new URI(ns),
- new Date(42), "node");
- network = NodeHelper.buildTestConfigTree(qName);
- networkShadow = NodeUtils.buildShadowDomTree(network);
- NodeHelper.compareXmlTree(networkShadow, "./config02-shadow.xml", getClass());
- }
-
- /**
- * Test method for methods creating immutable nodes in
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeFactory}.
- * @throws Exception
- */
- @Test
- public void testImmutableNodes() throws Exception {
- Assert.assertEquals(2, network.getValue().size());
- CompositeNode tpList = NodeUtils.findNodeByXpath(networkShadow,
- NodeHelper.AddNamespaceToPattern(
- "//{0}node[{0}node-id/text()='nodeId_19']/{0}termination-points", ns));
-
-
- Assert.assertEquals(2, tpList.getCompositesByName("termination-point").size());
- }
-
- /**
- * Test method for methods creating immutable and mutable nodes:
- * {@link NodeFactory#createMutableCompositeNode(QName, CompositeNode, List, ModifyAction, CompositeNode)},
- * {@link NodeFactory#createMutableSimpleNode(QName, CompositeNode, Object, ModifyAction, SimpleNode)}
- * @throws Exception
- */
- @Test
- public void testMutableNodes() throws Exception {
- // <config>
- // <top xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
- // <interface xc:operation="delete">
- // <name>Ethernet0/0</name>
- // <mtu>1500</mtu>
- // </interface>
- // <interface>
- // <name>Ethernet0/1</name>
- // <mtu>1501</mtu>
- // </interface>
- // </top>
- // </config>
-
-
- List<Node<?>> value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "name"), null, "Ethernet0/0"));
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "mtu"), null, 1500));
-
- MutableCompositeNode ifNode = NodeFactory.createMutableCompositeNode(
- QName.create(qName, "interface"), null,
- value, ModifyAction.DELETE, null);
- ifNode.init();
- NodeHelper.assignParentToChildren(ifNode);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "name"), null, "Ethernet1/0"));
- value.add(NodeFactory.createMutableSimpleNode(QName.create(qName, "mtu"), null, 1501, ModifyAction.REMOVE, null));
-
- CompositeNode ifNode2 = NodeFactory.createImmutableCompositeNode(QName.create(qName, "interface"), null, value);
- NodeHelper.assignParentToChildren(ifNode2);
-
- value = new ArrayList<Node<?>>();
- value.add(ifNode);
- value.add(ifNode2);
-
- CompositeNode topNode = NodeFactory.createImmutableCompositeNode(QName.create(qName, "top"), null, value);
- NodeHelper.assignParentToChildren(topNode);
- value = new ArrayList<Node<?>>();
- value.add(topNode);
-
- CompositeNode root = NodeFactory.createImmutableCompositeNode(QName.create(qName, "config"), null, value);
- Document shadowConfig = NodeUtils.buildShadowDomTree(root);
- NodeHelper.compareXmlTree(shadowConfig, "./mutableNodesConfig.xml", getClass());
-
- Assert.assertEquals(1, root.getValue().size());
- Assert.assertEquals(1, ifNode.getSimpleNodesByName("name").size());
- Assert.assertEquals(1, ifNode.getSimpleNodesByName("mtu").size());
- Assert.assertEquals(2, topNode.getCompositesByName("interface").size());
- NodeModification interfaceMod = topNode.getCompositesByName("interface").get(0);
- Assert.assertEquals(ModifyAction.DELETE, interfaceMod.getModificationAction());
- }
-
- /**
- * test of {@link NodeFactory#copyDeepAsMutable(CompositeNode, Map)}
- * @throws Exception
- */
- @Test
- public void testCopyDeepAsMutable() throws Exception {
- Map<Node<?>, Node<?>> mutableToOrig = new HashMap<>();
- CompositeNode mutableNetwork = NodeFactory.copyDeepAsMutable(network, mutableToOrig);
-
- Document mutableNetworkShadow = NodeUtils.buildShadowDomTree(mutableNetwork);
-
- NodeHelper.compareXmlTree(mutableNetworkShadow, "./config02-shadow.xml", getClass());
-
- CompositeNode immutableNetwork = NodeFactory.copyDeepAsImmutable(mutableNetwork, null);
- Assert.assertEquals(network, immutableNetwork);
- }
-
-
- /**
- * test of {@link NodeFactory#copyDeepAsImmutable(CompositeNode, Map)}
- * @throws Exception
- */
- @Test
- public void testCopyDeepAsImmutable() throws Exception {
- Map<Node<?>, Node<?>> mutableToOrig = new HashMap<>();
- CompositeNode immutableNetwork = NodeFactory.copyDeepAsImmutable(network, mutableToOrig);
-
- Document mutableNetworkShadow = NodeUtils.buildShadowDomTree(immutableNetwork);
- NodeHelper.compareXmlTree(mutableNetworkShadow, "./config02-shadow.xml", getClass());
-
- Assert.assertEquals(network, immutableNetwork);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import groovy.lang.Binding;
-import groovy.lang.GroovyShell;
-import groovy.lang.Script;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintStream;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.lang.reflect.Method;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import org.custommonkey.xmlunit.Diff;
-import org.junit.Assert;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
-import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use {@link NormalizedNodes} instead.
- */
-@Deprecated
-public abstract class NodeHelper {
-
- private static final Logger LOG = LoggerFactory.getLogger(NodeHelper.class);
-
- /** xml source of example network configuration */
- public static final String NETWORK_XML =
- "<network xmlns=\"urn:opendaylight:controller:network\">\n" +
- //"<network>\n" +
- " <topologies>\n" +
- " <topology>\n" +
- " <topology-id>topId_01</topology-id>\n" +
- " <nodes>\n" +
- " <node>\n" +
- " <node-id>nodeId_02</node-id>\n" +
- " <supporting-ne>networkId_02</supporting-ne>\n" +
- " <termination-points>\n" +
- " <termination-point>\n" +
- " <tp-id>tpId_03</tp-id>\n" +
- " </termination-point>\n" +
- " </termination-points>\n" +
- " </node>\n" +
- " <node>\n" +
- " <node-id>nodeId_16</node-id>\n" +
- " <supporting-ne>networkId_17</supporting-ne>\n" +
- " <termination-points>\n" +
- " <termination-point>\n" +
- " <tp-id>tpId_18</tp-id>\n" +
- " </termination-point>\n" +
- " </termination-points>\n" +
- " </node>\n" +
- " <node>\n" +
- " <node-id>nodeId_19</node-id>\n" +
- " <supporting-ne>networkId_20</supporting-ne>\n" +
- " <termination-points>\n" +
- " <termination-point>\n" +
- " <tp-id>tpId_18</tp-id>\n" +
- " </termination-point>\n" +
- " <termination-point>\n" +
- " <tp-id>tpId_19</tp-id>\n" +
- " </termination-point>\n" +
- " </termination-points>\n" +
- " </node>\n" +
- " </nodes>\n" +
- " <links>\n" +
- " <link>\n" +
- " <link-id>linkId_04</link-id>\n" +
- " <source>\n" +
- " <source-node>nodeId_05</source-node>\n" +
- " <source-tp>tpId_06</source-tp>\n" +
- " </source>\n" +
- " <destination>\n" +
- " <dest-node>nodeId_07</dest-node>\n" +
- " <dest-tp>tpId_08</dest-tp>\n" +
- " </destination>\n" +
- " </link>\n" +
- " <link>\n" +
- " <link-id>linkId_11</link-id>\n" +
- " <source>\n" +
- " <source-node>nodeId_12</source-node>\n" +
- " <source-tp>tpId_13</source-tp>\n" +
- " </source>\n" +
- " <destination>\n" +
- " <dest-node>nodeId_14</dest-node>\n" +
- " <dest-tp>tpId_15</dest-tp>\n" +
- " </destination>\n" +
- " </link>\n" +
- " </links>\n" +
- " </topology>\n" +
- " </topologies>\n" +
- " <network-elements>\n" +
- " <network-element>\n" +
- " <element-id>ntElementId_09</element-id>\n" +
- " </network-element>\n" +
- " <network-element>\n" +
- " <element-id>ntElementId_10</element-id>\n" +
- " </network-element>\n" +
- " </network-elements>\n" +
- "</network>";
-
- private static String domTreeString(final Document domTree) throws TransformerException {
- TransformerFactory transformerFact = TransformerFactory.newInstance();
- transformerFact.setAttribute("indent-number", 4);
- Transformer transformer = transformerFact.newTransformer();
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- //initialize StreamResult with File object to save to file
- StreamResult result = new StreamResult(new StringWriter());
- DOMSource source = new DOMSource(domTree);
- transformer.transform(source, result);
- return result.getWriter().toString();
- }
-
- /**
- * @param domTree
- * @param out
- * @throws Exception
- */
- private static void dumpDoc(final Document domTree, final PrintStream out) throws Exception {
- out.println(domTreeString(domTree));
- }
-
- public static void dumpDoc(final Document domTree, final Logger logger) throws TransformerException {
- logger.info("{}", domTreeString(domTree));
- }
-
- /**
- * @param qName
- * @return example tree, see {@link #NETWORK_XML}
- */
- public static CompositeNode buildTestConfigTree(final QName qName) {
- List<Node<?>> value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "element-id"), null, "ntElementId_09"));
- CompositeNode ntElementNode1 = NodeFactory.createImmutableCompositeNode(QName.create(qName, "network-element"),
- null, value);
- assignParentToChildren(ntElementNode1);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "element-id"), null, "ntElementId_10"));
- CompositeNode ntElementNode2 = NodeFactory.createImmutableCompositeNode(QName.create(qName, "network-element"),
- null, value);
- assignParentToChildren(ntElementNode2);
-
- value = new ArrayList<Node<?>>();
- value.add(ntElementNode1);
- value.add(ntElementNode2);
- CompositeNode ntElementsNode = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "network-elements"), null, value);
- assignParentToChildren(ntElementsNode);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "dest-node"), null, "nodeId_07"));
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "dest-tp"), null, "tpId_08"));
- CompositeNode destination = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "destination"), null,
- value);
- assignParentToChildren(destination);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "source-node"), null, "nodeId_05"));
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "source-tp"), null, "tpId_06"));
- CompositeNode source = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "source"), null, value);
- assignParentToChildren(source);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "link-id"), null, "linkId_04"));
- value.add(source);
- value.add(destination);
- CompositeNode link1 = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "link"), null, value);
- assignParentToChildren(link1);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "dest-node"), null, "nodeId_14"));
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "dest-tp"), null, "tpId_15"));
- destination = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "destination"), null, value);
- assignParentToChildren(destination);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "source-node"), null, "nodeId_12"));
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "source-tp"), null, "tpId_13"));
- source = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "source"), null, value);
- assignParentToChildren(source);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "link-id"), null, "linkId_11"));
- value.add(source);
- value.add(destination);
- CompositeNode link2 = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "link"), null, value);
- assignParentToChildren(link2);
-
- value = new ArrayList<Node<?>>();
- value.add(link1);
- value.add(link2);
- CompositeNode links = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "links"), null, value);
- assignParentToChildren(links);
-
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "tp-id"), null, "tpId_03"));
- CompositeNode terminationPointNode1 = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "termination-point"), null, value);
- assignParentToChildren(terminationPointNode1);
-
- value = new ArrayList<Node<?>>();
- value.add(terminationPointNode1);
- CompositeNode terminationPointsNode = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "termination-points"), null, value);
- assignParentToChildren(terminationPointsNode);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "node-id"), null, "nodeId_02"));
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "supporting-ne"), null, "networkId_02"));
- value.add(terminationPointsNode);
- CompositeNode node1Node = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "node"), null, value);
- assignParentToChildren(node1Node);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "tp-id"), null, "tpId_18"));
- terminationPointNode1 = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "termination-point"),
- null, value);
- assignParentToChildren(terminationPointNode1);
-
- value = new ArrayList<Node<?>>();
- value.add(terminationPointNode1);
- terminationPointsNode = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "termination-points"),
- null, value);
- assignParentToChildren(terminationPointsNode);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "node-id"), null, "nodeId_16"));
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "supporting-ne"), null, "networkId_17"));
- value.add(terminationPointsNode);
- CompositeNode node2Node = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "node"), null, value);
- assignParentToChildren(node2Node);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "tp-id"), null, "tpId_18"));
- terminationPointNode1 = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "termination-point"),
- null, value);
- assignParentToChildren(terminationPointNode1);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "tp-id"), null, "tpId_19"));
- CompositeNode terminationPointNode2 = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "termination-point"), null, value);
- assignParentToChildren(terminationPointNode2);
-
- value = new ArrayList<Node<?>>();
- value.add(terminationPointNode1);
- value.add(terminationPointNode2);
- terminationPointsNode = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "termination-points"),
- null, value);
- assignParentToChildren(terminationPointsNode);
-
- value = new ArrayList<Node<?>>();
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "node-id"), null, "nodeId_19"));
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "supporting-ne"), null, "networkId_20"));
- value.add(terminationPointsNode);
- CompositeNode node3Node = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "node"), null, value);
- assignParentToChildren(node3Node);
-
- value = new ArrayList<Node<?>>();
- value.add(node1Node);
- value.add(node2Node);
- value.add(node3Node);
- CompositeNode nodesNode = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "nodes"), null, value);
- assignParentToChildren(nodesNode);
-
- value = new ArrayList<Node<?>>();
- value.add(links);
- value.add(nodesNode);
- value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "topology-id"), null, "topId_01"));
- CompositeNode topology = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "topology"), null, value);
- assignParentToChildren(topology);
-
- value = new ArrayList<Node<?>>();
- value.add(topology);
- CompositeNode topologies = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "topologies"), null,
- value);
- assignParentToChildren(topologies);
-
- value = new ArrayList<Node<?>>();
- value.add(topologies);
- value.add(ntElementsNode);
- CompositeNode network = NodeFactory.createImmutableCompositeNode(
- QName.create(qName, "network"), null, value);
- assignParentToChildren(network);
-
- return network;
- }
-
- /**
- * @param parentNode
- */
- public static void assignParentToChildren(final CompositeNode parentNode) {
- for (Node<?> child : parentNode.getValue()) {
- ((AbstractNodeTO<?>) child).setParent(parentNode);
- }
- }
-
- /**
- * @return schema context of controller-network.yang
- */
- public static SchemaContext loadSchemaContext() {
- YangModelParser yParser = new YangParserImpl();
- List<InputStream> yangInputStreams = new ArrayList<>();
- yangInputStreams.add(NodeHelper.class.getResourceAsStream(
- "/controller-network.yang"));
- yangInputStreams.add(NodeHelper.class.getResourceAsStream(
- "/ietf-inet-types@2010-09-24.yang"));
- Set<Module> modules = yParser
- .parseYangModelsFromStreams(yangInputStreams);
- return yParser.resolveSchemaContext(modules);
- }
-
- /**
- * @param scriptName
- * @return tree root
- * @throws Exception
- */
- public static CompositeNode loadConfigByGroovy(final String scriptName) throws Exception {
- InputStream configStream = NodeHelper.class.getResourceAsStream(scriptName);
- Binding binding = new Binding();
- GroovyShell gShell = new GroovyShell(binding);
- LOG.debug("groovy: starting script parse.. {}", scriptName);
- Script configScript = gShell.parse(new InputStreamReader(configStream));
- LOG.debug("groovy: starting script.. {}", scriptName);
- configScript.run();
- LOG.debug("groovy: digging result");
- Object xmlGen = binding.getVariable("xmlGen");
- LOG.debug("xmlGen = {}", xmlGen);
- Method getter = xmlGen.getClass().getDeclaredMethod("getBuilder", new Class[0]);
- MyNodeBuilder builder = (MyNodeBuilder) getter.invoke(xmlGen, new Object[0]);
-
- return builder.getRootNode();
- }
-
- /**
- * @param pattern , e.g.: <pre>"//{0}:network/{1}:xx[text() = 'sss']"</pre>
- * @param nsArg , e.g.: <pre>{"uri:ns1", "uri:ns2"}</pre>
- * @return pattern with namespaces: <pre>//uri:ns1:network/uri:ns2:xx[text() = ''sss'']"</pre>
- */
- public static String AddNamespaceToPattern(final String pattern, final Object... nsArg) {
- Object[] ns = nsArg;
- String patternNs = pattern.replaceAll("'", "''");
- if (ns == null) {
- ns = new Object[]{""};
- } else {
- // add ':' into pattern after placeholders
- patternNs = patternNs.replaceAll("(\\{[0-9]+\\})", "$1:");
- }
-
- return MessageFormat.format(patternNs, ns);
- }
-
- /**
- * @param tree
- * @param xmlFile
- * @param clazz
- * @throws Exception
- * @throws SAXException
- * @throws IOException
- */
- public static void compareXmlTree(final Document tree, final String xmlFile, final Class<?> clazz) throws Exception,
- SAXException, IOException {
- ByteArrayOutputStream actualRaw = new ByteArrayOutputStream();
- dumpDoc(tree, new PrintStream(actualRaw));
- Reader actualReader = new InputStreamReader(new ByteArrayInputStream(actualRaw.toByteArray()));
-
- Reader expectedReader = new InputStreamReader(clazz.getResourceAsStream(xmlFile));
- Diff myDiff = new Diff(expectedReader, actualReader);
- myDiff.overrideDifferenceListener(new IgnoreWhiteCharsDiffListener());
-
- boolean similar = myDiff.similar();
- if (! similar) {
- LOG.info("{}", new String(actualRaw.toByteArray()));
- }
- Assert.assertEquals(myDiff.toString(), true, similar);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import static org.junit.Assert.assertSame;
-
-import java.net.URI;
-import java.util.Date;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-
-/**
- * @author michal.rehak
- *
- */
-@Deprecated
-public class NodeModificationBuilderImplTest {
-
- private static final Logger LOG = LoggerFactory.getLogger(NodeModificationBuilderImplTest.class);
-
- private SchemaContext schemaCtx;
- private QName qName;
- private CompositeNode network;
- private NodeModificationBuilderImpl nodeModificationBuilder;
-
- private String ns;
-
- /**
- * @throws Exception
- */
- private void dumpResult() throws Exception {
- CompositeNode diffTree = nodeModificationBuilder.buildDiffTree();
- CompositeNode diffTreeImmutable = NodeFactory.copyDeepAsImmutable(diffTree, null);
-
- Document diffShadow = NodeUtils.buildShadowDomTree(diffTreeImmutable);
- NodeHelper.dumpDoc(diffShadow, LOG);
- }
-
- /**
- * prepare schemaContext
- *
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- schemaCtx = NodeHelper.loadSchemaContext();
-
- ns = "urn:opendaylight:controller:network";
- qName = QName.create(new URI(ns), new Date(1369000800000L), "topos");
- network = NodeHelper.buildTestConfigTree(qName);
-
- nodeModificationBuilder = new NodeModificationBuilderImpl(schemaCtx);
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#getMutableEquivalent(org.opendaylight.yangtools.yang.data.api.Node)}
- * .
- */
- @Test
- public void testGetMutableEquivalent() {
- MutableCompositeNode rootMutable = (MutableCompositeNode) nodeModificationBuilder.getMutableEquivalent(network);
-
- CompositeNode topologies = network.getCompositesByName("topologies").iterator().next();
- Node<?> mutableEquivalent = nodeModificationBuilder.getMutableEquivalent(topologies);
- CompositeNode topologiesMutable = rootMutable.getCompositesByName("topologies").iterator().next();
-
- assertSame(topologiesMutable, mutableEquivalent);
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
- * .
- *
- * @throws Exception
- */
- @Test
- public void testBuildDiffTreeAddSimple() throws Exception {
- LOG.debug("testBuildDiffTreeAddSimple");
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
- CompositeNode needle = NodeUtils.findNodeByXpath(networkShadow,
- NodeHelper.AddNamespaceToPattern("//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]", ns));
-
- MutableCompositeNode mutableParent = (MutableCompositeNode) nodeModificationBuilder
- .getMutableEquivalent(needle);
-
- MutableSimpleNode<String> newMutable = NodeFactory.createMutableSimpleNode(
- QName.create(needle.getNodeType(),
- "anySubNode"), mutableParent, "42", null, null);
-
- nodeModificationBuilder.addNode(newMutable);
- dumpResult();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
- * .
- *
- * @throws Exception
- */
- @Test
- public void testBuildDiffTreeAddComposite() throws Exception {
- LOG.debug("testBuildDiffTreeAddComposite");
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
- CompositeNode needle = NodeUtils.findNodeByXpath(networkShadow,
- NodeHelper.AddNamespaceToPattern("//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]", ns));
-
- MutableCompositeNode mutableParent = (MutableCompositeNode) nodeModificationBuilder
- .getMutableEquivalent(needle);
-
- MutableSimpleNode<String> newMutable = NodeFactory.createMutableSimpleNode(
- QName.create(needle.getNodeType(),
- "anySubNode"), null, "42", null, null);
-
- MutableCompositeNode newMutableCom = NodeFactory.createMutableCompositeNode(
- QName.create(needle.getNodeType(),
- "anySubNode"), mutableParent, NodeUtils.buildChildrenList(newMutable), null, null);
- NodeUtils.fixChildrenRelation(newMutableCom);
- newMutableCom.init();
-
- nodeModificationBuilder.addNode(newMutableCom);
- dumpResult();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
- * .
- *
- * @throws Exception
- */
- @Test
- public void testBuildDiffTreeDeleteComposite() throws Exception {
- LOG.debug("testBuildDiffTreeDeleteComposite");
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
- SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
- "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
- @SuppressWarnings("unchecked")
- MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
- .getMutableEquivalent(needle);
-
- nodeModificationBuilder.deleteNode(mutableNeedle.getParent().asMutable());
- dumpResult();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
- * .
- *
- * @throws Exception
- */
- @Test
- public void testBuildDiffTreeDeleteSimple() throws Exception {
- LOG.debug("testBuildDiffTreeDeleteSimple");
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
- SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
- "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
- @SuppressWarnings("unchecked")
- MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
- .getMutableEquivalent(needle);
-
- nodeModificationBuilder.deleteNode(mutableNeedle);
- dumpResult();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
- * .
- *
- * @throws Exception
- */
- @Test
- public void testBuildDiffTreeMerge() throws Exception {
- LOG.debug("testBuildDiffTreeMerge");
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
- SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
- "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
- @SuppressWarnings("unchecked")
- MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
- .getMutableEquivalent(needle);
-
- mutableNeedle.setValue("tpId_18x");
- nodeModificationBuilder.mergeNode(mutableNeedle.getParent().asMutable());
- dumpResult();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
- * .
- *
- * @throws Exception
- */
- @Test
- public void testBuildDiffTreeRemoveComposite() throws Exception {
- LOG.debug("testBuildDiffTreeRemoveComposite");
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
- SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
- "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
- @SuppressWarnings("unchecked")
- MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
- .getMutableEquivalent(needle);
-
- nodeModificationBuilder.removeNode(mutableNeedle.getParent().asMutable());
- dumpResult();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
- * .
- *
- * @throws Exception
- */
- @Test
- public void testBuildDiffTreeRemoveSimple() throws Exception {
- LOG.debug("testBuildDiffTreeRemoveSimple");
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
- SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
- "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
- @SuppressWarnings("unchecked")
- MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
- .getMutableEquivalent(needle);
-
- nodeModificationBuilder.removeNode(mutableNeedle);
- dumpResult();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
- * .
- *
- * @throws Exception
- */
- @Test
- public void testBuildDiffTreeReplaceComposite() throws Exception {
- LOG.debug("testBuildDiffTreeReplaceComposite");
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
- SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
- "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
- @SuppressWarnings("unchecked")
- MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
- .getMutableEquivalent(needle);
-
- mutableNeedle.setValue("tpId_18x");
- nodeModificationBuilder.replaceNode(mutableNeedle.getParent().asMutable());
- dumpResult();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
- * .
- *
- * @throws Exception
- */
- @Test
- public void testBuildDiffTreeReplaceSimple() throws Exception {
- LOG.debug("testBuildDiffTreeReplaceSimple");
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
- SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
- "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
- @SuppressWarnings("unchecked")
- MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
- .getMutableEquivalent(needle);
-
- mutableNeedle.setValue("tpId_18x");
- nodeModificationBuilder.replaceNode(mutableNeedle);
- dumpResult();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.io.IOException;
-import java.net.URI;
-import java.util.Date;
-import java.util.Deque;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-
-/**
- * @author michal.rehak
- *
- */
-@Deprecated
-public class NodeUtilsTest {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(NodeUtilsTest.class);
-
- private QName qName;
- private CompositeNode network;
-
- private String ns;
-
-
- /**
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- ns = "urn:ietf:params:xml:ns:netconf:base:1.0";
- qName = QName.create(
- new URI(ns),
- new Date(42), "yang-data-impl-mutableTest");
- network = NodeHelper.buildTestConfigTree(qName);
- }
-
- /**
- * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#buildPath(org.opendaylight.yangtools.yang.data.api.Node)}.
- * @throws Exception
- */
- @Test
- public void testBuildPath() throws Exception {
- SimpleNode<?> needle = network.getCompositesByName("topologies").iterator().next()
- .getCompositesByName("topology").iterator().next()
- .getSimpleNodesByName("topology-id").iterator().next();
- String breadCrumbs = NodeUtils.buildPath(needle);
-
- Assert.assertEquals("network.topologies.topology.topology-id", breadCrumbs);
- }
-
- /**
- * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#buildShadowDomTree(org.opendaylight.yangtools.yang.data.api.CompositeNode)}.
- * @throws Exception
- */
- @Test
- public void testBuildShadowDomTree() throws Exception {
- MemoryConsumption mc = new MemoryConsumption();
- mc.startObserving();
-
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
-
- LOG.debug("After dom built: "+mc.finishObserving());
- NodeHelper.compareXmlTree(networkShadow, "./config02-shadow.xml", getClass());
- }
-
- /**
- * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#findNodeByXpath(org.w3c.dom.Document, java.lang.String)}.
- * @throws Exception
- */
- @Test
- public void testFindNodeByXpath() throws Exception {
- Document networkShadow = NodeUtils.buildShadowDomTree(network);
- MemoryConsumption mc = new MemoryConsumption();
- mc.startObserving();
-
- SimpleNode<String> needle = NodeUtils.findNodeByXpath(networkShadow,
- NodeHelper.AddNamespaceToPattern(
- "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
- LOG.debug("After xpath executed: "+mc.finishObserving());
-
- Assert.assertNotNull(needle);
- Assert.assertEquals("tpId_18", needle.getValue());
- }
-
- /**
- * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#buildNodeMap(java.util.List)}.
- */
- @Test
- public void testBuildNodeMap() {
- CompositeNode topology = network.getCompositesByName("topologies").iterator().next()
- .getCompositesByName("topology").iterator().next();
-
- Map<QName, List<Node<?>>> nodeMap = NodeUtils.buildNodeMap(topology.getValue());
- Assert.assertEquals(3, nodeMap.size());
- }
-
- /**
- * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#buildMapOfListNodes(org.opendaylight.yangtools.yang.model.api.SchemaContext)}.
- */
- @Test
- public void testBuildMapOfListNodes() {
- SchemaContext schemaCtx = NodeHelper.loadSchemaContext();
- Map<String, ListSchemaNode> mapOfLists = NodeUtils.buildMapOfListNodes(schemaCtx);
- Assert.assertEquals(5, mapOfLists.size());
- }
-
- /**
- * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#buildMapOfListNodes(org.opendaylight.yangtools.yang.model.api.SchemaContext)}.
- * @throws Exception
- * @throws IOException
- */
- @Test
- public void testLoadConfigByGroovy() throws IOException, Exception {
- CompositeNode treeRoot = NodeHelper.loadConfigByGroovy("./config02.groovy");
- Document shadowTree = NodeUtils.buildShadowDomTree(treeRoot);
- try {
- checkFamilyBinding(treeRoot);
- } catch (Exception e) {
- LOG.error(e.getMessage());
- throw e;
- }
-
- NodeHelper.compareXmlTree(shadowTree, "./config02g-shadow.xml", getClass());
- }
-
- private static void checkFamilyBinding(final CompositeNode treeRoot) throws Exception {
- Deque<CompositeNode> jobQueue = new LinkedList<>();
- jobQueue.push(treeRoot);
-
- while (!jobQueue.isEmpty()) {
- CompositeNode job = jobQueue.pop();
- for (Node<?> child : job.getValue()) {
- if (child instanceof CompositeNode) {
- jobQueue.push((CompositeNode) child);
- }
-
- if (job != child.getParent()) {
- throw new Exception("binding mismatch occured: \nPARENT["+job+"]\n CHILD[" + child+"]\n +-> "+child.getParent());
- }
- }
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.net.URI;
-import java.util.List;
-
-import javax.xml.stream.XMLStreamException;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-
-/**
- * The class <code>XmlTreeBuilderTest</code> contains tests for the class
- * {@link <code>XmlTreeBuilder</code>}
- *
- * @author Lukas Sedlak
- */
-public class XmlTreeBuilderTest {
-
- private InputStream inputStream;
-
- /**
- * Perform pre-test initialization
- *
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- final URI inputFile = getClass().getResource("/rpc-getDeviceEquipment.xml").toURI();
- inputStream = new FileInputStream(new File(inputFile));
- }
-
- /**
- * Run the Node<?> buildDataTree(InputStream) method test
- */
- @SuppressWarnings("unchecked")
- @Test
- public void testBuildDataTree()
- {
- Node<?> rootNode = null;
- try {
- rootNode = XmlTreeBuilder.buildDataTree(inputStream);
- } catch (XMLStreamException e) {
- e.printStackTrace();
- }
- assertNotNull(rootNode);
- assertTrue(rootNode instanceof CompositeNode);
-
- CompositeNode compRootNode = (CompositeNode)rootNode;
- assertNotNull(compRootNode.getValue());
-
- SimpleNode<String> methodName = null;
- SimpleNode<String> emptyTag = null;
- CompositeNode params = null;
- for (final Node<?> childNode : compRootNode.getValue()) {
- if (childNode instanceof SimpleNode) {
- if ("emptyTag".equals(childNode.getNodeType().getLocalName())) {
- emptyTag = (SimpleNode<String>) childNode;
- } else if ("methodName".equals(childNode.getNodeType().getLocalName())) {
- methodName = (SimpleNode<String>) childNode;
- }
-
- } else if (childNode instanceof CompositeNode) {
- params = (CompositeNode) childNode;
- }
- }
-
- assertNotNull(methodName);
- assertNotNull(params);
- assertTrue(emptyTag.getValue().isEmpty());
- assertEquals(methodName.getValue(), "getDeviceEquipment");
-
- String deviceId = null;
- String deviceIP = null;
- for (final Node<?> param : params.getValue()) {
- if (param instanceof CompositeNode) {
- final Node<?> valueNode = ((CompositeNode) param).getValue().get(0);
-
- assertTrue(valueNode instanceof CompositeNode);
- final CompositeNode value = (CompositeNode) valueNode;
- final Node<?> stringNode = value.getValue().get(0);
- assertTrue(stringNode instanceof SimpleNode);
-
- final SimpleNode<String> string = (SimpleNode<String>) stringNode;
- if ("DeviceID123".equals(string.getValue())) {
- deviceId = string.getValue();
- } else if ("172.23.218.75".equals(string.getValue())) {
- deviceIP = string.getValue();
- }
- }
- }
-
- assertNotNull(deviceId);
- assertNotNull(deviceIP);
- }
-
- @Test
- public void nodeMapInCompositeNodeTest() {
- Node<?> rootNode = null;
- try {
- rootNode = XmlTreeBuilder.buildDataTree(inputStream);
- } catch (XMLStreamException e) {
- e.printStackTrace();
- }
-
- CompositeNode compRootNode = (CompositeNode)rootNode;
- List<CompositeNode> params = compRootNode.getCompositesByName("params");
- assertEquals(1, params.size());
- List<CompositeNode> compositesByName = params.get(0).getCompositesByName("param");
- assertEquals(2, compositesByName.size());
- }
-}
package org.opendaylight.yangtools.yang.data.impl.codec.xml;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
import com.google.common.base.Charsets;
-import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.io.ByteSource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
-import javax.activation.UnsupportedDataTypeException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
-import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
import org.w3c.dom.Document;
-import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class XmlDocumentUtilsTest {
public static final String XML_CONTENT = "<input xmlns=\"urn:opendaylight:controller:rpc:test\">\n" +
"<a>value</a>\n" +
- "<ref xmlns:ltha=\"urn:opendaylight:controller:rpc:test\">/ltha:cont/ltha:l[ltha:id='id']</ref>\n" +
+ "<ref xmlns:ltha=\"urn:opendaylight:controller:rpc:test\">"+
+ "/ltha:cont/ltha:l[ ltha:id='id/foo/bar' ]"+
+ "</ref>\n" +
"</input>";
public static final String RPC_REPLY = "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"m-1\">\n" +
testRpc = rpcTestModule.getRpcs().iterator().next();
}
- @Test
- public void testRpcInputTransform() throws Exception {
-
- final Document inputDocument = readXmlToDocument(XML_CONTENT);
- final Element input = inputDocument.getDocumentElement();
-
- final CompositeNode node = inputXmlToCompositeNode(input);
- final SimpleNode<?> refParsed = node.getSimpleNodesByName("ref").iterator().next();
- assertEquals(YangInstanceIdentifier.class, refParsed.getValue().getClass());
- final Document serializedDocument = inputCompositeNodeToXml(node);
-
- XMLUnit.compareXML(inputDocument, serializedDocument);
- }
-
- @Test
- public void testRpcReplyToDom() throws Exception {
- final Document reply = readXmlToDocument(RPC_REPLY);
- final CompositeNode domNodes = XmlDocumentUtils.rpcReplyToDomNodes(reply, QName.create("urn:opendaylight:controller:rpc:test", "2014-07-28", "test"), schema);
- assertEquals(1, domNodes.getValue().size());
- final Node<?> outputNode = domNodes.getValue().get(0);
- assertTrue(outputNode instanceof CompositeNode);
- assertEquals(1, ((CompositeNode) outputNode).getValue().size());
- final Node<?> okNode = ((CompositeNode) outputNode).getValue().get(0);
- assertEquals("ok", okNode.getNodeType().getLocalName());
- }
-
public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
}
doc.getDocumentElement().normalize();
return doc;
}
-
- public Document inputCompositeNodeToXml(final CompositeNode cNode)
- throws UnsupportedDataTypeException {
- return XmlDocumentUtils.toDocument(cNode, testRpc.getInput(), XmlDocumentUtils.defaultValueCodecProvider());
- }
-
- public CompositeNode inputXmlToCompositeNode(final Element e) {
- return (CompositeNode) XmlDocumentUtils.toDomNode(e, Optional.<DataSchemaNode>of(testRpc.getInput()),
- Optional.of(XmlDocumentUtils.defaultValueCodecProvider()), Optional.of(schema));
- }
}
import java.net.URISyntaxException;
import java.util.AbstractMap;
import java.util.Arrays;
-import java.util.Collections;
import java.util.Map;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
return targetBaseType;
}
- @Test
- public void testEmptyNodeWithAttribute() throws Exception {
- final ByteArrayOutputStream out = new ByteArrayOutputStream();
- final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);
-
- final Map<QName, String> attrs = Maps.newHashMap();
- attrs.put(QName.create("namespaceAttr", "2012-12-12", "attr1"), "value");
- final QName qName = QName.create("urn:opendaylight:controller:rpc:test", "2014-07-28", "cont");
- final ImmutableCompositeNode dataAttributes = ImmutableCompositeNode.create(qName, attrs, Collections.<Node<?>>emptyList());
- XmlStreamUtils.create(XmlUtils.DEFAULT_XML_CODEC_PROVIDER).writeDocument(writer, dataAttributes);
-
- writer.close();
- out.close();
-
- final String xmlAsString = new String(out.toByteArray());
-
- // TODO why resulting xml does not have namespace definition ? If sending xml by e.g. netconf the namespace is there but not here in test
- final String expectedXmlAsString = "<cont xmlns:a=\"namespaceAttr\" a:attr1=\"value\"></cont>";
-
- XMLUnit.setIgnoreAttributeOrder(true);
- final Document control = XMLUnit.buildControlDocument(expectedXmlAsString);
- final Document test = XMLUnit.buildTestDocument(xmlAsString);
- final Diff diff = XMLUnit.compareXML(control, test);
-
- final boolean identical = diff.identical();
- assertTrue("Xml differs: " + diff.toString(), identical);
- }
-
private Map<String, String> mapPrefixed(final Iterable<Map.Entry<URI, String>> prefixes) {
final Map<String, String> mappedPrefixes = Maps.newHashMap();
for (final Map.Entry<URI, String> prefix : prefixes) {
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
-
import java.io.InputStream;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Set;
-
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
+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.LeafNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableChoiceNodeSchemaAwareBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeSchemaAwareBuilder;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
LeafSchemaNode augumentString1SchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "augmentString1");
LeafSchemaNode augumentString2SchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "augmentString2");
- ChoiceNode choice1SchemaNode = (ChoiceNode) getSchemaNode(schema, "test", "choice");
- org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode choice = ImmutableChoiceNodeSchemaAwareBuilder
+ ChoiceSchemaNode choice1SchemaNode = (ChoiceSchemaNode) getSchemaNode(schema, "test", "choice");
+ ChoiceNode choice = ImmutableChoiceNodeSchemaAwareBuilder
.create(choice1SchemaNode)
.withChild(Builders.<String> leafBuilder(augumentString1SchemaNode).withValue("case1").build())
// This should fail, since child node belongs to different case
}
if (dataSchemaNode instanceof DataNodeContainer) {
containers.add((DataNodeContainer) dataSchemaNode);
- } else if (dataSchemaNode instanceof ChoiceNode) {
- containers.addAll(((ChoiceNode) dataSchemaNode).getCases());
+ } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
+ containers.addAll(((ChoiceSchemaNode) dataSchemaNode).getCases());
}
}
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
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.stream.NormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedDataBuilderTest;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(Parameterized.class)
public class NormalizedNodeXmlTranslationTest {
private static final Logger logger = LoggerFactory.getLogger(NormalizedNodeXmlTranslationTest.class);
+ private final SchemaContext schema;
@Parameterized.Parameters()
public static Collection<Object[]> data() {
});
}
-
public static final String NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test";
private static Date revision;
static {
try {
revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-03-13");
- } catch (ParseException e) {
+ } catch (final ParseException e) {
throw new RuntimeException(e);
}
}
private static ContainerNode withAttributes() {
- DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
b.withNodeIdentifier(getNodeIdentifier("container"));
- CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder().withNodeIdentifier(
+ final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder().withNodeIdentifier(
getNodeIdentifier("list"));
- Map<QName, Object> predicates = Maps.newHashMap();
+ final Map<QName, Object> predicates = Maps.newHashMap();
predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L);
- DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> list1Builder = Builders
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> list1Builder = Builders
.mapEntryBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifierWithPredicates(getNodeIdentifier("list").getNodeType(),
predicates));
- NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier,Object,LeafNode<Object>> uint32InListBuilder
+ final NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier,Object,LeafNode<Object>> uint32InListBuilder
= Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("uint32InList"));
list1Builder.withChild(uint32InListBuilder.withValue(3L).build());
listBuilder.withChild(list1Builder.build());
b.withChild(listBuilder.build());
- NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> booleanBuilder
+ final NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> booleanBuilder
= Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean"));
booleanBuilder.withValue(false);
b.withChild(booleanBuilder.build());
- ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder
+ final ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder
= Builders.leafSetBuilder().withNodeIdentifier(getNodeIdentifier("leafList"));
- NormalizedNodeBuilder<YangInstanceIdentifier.NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder
+ final NormalizedNodeBuilder<YangInstanceIdentifier.NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder
= Builders.leafSetEntryBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeWithValue(getNodeIdentifier("leafList").getNodeType(), "a"));
leafList1Builder.withValue("a");
private static ContainerNode augmentChoiceHell() {
- DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
b.withNodeIdentifier(getNodeIdentifier("container"));
b.withChild(
}
public static YangInstanceIdentifier.AugmentationIdentifier getAugmentIdentifier(final String... childNames) {
- Set<QName> qn = Sets.newHashSet();
+ final Set<QName> qn = Sets.newHashSet();
- for (String childName : childNames) {
+ for (final String childName : childNames) {
qn.add(getNodeIdentifier(childName).getNodeType());
}
}
public NormalizedNodeXmlTranslationTest(final String yangPath, final String xmlPath, final ContainerNode expectedNode) {
- SchemaContext schema = parseTestSchema(yangPath);
+ schema = parseTestSchema(yangPath);
this.xmlPath = xmlPath;
this.containerNode = (ContainerSchemaNode) NormalizedDataBuilderTest.getSchemaNode(schema, "test", "container");
this.expectedNode = expectedNode;
SchemaContext parseTestSchema(final String... yangPath) {
- YangParserImpl yangParserImpl = new YangParserImpl();
- Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(getTestYangs(yangPath));
+ final YangParserImpl yangParserImpl = new YangParserImpl();
+ final Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(getTestYangs(yangPath));
return yangParserImpl.resolveSchemaContext(modules);
}
new Function<String, InputStream>() {
@Override
public InputStream apply(final String input) {
- InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(input);
+ final InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(input);
Preconditions.checkNotNull(resourceAsStream, "File %s was null", resourceAsStream);
return resourceAsStream;
}
@Test
public void testTranslation() throws Exception {
- Document doc = loadDocument(xmlPath);
+ final Document doc = loadDocument(xmlPath);
- ContainerNode built =
- DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider()).getContainerNodeParser().parse(
+ final ContainerNode built =
+ DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schema).getContainerNodeParser().parse(
Collections.singletonList(doc.getDocumentElement()), containerNode);
if (expectedNode != null) {
org.junit.Assert.assertEquals(expectedNode, built);
}
+ System.err.println(built);
logger.info("{}", built);
- Iterable<Element> els = DomFromNormalizedNodeSerializerFactory.getInstance(XmlDocumentUtils.getDocument(), DomUtils.defaultValueCodecProvider())
- .getContainerNodeSerializer().serialize(containerNode, built);
-
- Element el = els.iterator().next();
+ final Element elementNS = XmlDocumentUtils.getDocument().createElementNS(containerNode.getQName().getNamespace().toString(), containerNode.getQName().getLocalName());
+ writeNormalizedNode(built, new DOMResult(elementNS), SchemaPath.create(true), schema);
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreComments(true);
+ XMLUnit.setIgnoreAttributeOrder(true);
+ XMLUnit.setNormalize(true);
+
System.err.println(toString(doc.getDocumentElement()));
- System.err.println(toString(el));
+ System.err.println(toString(elementNS));
+
+ final Diff diff = new Diff(XMLUnit.buildControlDocument(toString(doc.getDocumentElement())), XMLUnit.buildTestDocument(toString(elementNS)));
+
+ // FIXME the comparison cannot be performed, since the qualifiers supplied by XMlUnit do not work correctly in this case
+ // We need to implement custom qualifier so that the element ordering does not mess the DIFF
+// dd.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(100, true));
+// assertTrue(dd.toString(), dd.similar());
+ }
+
- boolean diff = new Diff(XMLUnit.buildControlDocument(toString(doc.getDocumentElement())), XMLUnit.buildTestDocument(toString(el))).similar();
+ static final XMLOutputFactory XML_FACTORY;
+ static {
+ XML_FACTORY = XMLOutputFactory.newFactory();
+ XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
+ }
+
+ private void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext context)
+ throws IOException, XMLStreamException {
+ NormalizedNodeWriter normalizedNodeWriter = null;
+ NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
+ XMLStreamWriter writer = null;
+ try {
+ writer = XML_FACTORY.createXMLStreamWriter(result);
+ normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
+ normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter);
+
+ normalizedNodeWriter.write(normalized);
+
+ normalizedNodeWriter.flush();
+ } finally {
+ if(normalizedNodeWriter != null) {
+ normalizedNodeWriter.close();
+ }
+ if(normalizedNodeStreamWriter != null) {
+ normalizedNodeStreamWriter.close();
+ }
+ if(writer != null) {
+ writer.close();
+ }
+ }
}
private Document loadDocument(final String xmlPath) throws Exception {
- InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(xmlPath);
+ final InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(xmlPath);
- Document currentConfigElement = readXmlToDocument(resourceAsStream);
+ final Document currentConfigElement = readXmlToDocument(resourceAsStream);
Preconditions.checkNotNull(currentConfigElement);
return currentConfigElement;
}
private static final DocumentBuilderFactory BUILDERFACTORY;
static {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setCoalescing(true);
factory.setIgnoringElementContentWhitespace(true);
}
private Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException {
- DocumentBuilder dBuilder;
+ final DocumentBuilder dBuilder;
try {
dBuilder = BUILDERFACTORY.newDocumentBuilder();
- } catch (ParserConfigurationException e) {
+ } catch (final ParserConfigurationException e) {
throw new RuntimeException("Failed to parse XML document", e);
}
- Document doc = dBuilder.parse(xmlContent);
+ final Document doc = dBuilder.parse(xmlContent);
doc.getDocumentElement().normalize();
return doc;
public static String toString(final Element xml) {
try {
- Transformer transformer = TransformerFactory.newInstance().newTransformer();
+ final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- StreamResult result = new StreamResult(new StringWriter());
- DOMSource source = new DOMSource(xml);
+ final StreamResult result = new StreamResult(new StringWriter());
+ final DOMSource source = new DOMSource(xml);
transformer.transform(source, result);
return result.getWriter().toString();
<containerInList name="inContainer">
<uint32>32</uint32>
<uint16>16</uint16>
+ <identityr xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:test">prefix:b</identityr>
+ <anyX xmlns="urn:opendaylight:params:xml:ns:yang:controller:test">direct Value</anyX>
+ <uint16-ref>16</uint16-ref>
+ <instance-id xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:test">/prefix:container/prefix:list[prefix:uint32InList="1"]</instance-id>
</containerInList>
<stringAugmentedToList>augmentInList</stringAugmentedToList>
<stringAugmentedToListInCase1>augmentInListCase1</stringAugmentedToListInCase1>
<containerInList>
<uint32>32</uint32>
<uint16>16</uint16>
+ <identityr>b</identityr>
+ <anyX>
+ <container xmlns="randomNamespace" xmlns:pref="prefixed:namespace">
+ <pref:boolean>true</pref:boolean>
+ <innerContainer xmlns:p="prefixed:namespace">
+ <uint16 xmlns:pref2="prefixed:namespace">pref2:44</uint16>
+ </innerContainer>
+ </container>
+ <container2 xmlns="randomNamespace2"/>
+ </anyX>
</containerInList>
<!--<stringAugmentedToListInCase1>augmentInListCase1</stringAugmentedToListInCase1>-->
<stringAugmentedToListInCase2>augmentInListCase2</stringAugmentedToListInCase2>
</list>
+ <list>
+ <uint32InList>4</uint32InList>
+ <containerInList>
+ <anyX>
+ <netconf-state xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring">
+ <schemas>
+ <schema>
+ <identifier>module</identifier>
+ <version>2012-12-12</version>
+ <format xmlns:x="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring">x:yang</format>
+ </schema>
+ </schemas>
+ </netconf-state>
+ </anyX>
+ </containerInList>
+ </list>
<list>
<uint32InList>3</uint32InList>
</list>
"Initial revision";
}
+ identity a {}
+
+ identity b {
+ base "test:a";
+ }
+
grouping listGroup {
list list {
key "uint32InList";
leaf uint16 {
type uint16;
}
+
+ leaf identityr {
+ type identityref {
+ base "test:a";
+ }
+ }
+
+ leaf uint16-ref {
+ type leafref {
+ path "../uint16";
+ }
+ }
+
+ leaf instance-id {
+ type instance-identifier;
+ }
+
+ anyxml anyX;
}
}
}
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
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.UnkeyedListNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<?>> implements Modification<S, N> {
@Override
- public final Optional<N> modify(S schema, Optional<N> actual, Optional<N> modification,
- OperationStack operationStack) throws DataModificationException {
+ public final Optional<N> modify(final S schema, final Optional<N> actual, final Optional<N> modification,
+ final OperationStack operationStack) throws DataModificationException {
operationStack.enteringNode(modification);
protected abstract QName getQName(S schema);
- private Optional<N> modifyContainer(S schema, Optional<N> actual, Optional<N> modification,
- OperationStack operationStack) throws DataModificationException {
+ private Optional<N> modifyContainer(final S schema, final Optional<N> actual, final Optional<N> modification,
+ final OperationStack operationStack) throws DataModificationException {
if (!actual.isPresent()) {
return modification;
return build(schema, merged);
}
- private List<? extends DataContainerChild<?, ?>> modifyContainerChildNodes(S schema, OperationStack operationStack,
- N actual, N modification, Set<YangInstanceIdentifier.PathArgument> toProcess) throws DataModificationException {
+ private List<? extends DataContainerChild<?, ?>> modifyContainerChildNodes(final S schema, final OperationStack operationStack,
+ final N actual, final N modification, final Set<YangInstanceIdentifier.PathArgument> toProcess) throws DataModificationException {
List<DataContainerChild<?, ?>> result = Lists.newArrayList();
for (YangInstanceIdentifier.PathArgument childToProcessId : toProcess) {
return result;
}
- private Optional<? extends DataContainerChild<?, ?>> modifyContainerNode(OperationStack operationStack, N actual,
- N modification, YangInstanceIdentifier.PathArgument childToProcess, Object schemaChild)
+ private Optional<? extends DataContainerChild<?, ?>> modifyContainerNode(final OperationStack operationStack, final N actual,
+ final N modification, final YangInstanceIdentifier.PathArgument childToProcess, final Object schemaChild)
throws DataModificationException {
Optional<DataContainerChild<?, ?>> storedChildren = actual.getChild(childToProcess);
return NodeDispatcher.dispatchChildModification(schemaChild, storedChildren, modifiedChildren, operationStack);
}
- private Object findSchema(S schema, YangInstanceIdentifier.PathArgument childToProcessId) {
+ private Object findSchema(final S schema, final YangInstanceIdentifier.PathArgument childToProcessId) {
if (childToProcessId instanceof YangInstanceIdentifier.AugmentationIdentifier) {
return findSchemaForAugment(schema, (YangInstanceIdentifier.AugmentationIdentifier) childToProcessId);
} else {
protected abstract Object findSchemaForAugment(S schema, YangInstanceIdentifier.AugmentationIdentifier childToProcessId);
- private Optional<N> build(S schema, List<? extends DataContainerChild<?, ?>> result) {
+ private Optional<N> build(final S schema, final List<? extends DataContainerChild<?, ?>> result) {
DataContainerNodeBuilder<?, N> b = getBuilder(schema);
// TODO skip empty container nodes ? e.g. if container looses all its child nodes
protected abstract DataContainerNodeBuilder<?, N> getBuilder(S schema);
- protected Set<YangInstanceIdentifier.PathArgument> getChildrenToProcess(S schema, Optional<N> actual,
- Optional<N> modification) throws DataModificationException {
+ protected Set<YangInstanceIdentifier.PathArgument> getChildrenToProcess(final S schema, final Optional<N> actual,
+ final Optional<N> modification) throws DataModificationException {
Set<YangInstanceIdentifier.PathArgument> qNames = Sets.newLinkedHashSet();
qNames.addAll(getChildQNames(actual));
return qNames;
}
- private Set<? extends YangInstanceIdentifier.PathArgument> getChildQNames(Optional<N> actual) {
+ private Set<? extends YangInstanceIdentifier.PathArgument> getChildQNames(final Optional<N> actual) {
Set<YangInstanceIdentifier.PathArgument> qNames = Sets.newLinkedHashSet();
for (DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> child : actual.get().getValue()) {
private static final LeafSetNodeModification LEAF_SET_NODE_MODIFICATION = new LeafSetNodeModification();
private static final AugmentationNodeModification AUGMENTATION_NODE_MODIFICATION = new AugmentationNodeModification();
private static final MapNodeModification MAP_NODE_MODIFICATION = new MapNodeModification();
+ private static final UnkeyedListNodeModification UNKEYED_LIST_NODE_MODIFICATION = new UnkeyedListNodeModification();
private static final ContainerNodeModification CONTAINER_NODE_MODIFICATION = new ContainerNodeModification();
private static final ChoiceNodeModification CHOICE_NODE_MODIFICATION = new ChoiceNodeModification();
- static Optional<? extends DataContainerChild<?, ?>> dispatchChildModification(Object schemaChild,
- Optional<DataContainerChild<?, ?>> actual, Optional<DataContainerChild<?, ?>> modification,
- OperationStack operations) throws DataModificationException {
+ static Optional<? extends DataContainerChild<?, ?>> dispatchChildModification(final Object schemaChild,
+ final Optional<DataContainerChild<?, ?>> actual, final Optional<DataContainerChild<?, ?>> modification,
+ final OperationStack operations) throws DataModificationException {
if (schemaChild instanceof LeafSchemaNode) {
return onLeafNode((LeafSchemaNode) schemaChild, actual, modification, operations);
} else if (schemaChild instanceof AugmentationSchema) {
return onAugmentationNode((AugmentationSchema) schemaChild, actual, modification, operations);
} else if (schemaChild instanceof ListSchemaNode) {
- return onMapNode((ListSchemaNode) schemaChild, actual, modification, operations);
- } else if (schemaChild instanceof org.opendaylight.yangtools.yang.model.api.ChoiceNode) {
- return onChoiceNode((org.opendaylight.yangtools.yang.model.api.ChoiceNode) schemaChild, actual,
+ if (((ListSchemaNode)schemaChild).getKeyDefinition().isEmpty()) {
+ return onUnkeyedNode((ListSchemaNode) schemaChild, actual, modification, operations);
+ } else {
+ return onMapNode((ListSchemaNode) schemaChild, actual, modification, operations);
+ }
+ } else if (schemaChild instanceof ChoiceSchemaNode) {
+ return onChoiceNode((ChoiceSchemaNode) schemaChild, actual,
modification, operations);
}
}
private static Optional<? extends DataContainerChild<?, ?>> onChoiceNode(
- org.opendaylight.yangtools.yang.model.api.ChoiceNode schemaChild,
- Optional<? extends DataContainerChild<?, ?>> actual,
- Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+ final ChoiceSchemaNode schemaChild,
+ final Optional<? extends DataContainerChild<?, ?>> actual,
+ final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
throws DataModificationException {
checkType(actual, ChoiceNode.class);
checkType(modification, ChoiceNode.class);
(Optional<ChoiceNode>) modification, operations);
}
- private static Optional<? extends DataContainerChild<?, ?>> onMapNode(ListSchemaNode schemaChild,
- Optional<? extends DataContainerChild<?, ?>> actual,
- Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+ private static Optional<? extends DataContainerChild<?, ?>> onMapNode(final ListSchemaNode schemaChild,
+ final Optional<? extends DataContainerChild<?, ?>> actual,
+ final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
throws DataModificationException {
checkType(actual, MapNode.class);
checkType(modification, MapNode.class);
(Optional<MapNode>) modification, operations);
}
- private static Optional<? extends DataContainerChild<?, ?>> onAugmentationNode(AugmentationSchema schemaChild,
- Optional<? extends DataContainerChild<?, ?>> actual,
- Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+ private static Optional<? extends DataContainerChild<?, ?>> onUnkeyedNode(final ListSchemaNode schemaChild,
+ final Optional<? extends DataContainerChild<?, ?>> actual,
+ final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
+ throws DataModificationException {
+ checkType(actual, UnkeyedListNode.class);
+ checkType(modification, UnkeyedListNode.class);
+ return UNKEYED_LIST_NODE_MODIFICATION.modify(schemaChild, (Optional<UnkeyedListNode>) actual,
+ (Optional<UnkeyedListNode>) modification, operations);
+ }
+
+ private static Optional<? extends DataContainerChild<?, ?>> onAugmentationNode(final AugmentationSchema schemaChild,
+ final Optional<? extends DataContainerChild<?, ?>> actual,
+ final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
throws DataModificationException {
checkType(actual, AugmentationNode.class);
checkType(modification, AugmentationNode.class);
(Optional<AugmentationNode>) modification, operations);
}
- private static Optional<? extends DataContainerChild<?, ?>> onLeafSetNode(LeafListSchemaNode schemaChild,
- Optional<? extends DataContainerChild<?, ?>> actual,
- Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+ private static Optional<? extends DataContainerChild<?, ?>> onLeafSetNode(final LeafListSchemaNode schemaChild,
+ final Optional<? extends DataContainerChild<?, ?>> actual,
+ final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
throws DataModificationException {
checkType(actual, LeafSetNode.class);
checkType(modification, LeafSetNode.class);
(Optional<LeafSetNode<?>>) modification, operations);
}
- private static Optional<? extends DataContainerChild<?, ?>> onContainerNode(ContainerSchemaNode schemaChild,
- Optional<? extends DataContainerChild<?, ?>> actual,
- Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+ private static Optional<? extends DataContainerChild<?, ?>> onContainerNode(final ContainerSchemaNode schemaChild,
+ final Optional<? extends DataContainerChild<?, ?>> actual,
+ final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
throws DataModificationException {
checkType(actual, ContainerNode.class);
checkType(modification, ContainerNode.class);
(Optional<ContainerNode>) modification, operations);
}
- private static Optional<? extends DataContainerChild<?, ?>> onLeafNode(LeafSchemaNode schemaChild,
- Optional<? extends DataContainerChild<?, ?>> actual,
- Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+ private static Optional<? extends DataContainerChild<?, ?>> onLeafNode(final LeafSchemaNode schemaChild,
+ final Optional<? extends DataContainerChild<?, ?>> actual,
+ final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
throws DataModificationException {
checkType(actual, LeafNode.class);
checkType(modification, LeafNode.class);
(Optional<LeafNode<?>>) modification, operations);
}
- private static void checkType(Optional<? extends DataContainerChild<?, ?>> actual, Class<?> leafNodeClass) {
+ private static void checkType(final Optional<? extends DataContainerChild<?, ?>> actual, final Class<?> leafNodeClass) {
if (actual.isPresent()) {
Preconditions.checkArgument(leafNodeClass.isAssignableFrom(actual.get().getClass()),
"Unexpected node type, should be: %s, but was: %s, for: %s", leafNodeClass, actual.getClass(),
import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
-final class ChoiceNodeModification extends
- AbstractContainerNodeModification<ChoiceNode, org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> {
+final class ChoiceNodeModification extends AbstractContainerNodeModification<ChoiceSchemaNode, ChoiceNode> {
@Override
- protected QName getQName(ChoiceNode schema) {
+ protected QName getQName(final ChoiceSchemaNode schema) {
return schema.getQName();
}
@Override
- protected Object findSchemaForChild(ChoiceNode schema, QName nodeType) {
+ protected Object findSchemaForChild(final ChoiceSchemaNode schema, final QName nodeType) {
return SchemaUtils.findSchemaForChild(schema, nodeType);
}
@Override
- protected Set<YangInstanceIdentifier.PathArgument> getChildrenToProcess(ChoiceNode schema,
- Optional<org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> actual,
- Optional<org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> modification)
+ protected Set<YangInstanceIdentifier.PathArgument> getChildrenToProcess(final ChoiceSchemaNode schema,
+ final Optional<ChoiceNode> actual,
+ final Optional<ChoiceNode> modification)
throws DataModificationException {
Set<YangInstanceIdentifier.PathArgument> childrenToProcess = super.getChildrenToProcess(schema, actual,
modification);
return childrenToProcessFiltered;
}
- private boolean belongsToCase(ChoiceCaseNode detectedCase, YangInstanceIdentifier.PathArgument childToProcess) {
+ private boolean belongsToCase(final ChoiceCaseNode detectedCase, final YangInstanceIdentifier.PathArgument childToProcess) {
return detectedCase.getDataChildByName(childToProcess.getNodeType()) != null;
}
@Override
- protected Object findSchemaForAugment(ChoiceNode schema, YangInstanceIdentifier.AugmentationIdentifier childToProcessId) {
+ protected Object findSchemaForAugment(final ChoiceSchemaNode schema, final YangInstanceIdentifier.AugmentationIdentifier childToProcessId) {
return SchemaUtils.findSchemaForAugment(schema, childToProcessId.getPossibleChildNames());
}
@Override
- protected DataContainerNodeBuilder<?, org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> getBuilder(
- ChoiceNode schema) {
+ protected DataContainerNodeBuilder<?, ChoiceNode> getBuilder(
+ final ChoiceSchemaNode schema) {
return Builders.choiceBuilder(schema);
}
}
package org.opendaylight.yangtools.yang.data.operations;
import com.google.common.base.Optional;
-
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
super(String.format("Data missing for node: %s", nodeType), nodeType);
}
- public DataMissingException(final QName nodeType, final Node<?> modificationNode) {
- super(String.format("Data missing for node: %s, %s", nodeType, modificationNode), nodeType);
- }
-
public DataMissingException(final QName nodeType, final NormalizedNode<?, ?> modificationNode) {
super(String.format("Data missing for node: %s, %s", nodeType, modificationNode), nodeType);
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.operations;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
+import java.util.List;
+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.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+public class UnkeyedListNodeModification implements Modification<ListSchemaNode, UnkeyedListNode> {
+
+ public static final MapEntryNodeModification MAP_ENTRY_NODE_MODIFICATION = new MapEntryNodeModification();
+
+ @Override
+ public Optional<UnkeyedListNode> modify(ListSchemaNode schema, Optional<UnkeyedListNode> actual,
+ Optional<UnkeyedListNode> modification, OperationStack operationStack) throws DataModificationException {
+
+ // Merge or None operation on parent, leaving actual if modification not present
+ if (modification.isPresent() == false)
+ return actual;
+
+ List<UnkeyedListEntryNode> resultNodes = Lists.newArrayList();
+ if (actual.isPresent())
+ resultNodes = unkeyedListEntries(actual.get());
+
+ // TODO implement ordering for modification nodes
+
+ for (UnkeyedListEntryNode unkeyedListEntryModification : modification.get().getValue()) {
+
+ operationStack.enteringNode(unkeyedListEntryModification);
+
+ YangInstanceIdentifier.NodeIdentifier entryKey = unkeyedListEntryModification.getIdentifier();
+
+ switch (operationStack.getCurrentOperation()) {
+ case NONE:
+ break;
+ // DataModificationException.DataMissingException.check(schema.getQName(), actual, mapEntryModification);
+ case MERGE:
+ case CREATE: {
+ DataModificationException.DataExistsException.check(schema.getQName(), actual,
+ unkeyedListEntryModification);
+ resultNodes.add(unkeyedListEntryModification);
+ }
+ case REPLACE: {
+ break;
+ }
+ case DELETE: {
+ // DataModificationException.DataMissingException.check(schema.getQName(), actual,
+ // unkeyedListEntryModification);
+ break;
+ }
+ case REMOVE: {
+ break;
+ }
+ default:
+ throw new UnsupportedOperationException(
+ String.format("Unable to perform operation: %s on: %s, unknown",
+ operationStack.getCurrentOperation(), schema));
+ }
+
+ operationStack.exitingNode(unkeyedListEntryModification);
+ }
+ return build(schema, resultNodes);
+ }
+
+ private Optional<UnkeyedListNode> build(ListSchemaNode schema, List<UnkeyedListEntryNode> resultNodes) {
+ if (resultNodes.isEmpty())
+ return Optional.absent();
+
+ CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> b = Builders.unkeyedListBuilder();
+ b.withNodeIdentifier(new NodeIdentifier(schema.getQName()));
+
+ for (UnkeyedListEntryNode child : resultNodes) {
+ b.withChild(child);
+ }
+
+ return Optional.of(b.build());
+ }
+
+ private List<UnkeyedListEntryNode> unkeyedListEntries(UnkeyedListNode unkeyedListNode) {
+ List<UnkeyedListEntryNode> unkeyedListEntries = Lists.newArrayList();
+
+ for (UnkeyedListEntryNode unkeyedListEntryNode : unkeyedListNode.getValue()) {
+ unkeyedListEntries.add(unkeyedListEntryNode);
+ }
+
+ return unkeyedListEntries;
+ }
+
+}
protected final Optional<ContainerNode> currentConfig;
protected final Optional<ContainerNode> modification;
protected final ModifyAction modifyAction;
+ private final SchemaContext schema;
@Parameterized.Parameters()
public static Collection<Object[]> data() {
}
public YangDataOperationsTest(final String testDir) throws Exception {
- SchemaContext schema = parseTestSchema();
+ schema = parseTestSchema();
containerNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
this.testDirName = testDir;
Document currentConfigElement = readXmlToDocument(resourceAsStream);
Preconditions.checkNotNull(currentConfigElement);
- return Optional.of(DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider()).getContainerNodeParser().parse(
+ return Optional.of(DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schema).getContainerNodeParser().parse(
Collections.singletonList(currentConfigElement.getDocumentElement()), containerNode));
}
<groupId>${project.groupId}</groupId>
<artifactId>yang-data-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>yang-model-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>yang-model-util</artifactId>
+ </dependency>
</dependencies>
</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.util;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-
-/**
- * @deprecated Use one of the {@link NormalizedNodeContainer} implementation packages.
- */
-@Deprecated
-public abstract class AbstractContainerNode extends AbstractNode<List<Node<?>>> implements CompositeNode {
-
- @Override
- public SimpleNode<?> getFirstSimpleByName(final QName leaf) {
- List<SimpleNode<?>> list = getSimpleNodesByName(leaf);
- if (list.size() == 0) {
- return null;
- }
- return list.get(0);
- }
-
- protected AbstractContainerNode(final QName name, final CompositeNode parent) {
- super(name, parent);
- }
-
- public AbstractContainerNode(final QName name) {
- super(name, null);
- }
-
- @Override
- public List<Node<?>> getChildren() {
- return getValue();
- }
-
- @Override
- public List<Node<?>> getValue() {
- Map<QName, List<Node<?>>> map = getNodeMap();
- if (map == null) {
- throw new IllegalStateException("nodeMap should not be null");
- }
- List<Node<?>> ret = new ArrayList<Node<?>>();
- Collection<List<Node<?>>> values = map.values();
- for (List<Node<?>> list : values) {
- ret.addAll(list);
- }
- return ret;
- }
-
- protected abstract Map<QName, List<Node<?>>> getNodeMap();
-
- @Override
- public List<CompositeNode> getCompositesByName(final QName children) {
- Map<QName, List<Node<?>>> map = getNodeMap();
- if (map == null) {
- throw new IllegalStateException("nodeMap should not be null");
- }
- List<Node<?>> toFilter = map.get(children);
- List<CompositeNode> list = new ArrayList<CompositeNode>();
- for (Node<?> node : toFilter) {
- if (node instanceof CompositeNode) {
- list.add((CompositeNode) node);
- }
- }
- return list;
- }
-
- @Override
- public List<SimpleNode<?>> getSimpleNodesByName(final QName children) {
- Map<QName, List<Node<?>>> map = getNodeMap();
- if (map == null) {
- throw new IllegalStateException("nodeMap should not be null");
- }
- List<Node<?>> toFilter = map.get(children);
- List<SimpleNode<?>> list = new ArrayList<SimpleNode<?>>();
-
- for (Node<?> node : toFilter) {
- if (node instanceof SimpleNode<?>) {
- list.add((SimpleNode<?>) node);
- }
- }
- return list;
- }
-
- @Override
- public CompositeNode getFirstCompositeByName(final QName container) {
- List<CompositeNode> list = getCompositesByName(container);
- if (list.size() == 0) {
- return null;
- }
- return list.get(0);
- }
-
- public SimpleNode<?> getFirstLeafByName(final QName leaf) {
- List<SimpleNode<?>> list = getSimpleNodesByName(leaf);
- if (list.size() == 0) {
- return null;
- }
- return list.get(0);
- }
-
- @Override
- public List<CompositeNode> getCompositesByName(final String children) {
- return getCompositesByName(localQName(children));
- }
-
- @Override
- public List<SimpleNode<?>> getSimpleNodesByName(final String children) {
- return getSimpleNodesByName(localQName(children));
- }
-
- private QName localQName(final String str) {
- return QName.create(getNodeType(), str);
- }
-}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+abstract class AbstractInteriorContextNode<T extends PathArgument> extends
+ DataSchemaContextNode<T> {
+
+ protected AbstractInteriorContextNode(final T identifier, final DataSchemaNode schema) {
+ super(identifier, schema);
+ }
+
+ @Override
+ public boolean isLeaf() {
+ return false;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+abstract class AbstractLeafNodeContext<T extends PathArgument> extends DataSchemaContextNode<T> {
+
+ protected AbstractLeafNodeContext(final T identifier, final DataSchemaNode potential) {
+ super(identifier, potential);
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final PathArgument child) {
+ return null;
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final QName child) {
+ return null;
+ }
+
+ @Override
+ public boolean isLeaf() {
+ return true;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+abstract class AbstractMixinContextNode<T extends PathArgument> extends
+ AbstractInteriorContextNode<T> {
+
+ protected AbstractMixinContextNode(final T identifier, final DataSchemaNode schema) {
+ super(identifier, schema);
+ }
+
+ @Override
+ public final boolean isMixin() {
+ return true;
+ }
+
+}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.util;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
-@Deprecated
-public abstract class AbstractNode<T> implements Node<T> {
-
- private final QName nodeName;
- private final CompositeNode parent;
-
- protected AbstractNode(final QName name, final CompositeNode parent) {
- nodeName = name;
- this.parent = parent;
- }
-
- @Override
- public QName getNodeType() {
- return this.nodeName;
- }
-
- @Override
- public CompositeNode getParent() {
- return parent;
- }
-
- /* (non-Javadoc)
- */
- /**
- * @see org.opendaylight.yangtools.yang.data.api.NodeModification#getModificationAction()
- */
- public ModifyAction getModificationAction() {
- // TODO Auto-generated method stub
- return null;
- }
-}
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
-import com.google.common.base.Splitter;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
+import javax.annotation.Nonnull;
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.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
*/
@Beta
public abstract class AbstractStringInstanceIdentifierCodec extends AbstractNamespaceCodec implements InstanceIdentifierCodec<String> {
- private static final Pattern PREDICATE_PATTERN = Pattern.compile("\\[(.*?)\\]");
- private static final Splitter SLASH_SPLITTER = Splitter.on('/');
@Override
public final String serialize(final YangInstanceIdentifier data) {
StringBuilder sb = new StringBuilder();
+ DataSchemaContextNode<?> current = getDataContextTree().getRoot();
for (PathArgument arg : data.getPathArguments()) {
- if(arg instanceof AugmentationIdentifier) {
+ current = current.getChild(arg);
+
+ if(current.isMixin()) {
/*
* XML/YANG instance identifier does not have concept
- * of augmentation identifier, which identifies
- * mixin (same as paretn element), so we can safely
- * ignore it if it is part of path (since child node)
- * is identified in same fashion.
+ * of augmentation identifier, or list as whole which
+ * identifies mixin (same as paretn element),
+ * so we can safely ignore it if it is part of path
+ * (since child node) is identified in same fashion.
*
*/
continue;
sb.append("']");
}
}
-
return sb.toString();
}
+ /**
+ *
+ * Returns DataSchemaContextTree associated with SchemaContext for which
+ * serialization / deserialization occurs.
+ *
+ * Implementations MUST provide non-null Data Tree context, in order
+ * for correct serialization / deserialization of PathArguments,
+ * since XML representation does not have Augmentation arguments
+ * and does not provide path arguments for cases.
+ *
+ * This effectively means same input XPath representation of Path Argument
+ * may result in different YangInstanceIdentifiers if models are different
+ * in uses of choices and cases.
+ *
+ * @return DataSchemaContextTree associated with SchemaContext for which
+ * serialization / deserialization occurs.
+ */
+ protected abstract @Nonnull DataSchemaContextTree getDataContextTree();
+
@Override
public final YangInstanceIdentifier deserialize(final String data) {
Preconditions.checkNotNull(data, "Data may not be null");
-
- final Iterator<String> xPathParts = SLASH_SPLITTER.split(data).iterator();
-
- // must be at least "/pr:node"
- if (!xPathParts.hasNext() || !xPathParts.next().isEmpty() || !xPathParts.hasNext()) {
- return null;
- }
-
- List<PathArgument> result = new ArrayList<>();
- while (xPathParts.hasNext()) {
- String xPathPartTrimmed = xPathParts.next().trim();
-
- PathArgument pathArgument = toPathArgument(xPathPartTrimmed);
- if (pathArgument != null) {
- result.add(pathArgument);
- }
- }
- return YangInstanceIdentifier.create(result);
+ XpathStringParsingPathArgumentBuilder builder = new XpathStringParsingPathArgumentBuilder(this, data);
+ return YangInstanceIdentifier.create(builder.build());
}
- private PathArgument toPathArgument(final String xPathArgument) {
- final QName mainQName = parseQName(xPathArgument);
-
- // predicates
- final Matcher matcher = PREDICATE_PATTERN.matcher(xPathArgument);
- final Map<QName, Object> predicates = new LinkedHashMap<>();
- QName currentQName = mainQName;
-
- while (matcher.find()) {
- final String predicateStr = matcher.group(1).trim();
- final int indexOfEqualityMark = predicateStr.indexOf('=');
- if (indexOfEqualityMark != -1) {
- final String predicateValue = toPredicateValue(predicateStr.substring(indexOfEqualityMark + 1));
- if (predicateValue == null) {
- return null;
- }
-
- if (predicateStr.charAt(0) != '.') {
- // target is not a leaf-list
- currentQName = parseQName(predicateStr.substring(0, indexOfEqualityMark));
- if (currentQName == null) {
- return null;
- }
- }
- predicates.put(currentQName, predicateValue);
- }
- }
-
- if (predicates.isEmpty()) {
- return new YangInstanceIdentifier.NodeIdentifier(mainQName);
- } else {
- return new YangInstanceIdentifier.NodeIdentifierWithPredicates(mainQName, predicates);
- }
- }
-
- private static String toPredicateValue(final String predicatedValue) {
- final String predicatedValueTrimmed = predicatedValue.trim();
- if (predicatedValue.isEmpty()) {
- return null;
- }
-
- switch (predicatedValueTrimmed.charAt(0)) {
- case '"':
- return trimIfEndIs(predicatedValueTrimmed, '"');
- case '\'':
- return trimIfEndIs(predicatedValueTrimmed, '\'');
- default:
- return null;
- }
- }
-
- private static String trimIfEndIs(final String str, final char end) {
- final int l = str.length() - 1;
- if (str.charAt(l) != end) {
- return null;
- }
-
- return str.substring(1, l);
- }
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+
+class AnyXmlContextNode extends DataSchemaContextNode<NodeIdentifier> {
+
+ protected AnyXmlContextNode(final AnyXmlSchemaNode schema) {
+ super(new NodeIdentifier(schema.getQName()), schema);
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final PathArgument child) {
+ return null;
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final QName child) {
+ return null;
+ }
+
+ @Override
+ public boolean isLeaf() {
+ return false;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import java.util.Set;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+final class AugmentationContextNode extends
+ DataContainerContextNode<AugmentationIdentifier> {
+
+ public AugmentationContextNode(final AugmentationSchema augmentation, final DataNodeContainer schema) {
+ // super();
+ super(augmentationIdentifierFrom(augmentation), augmentationProxy(augmentation, schema), null);
+ }
+
+ @Override
+ public boolean isMixin() {
+ return true;
+ }
+
+ @Override
+ protected DataSchemaContextNode<?> fromLocalSchemaAndQName(final DataNodeContainer schema, final QName child) {
+ DataSchemaNode result = findChildSchemaNode(schema, child);
+ // We try to look up if this node was added by augmentation
+ if ((schema instanceof DataSchemaNode) && result.isAugmenting()) {
+ return fromAugmentation(schema, (AugmentationTarget) schema, result);
+ }
+ return fromDataSchemaNode(result);
+ }
+
+ @Override
+ protected Set<QName> getQNameIdentifiers() {
+ return getIdentifier().getPossibleChildNames();
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import com.google.common.collect.ImmutableMap;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+class ChoiceNodeContextNode extends AbstractMixinContextNode<NodeIdentifier> {
+
+ private final ImmutableMap<QName, DataSchemaContextNode<?>> byQName;
+ private final ImmutableMap<PathArgument, DataSchemaContextNode<?>> byArg;
+
+ protected ChoiceNodeContextNode(final ChoiceSchemaNode schema) {
+ super(new NodeIdentifier(schema.getQName()), schema);
+ ImmutableMap.Builder<QName, DataSchemaContextNode<?>> byQNameBuilder = ImmutableMap.builder();
+ ImmutableMap.Builder<PathArgument, DataSchemaContextNode<?>> byArgBuilder = ImmutableMap.builder();
+
+ for (ChoiceCaseNode caze : schema.getCases()) {
+ for (DataSchemaNode cazeChild : caze.getChildNodes()) {
+ DataSchemaContextNode<?> childOp = fromDataSchemaNode(cazeChild);
+ byArgBuilder.put(childOp.getIdentifier(), childOp);
+ for (QName qname : childOp.getQNameIdentifiers()) {
+ byQNameBuilder.put(qname, childOp);
+ }
+ }
+ }
+ byQName = byQNameBuilder.build();
+ byArg = byArgBuilder.build();
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final PathArgument child) {
+ return byArg.get(child);
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final QName child) {
+ return byQName.get(child);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+
+final class ContainerContextNode extends DataContainerContextNode<NodeIdentifier> {
+
+ protected ContainerContextNode(final ContainerSchemaNode schema) {
+ super(new NodeIdentifier(schema.getQName()), schema, schema);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+class DataContainerContextNode<T extends PathArgument> extends
+ AbstractInteriorContextNode<T> {
+
+ private final DataNodeContainer schema;
+ private final Map<QName, DataSchemaContextNode<?>> byQName;
+ private final Map<PathArgument, DataSchemaContextNode<?>> byArg;
+
+ protected DataContainerContextNode(final T identifier, final DataNodeContainer schema,
+ final DataSchemaNode node) {
+ super(identifier, node);
+ this.schema = schema;
+ this.byArg = new ConcurrentHashMap<>();
+ this.byQName = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final PathArgument child) {
+ DataSchemaContextNode<?> potential = byArg.get(child);
+ if (potential != null) {
+ return potential;
+ }
+ potential = fromLocalSchema(child);
+ return register(potential);
+ }
+
+ private DataSchemaContextNode<?> fromLocalSchema(final PathArgument child) {
+ if (child instanceof AugmentationIdentifier) {
+ return fromSchemaAndQNameChecked(schema, ((AugmentationIdentifier) child).getPossibleChildNames()
+ .iterator().next());
+ }
+ return fromSchemaAndQNameChecked(schema, child.getNodeType());
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final QName child) {
+ DataSchemaContextNode<?> potential = byQName.get(child);
+ if (potential != null) {
+ return potential;
+ }
+ potential = fromLocalSchemaAndQName(schema, child);
+ return register(potential);
+ }
+
+ protected DataSchemaContextNode<?> fromLocalSchemaAndQName(final DataNodeContainer schema2, final QName child) {
+ return fromSchemaAndQNameChecked(schema2, child);
+ }
+
+ private DataSchemaContextNode<?> register(final DataSchemaContextNode<?> potential) {
+ if (potential != null) {
+ byArg.put(potential.getIdentifier(), potential);
+ for (QName qName : potential.getQNameIdentifiers()) {
+ byQName.put(qName, potential);
+ }
+ }
+ return potential;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableSet;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.concepts.Identifiable;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+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.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
+
+/**
+ * Schema derived data providing necessary information for mapping
+ * between {@link org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode}
+ * and serialization format defined in RFC6020, since the mapping
+ * is not one-to-one.
+ *
+ * @param <T> Path Argument type
+ *
+ */
+public abstract class DataSchemaContextNode<T extends PathArgument> implements Identifiable<T> {
+
+ private final T identifier;
+ private final DataSchemaNode dataSchemaNode;
+
+ @Override
+ public T getIdentifier() {
+ return identifier;
+ };
+
+ protected DataSchemaContextNode(final T identifier, final SchemaNode schema) {
+ super();
+ this.identifier = identifier;
+ if (schema instanceof DataSchemaNode) {
+ this.dataSchemaNode = (DataSchemaNode) schema;
+ } else {
+ this.dataSchemaNode = null;
+ }
+ }
+
+ public boolean isMixin() {
+ return false;
+ }
+
+ public boolean isKeyedEntry() {
+ return false;
+ }
+
+ protected Set<QName> getQNameIdentifiers() {
+ return Collections.singleton(identifier.getNodeType());
+ }
+
+ public abstract @Nullable DataSchemaContextNode<?> getChild(final PathArgument child);
+
+ public abstract @Nullable DataSchemaContextNode<?> getChild(QName child);
+
+ public abstract boolean isLeaf();
+
+
+ public @Nullable DataSchemaNode getDataSchemaNode() {
+ return dataSchemaNode;
+ }
+
+ static final DataSchemaNode findChildSchemaNode(final DataNodeContainer parent, final QName child) {
+ DataSchemaNode potential = parent.getDataChildByName(child);
+ if (potential == null) {
+ Iterable<ChoiceSchemaNode> choices = FluentIterable.from(
+ parent.getChildNodes()).filter(ChoiceSchemaNode.class);
+ potential = findChoice(choices, child);
+ }
+ return potential;
+ }
+
+ static DataSchemaContextNode<?> fromSchemaAndQNameChecked(final DataNodeContainer schema, final QName child) {
+ DataSchemaNode result = findChildSchemaNode(schema, child);
+ // We try to look up if this node was added by augmentation
+ if ((schema instanceof DataSchemaNode) && result.isAugmenting()) {
+ return fromAugmentation(schema, (AugmentationTarget) schema, result);
+ }
+ return fromDataSchemaNode(result);
+ }
+
+ private static ChoiceSchemaNode findChoice(final Iterable<ChoiceSchemaNode> choices, final QName child) {
+ ChoiceSchemaNode foundChoice = null;
+ choiceLoop: for (ChoiceSchemaNode choice : choices) {
+ for (ChoiceCaseNode caze : choice.getCases()) {
+ if (findChildSchemaNode(caze, child) != null) {
+ foundChoice = choice;
+ break choiceLoop;
+ }
+ }
+ }
+ return foundChoice;
+ }
+
+ public static AugmentationIdentifier augmentationIdentifierFrom(final AugmentationSchema augmentation) {
+ ImmutableSet.Builder<QName> potentialChildren = ImmutableSet.builder();
+ for (DataSchemaNode child : augmentation.getChildNodes()) {
+ potentialChildren.add(child.getQName());
+ }
+ return new AugmentationIdentifier(potentialChildren.build());
+ }
+
+ static DataNodeContainer augmentationProxy(final AugmentationSchema augmentation,
+ final DataNodeContainer schema) {
+ Set<DataSchemaNode> children = new HashSet<>();
+ for (DataSchemaNode augNode : augmentation.getChildNodes()) {
+ children.add(schema.getDataChildByName(augNode.getQName()));
+ }
+ return new EffectiveAugmentationSchema(augmentation, children);
+ }
+
+ /**
+ * Returns a DataContextNodeOperation for provided child node
+ *
+ * If supplied child is added by Augmentation this operation returns a
+ * DataContextNodeOperation for augmentation, otherwise returns a
+ * DataContextNodeOperation for child as call for
+ * {@link #fromDataSchemaNode(DataSchemaNode)}.
+ *
+ *
+ * @param parent
+ * @param parentAug
+ * @param child
+ * @return
+ */
+ static @Nullable DataSchemaContextNode<?> fromAugmentation(final DataNodeContainer parent,
+ final AugmentationTarget parentAug, final DataSchemaNode child) {
+ AugmentationSchema augmentation = null;
+ for (AugmentationSchema aug : parentAug.getAvailableAugmentations()) {
+ DataSchemaNode potential = aug.getDataChildByName(child.getQName());
+ if (potential != null) {
+ augmentation = aug;
+ break;
+ }
+ }
+ if (augmentation != null) {
+ return new AugmentationContextNode(augmentation, parent);
+ }
+ return fromDataSchemaNode(child);
+ }
+
+ public static @Nullable DataSchemaContextNode<?> fromDataSchemaNode(final DataSchemaNode potential) {
+ if (potential instanceof ContainerSchemaNode) {
+ return new ContainerContextNode((ContainerSchemaNode) potential);
+ } else if (potential instanceof ListSchemaNode) {
+ return fromListSchemaNode((ListSchemaNode) potential);
+ } else if (potential instanceof LeafSchemaNode) {
+ return new LeafContextNode((LeafSchemaNode) potential);
+ } else if (potential instanceof ChoiceSchemaNode) {
+ return new ChoiceNodeContextNode((ChoiceSchemaNode) potential);
+ } else if (potential instanceof LeafListSchemaNode) {
+ return fromLeafListSchemaNode((LeafListSchemaNode) potential);
+ } else if (potential instanceof AnyXmlSchemaNode) {
+ return new AnyXmlContextNode((AnyXmlSchemaNode) potential);
+ }
+ return null;
+ }
+
+ private static DataSchemaContextNode<?> fromListSchemaNode(final ListSchemaNode potential) {
+ List<QName> keyDefinition = potential.getKeyDefinition();
+ if (keyDefinition == null || keyDefinition.isEmpty()) {
+ return new UnkeyedListMixinContextNode(potential);
+ }
+ if (potential.isUserOrdered()) {
+ return new OrderedMapMixinContextNode(potential);
+ }
+ return new UnorderedMapMixinContextNode(potential);
+ }
+
+ private static DataSchemaContextNode<?> fromLeafListSchemaNode(final LeafListSchemaNode potential) {
+ if (potential.isUserOrdered()) {
+ return new OrderedLeafListMixinContextNode(potential);
+ }
+ return new UnorderedLeafListMixinContextNode(potential);
+ }
+
+ public static DataSchemaContextNode<?> from(final SchemaContext ctx) {
+ return new ContainerContextNode(ctx);
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import java.util.Iterator;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class DataSchemaContextTree {
+
+ private static final LoadingCache<SchemaContext, DataSchemaContextTree> TREES = CacheBuilder.newBuilder()
+ .weakKeys()
+ .build(new CacheLoader<SchemaContext, DataSchemaContextTree>() {
+
+ @Override
+ public DataSchemaContextTree load(SchemaContext key) throws Exception {
+ return new DataSchemaContextTree(key);
+ }
+
+ });
+
+ private final DataSchemaContextNode<?> root;
+
+ private DataSchemaContextTree(final SchemaContext ctx) {
+ root = DataSchemaContextNode.from(ctx);
+ }
+
+
+ public static DataSchemaContextTree from(SchemaContext ctx) {
+ return TREES.getUnchecked(ctx);
+ }
+
+ public DataSchemaContextNode<?> getChild(final YangInstanceIdentifier path) {
+ DataSchemaContextNode<?> currentOp = root;
+ Iterator<PathArgument> arguments = path.getPathArguments().iterator();
+ while (arguments.hasNext()) {
+ currentOp = currentOp.getChild(arguments.next());
+ }
+ return currentOp;
+ }
+
+ public DataSchemaContextNode<?> getRoot() {
+ return root;
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+
+final class LeafContextNode extends AbstractLeafNodeContext<NodeIdentifier> {
+
+ protected LeafContextNode(final LeafSchemaNode potential) {
+ super(new NodeIdentifier(potential.getQName()), potential);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+
+final class LeafListEntryContextNode extends AbstractLeafNodeContext<NodeWithValue> {
+
+ public LeafListEntryContextNode(final LeafListSchemaNode potential) {
+ super(new NodeWithValue(potential.getQName(), null), potential);
+ }
+
+ @Override
+ public boolean isKeyedEntry() {
+ return true;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+final class ListItemContextNode extends
+ DataContainerContextNode<NodeIdentifierWithPredicates> {
+
+
+ protected ListItemContextNode(final NodeIdentifierWithPredicates identifier, final ListSchemaNode schema) {
+ super(identifier, schema, schema);
+ }
+
+ @Override
+ public boolean isKeyedEntry() {
+ return true;
+ }
+}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.util;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
-@Deprecated
-public final class Nodes {
-
- private Nodes() {
- }
-
- public static <T> SimpleNode<T> leafNode(final QName name, final T value) {
- return new SimpleNodeTO<T>(name, value, null);
- }
-
- public static CompositeNode containerNode(final QName name, final List<Node<?>> children) {
- return containerNode(name, children, null);
- }
-
- public static CompositeNode containerNode(final QName name, final List<Node<?>> children, final CompositeNode parent) {
- return new ContainerNodeTO(name, parent, nodeMapFromList(children));
- }
-
- public static Map<QName, List<Node<?>>> nodeMapFromList(final List<Node<?>> children) {
- Map<QName, List<Node<?>>> map = new HashMap<QName, List<Node<?>>>();
- for (Node<?> node : children) {
-
- QName name = node.getNodeType();
- List<Node<?>> targetList = map.get(name);
- if (targetList == null) {
- targetList = new ArrayList<Node<?>>();
- map.put(name, targetList);
- }
- targetList.add(node);
- }
- return map;
- }
-
- /**
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
- @Deprecated
- private static class ContainerNodeTO extends AbstractContainerNode {
-
- private final Map<QName, List<Node<?>>> nodeMap;
-
- public ContainerNodeTO(final QName name, final Map<QName, List<Node<?>>> nodeMap) {
- super(name);
- this.nodeMap = nodeMap;
- }
-
- public ContainerNodeTO(final QName name, final CompositeNode parent, final Map<QName, List<Node<?>>> nodeMap) {
- super(name, parent);
- this.nodeMap = nodeMap;
- }
-
- @Override
- protected Map<QName, List<Node<?>>> getNodeMap() {
-
- return nodeMap;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.opendaylight.yangtools.yang.data.api.CompositeNode#asMutable()
- */
- @Override
- public MutableCompositeNode asMutable() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public QName getKey() {
- return getNodeType();
- }
-
- @Override
- public List<Node<?>> setValue(final List<Node<?>> value) {
- return null;
- }
-
- @Override
- public int size() {
- return nodeMap.size();
- }
-
- @Override
- public boolean isEmpty() {
- return nodeMap.isEmpty();
- }
-
- @Override
- public boolean containsKey(final Object key) {
- return nodeMap.containsKey(key);
- }
-
- @Override
- public boolean containsValue(final Object value) {
- return nodeMap.containsValue(value);
- }
-
- @Override
- public List<Node<?>> get(final Object key) {
- return nodeMap.get(key);
- }
-
- @Override
- public List<Node<?>> put(final QName key, final List<Node<?>> value) {
- return nodeMap.put(key, value);
- }
-
- @Override
- public List<Node<?>> remove(final Object key) {
- return nodeMap.remove(key);
- }
-
- @Override
- public void putAll(final Map<? extends QName, ? extends List<Node<?>>> m) {
- nodeMap.putAll(m);
- }
-
- @Override
- public void clear() {
- nodeMap.clear();
- }
-
- @Override
- public Set<QName> keySet() {
- return nodeMap.keySet();
- }
-
- @Override
- public Collection<List<Node<?>>> values() {
- return nodeMap.values();
- }
-
- @Override
- public Set<java.util.Map.Entry<QName, List<Node<?>>>> entrySet() {
-
- return nodeMap.entrySet();
- }
-
- }
-
- /**
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
- @Deprecated
- private static class SimpleNodeTO<T> extends AbstractNode<T> implements SimpleNode<T> {
-
- private final T value;
-
- protected SimpleNodeTO(final QName name, final T val, final CompositeNode parent) {
- super(name, parent);
- value = val;
-
- }
-
- @Override
- public T getValue() {
- return value;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.opendaylight.yangtools.yang.data.api.SimpleNode#asMutable()
- */
- @Override
- public MutableSimpleNode<T> asMutable() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public T setValue(final T value) {
- return null;
- }
-
- @Override
- public QName getKey() {
- return getNodeType();
- }
- }
-
-}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+
+final class OrderedLeafListMixinContextNode extends UnorderedLeafListMixinContextNode {
+
+ public OrderedLeafListMixinContextNode(final LeafListSchemaNode potential) {
+ super(potential);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+final class OrderedMapMixinContextNode extends UnorderedMapMixinContextNode {
+
+ public OrderedMapMixinContextNode(final ListSchemaNode list) {
+ super(list);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+final class UnkeyedListItemContextNode extends DataContainerContextNode<NodeIdentifier> {
+
+ protected UnkeyedListItemContextNode(final ListSchemaNode schema) {
+ super(new NodeIdentifier(schema.getQName()), schema, schema);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+class UnkeyedListMixinContextNode extends AbstractMixinContextNode<NodeIdentifier> {
+
+ private final UnkeyedListItemContextNode innerNode;
+
+ public UnkeyedListMixinContextNode(final ListSchemaNode list) {
+ super(new NodeIdentifier(list.getQName()), list);
+ this.innerNode = new UnkeyedListItemContextNode(list);
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final PathArgument child) {
+ if (child.getNodeType().equals(getIdentifier().getNodeType())) {
+ return innerNode;
+ }
+ return null;
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final QName child) {
+ if (getIdentifier().getNodeType().equals(child)) {
+ return innerNode;
+ }
+ return null;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+
+class UnorderedLeafListMixinContextNode extends AbstractMixinContextNode<NodeIdentifier> {
+
+ private final DataSchemaContextNode<?> innerOp;
+
+ public UnorderedLeafListMixinContextNode(final LeafListSchemaNode potential) {
+ super(new NodeIdentifier(potential.getQName()), potential);
+ innerOp = new LeafListEntryContextNode(potential);
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final PathArgument child) {
+ if (child instanceof NodeWithValue) {
+ return innerOp;
+ }
+ return null;
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final QName child) {
+ if (getIdentifier().getNodeType().equals(child)) {
+ return innerOp;
+ }
+ return null;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import java.util.Collections;
+import org.opendaylight.yangtools.yang.common.QName;
+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.model.api.ListSchemaNode;
+
+class UnorderedMapMixinContextNode extends AbstractMixinContextNode<NodeIdentifier> {
+
+ private final ListItemContextNode innerNode;
+
+ public UnorderedMapMixinContextNode(final ListSchemaNode list) {
+ super(new NodeIdentifier(list.getQName()), list);
+ this.innerNode = new ListItemContextNode(new NodeIdentifierWithPredicates(list.getQName(),
+ Collections.<QName, Object> emptyMap()), list);
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final PathArgument child) {
+ if (child.getNodeType().equals(getIdentifier().getNodeType())) {
+ return innerNode;
+ }
+ return null;
+ }
+
+ @Override
+ public DataSchemaContextNode<?> getChild(final QName child) {
+ if (getIdentifier().getNodeType().equals(child)) {
+ return innerNode;
+ }
+ return null;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import java.util.LinkedList;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.concepts.Builder;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+/**
+ *
+ * Iterator which lazily parses {@link PathArgument} from string representation.
+ *
+ * Note that invocation of {@link #hasNext()} or {@link #next()} may result in
+ * throwing of {@link IllegalArgumentException} if underlying string represenation
+ * is not correctly serialized or does not represent instance identifier valid
+ * for associated schema context.
+ *
+ * In order to obtain {@link Iterable} or {@link java.util.Collection} please use
+ * {@link com.google.common.collect.ImmutableList#copyOf(java.util.Iterator)}
+ * with this Iterator, which will trigger computation of all path arguments.
+ *
+ */
+class XpathStringParsingPathArgumentBuilder implements Builder<Iterable<PathArgument>> {
+
+ /**
+ * Matcher matching WSP YANG ABNF token
+ *
+ */
+ private static final CharMatcher WSP = CharMatcher.anyOf(" \t");
+
+ /**
+ * Matcher matching IDENTIFIER first char token.
+ *
+ */
+ private static final CharMatcher IDENTIFIER_FIRST_CHAR =
+ CharMatcher.inRange('a', 'z')
+ .or(CharMatcher.inRange('A', 'Z'))
+ .or(CharMatcher.is('_')).precomputed();
+ /**
+ *
+ * Matcher matching IDENTIFIER token
+ *
+ */
+ private static final CharMatcher IDENTIFIER =
+ IDENTIFIER_FIRST_CHAR
+ .or(CharMatcher.inRange('0', '9'))
+ .or(CharMatcher.anyOf(".-")).precomputed();
+
+ private static final CharMatcher SQUOTE = CharMatcher.is('\'');
+ private static final CharMatcher DQUOTE = CharMatcher.is('"');
+
+ private static final char SLASH = '/';
+ private static final char COLON = ':';
+ private static final char DOT = '.';
+ private static final char EQUALS = '=';
+ private static final char PRECONDITION_START = '[';
+ private static final char PRECONDITION_END = ']';
+
+ private final AbstractStringInstanceIdentifierCodec codec;
+ private final String data;
+
+ private final LinkedList<PathArgument> product = new LinkedList<>();
+
+ private DataSchemaContextNode<?> current;
+ private int offset;
+
+ XpathStringParsingPathArgumentBuilder(AbstractStringInstanceIdentifierCodec codec, String data) {
+ this.codec = Preconditions.checkNotNull(codec);
+ this.data = Preconditions.checkNotNull(data);
+ this.current = codec.getDataContextTree().getRoot();
+ this.offset = 0;
+ }
+
+
+ @Override
+ public Iterable<PathArgument> build() {
+ while (!allCharactersConsumed()) {
+ product.add(computeNextArgument());
+ }
+ return ImmutableList.copyOf(product);
+ }
+
+ private PathArgument computeNextArgument() {
+ checkValid(SLASH == currentChar(),"Identifier must start with '/'.");
+ skipCurrentChar();
+
+ QName name = nextQName();
+ if(allCharactersConsumed() || SLASH == currentChar()) {
+ return computeIdentifier(name);
+ } else {
+ checkValid(PRECONDITION_START == currentChar(), "Last element must be identifier, predicate or '/'");
+ return computeIdentifierWithPredicate(name);
+ }
+ }
+
+
+ private DataSchemaContextNode<?> nextContextNode(QName name) {
+ current = current.getChild(name);
+ checkValid(current != null, "%s is not correct schema node identifier.",name);
+ while(current.isMixin()) {
+ product.add(current.getIdentifier());
+ current = current.getChild(name);
+ }
+ return current;
+ }
+
+
+ /**
+ *
+ * Creates path argument with predicates and sets offset
+ * to end of path argument.
+ *
+ * {@code
+ * predicate = "[" *WSP (predicate-expr / pos) *WSP "]"
+ * predicate-expr = (node-identifier / ".") *WSP "=" *WSP
+ * ((DQUOTE string DQUOTE) /
+ * (SQUOTE string SQUOTE))
+ * pos = non-negative-integer-value
+ * }
+ *
+ * @param name QName of node, for which predicates are computed.
+ * @return PathArgument representing node selection with predictes
+ */
+ private PathArgument computeIdentifierWithPredicate(QName name) {
+ DataSchemaContextNode<?> currentNode = nextContextNode(name);
+ checkValid(currentNode.isKeyedEntry(), "Entry %s does not allow specifying predicates.", name);
+
+ ImmutableMap.Builder<QName,Object> keyValues = ImmutableMap.builder();
+ while(!allCharactersConsumed() && PRECONDITION_START == currentChar()) {
+ skipCurrentChar();
+ skipWhitespaces();
+ final QName key;
+ if(DOT == currentChar()) {
+ key = null;
+ skipCurrentChar();
+ } else {
+ key = nextQName();
+ }
+ skipWhitespaces();
+ checkCurrentAndSkip(EQUALS, "Precondition must contain '='");
+ skipWhitespaces();
+ final Object value = deserializeValue(key,nextQuotedValue());
+ skipWhitespaces();
+ checkCurrentAndSkip(PRECONDITION_END, "Precondition must ends with ']'");
+
+ // Break-out from method for leaf-list case
+ if(key == null && currentNode.isLeaf()) {
+ checkValid(offset == data.length(), "Leaf argument must be last argument of instance identifier.");
+ return new YangInstanceIdentifier.NodeWithValue(name, value);
+ }
+ keyValues.put(key, value);
+ }
+ return new YangInstanceIdentifier.NodeIdentifierWithPredicates(name, keyValues.build());
+ }
+
+
+ private PathArgument computeIdentifier(QName name) {
+ DataSchemaContextNode<?> currentNode = nextContextNode(name);
+ checkValid(!currentNode.isKeyedEntry(), "Entry %s requires key or value predicate to be present", name);
+ return currentNode.getIdentifier();
+ }
+
+
+ /**
+ *
+ * Returns following QName and sets offset to end of QName.
+ *
+ * @return following QName.
+ */
+ private QName nextQName() {
+ // Consume prefix or identifie
+ final String maybePrefix = nextIdentifier();
+ final String prefix,localName;
+ if(COLON == currentChar()) {
+ // previous token is prefix;
+ prefix = maybePrefix;
+ skipCurrentChar();
+ localName = nextIdentifier();
+ } else {
+ prefix = "";
+ localName = maybePrefix;
+ }
+ return createQName(prefix, localName);
+ }
+
+ /**
+ * Returns true if all characters from input string
+ * were consumed.
+ *
+ * @return true if all characters from input string
+ * were consumed.
+ */
+ private boolean allCharactersConsumed() {
+ return offset == data.length();
+ }
+
+
+ private QName createQName(String prefix, String localName) {
+ return codec.createQName(prefix, localName);
+ }
+
+ /**
+ *
+ * Skips current char if it equals expected otherwise fails parsing.
+ *
+ * @param expected Expected character
+ * @param errorMsg Error message if {@link #currentChar()} does not match expected.
+ */
+ private void checkCurrentAndSkip(char expected, String errorMsg) {
+ checkValid(expected == currentChar(), errorMsg);
+ offset++;
+ }
+
+
+ /**
+ *
+ * Deserializes value for supplied key
+ *
+ * @param key Name of referenced key, If null, referenced leaf is previous encountered item.
+ * @param value Value to be checked and deserialized
+ * @return Object representing value in yang-data-api format.
+ */
+ private Object deserializeValue(@Nullable QName key, String value) {
+ // FIXME: Use codec to deserialize value to correct Java type
+ return value;
+ }
+
+ /**
+ *
+ * Fails parsing if condition is not met.
+ *
+ * In case of error provides pointer to failed instance identifier,
+ * offset on which failure occured with explanation.
+ *
+ * @param condition Fails parsing if {@code condition} is false
+ * @param errorMsg Error message which will be provided to user.
+ * @param attributes
+ */
+ private void checkValid(boolean condition, String errorMsg, Object... attributes) {
+ Preconditions.checkArgument(condition, "Could not parse Instance Identifier '%s'. Offset: %s : Reason: %s",
+ data,
+ offset,
+ String.format(errorMsg, attributes));
+ }
+
+ /**
+ *
+ * Returns following value of quoted literal (without qoutes)
+ * and sets offset after literal.
+ *
+ * @return String literal
+ */
+ private String nextQuotedValue() {
+ char quoteChar = currentChar();
+ checkValidQuotation(quoteChar);
+ skipCurrentChar();
+ int valueStart = offset;
+ int endQoute = data.indexOf(quoteChar, offset);
+ String value = data.substring(valueStart, endQoute);
+ offset = endQoute;
+ skipCurrentChar();
+ return value;
+ }
+
+ /**
+ * Returns character at current offset.
+ *
+ * @return character at current offset.
+ */
+ private char currentChar() {
+ return data.charAt(offset);
+ }
+
+ /**
+ * Increases processing offset by 1
+ */
+ private void skipCurrentChar() {
+ offset++;
+ }
+
+ /**
+ * Skip whitespace characters, sets offset to first following
+ * non-whitespace character.
+ */
+ private void skipWhitespaces() {
+ nextSequenceEnd(WSP);
+ }
+
+ /**
+ * Returns string which matches IDENTIFIER YANG ABNF token
+ * and sets processing offset after end of identifier.
+ *
+ * @return string which matches IDENTIFIER YANG ABNF token
+ */
+ private String nextIdentifier() {
+ int start = offset;
+ checkValid(IDENTIFIER_FIRST_CHAR.matches(currentChar()), "Identifier must start with character from set 'a-zA-Z_'");
+ nextSequenceEnd(IDENTIFIER);
+ return data.substring(start, offset);
+ }
+
+ private void nextSequenceEnd(CharMatcher matcher) {
+ while(!allCharactersConsumed() && matcher.matches(data.charAt(offset))) {
+ offset++;
+ }
+ }
+
+ private void checkValidQuotation(char quoteChar) {
+ checkValid(
+ SQUOTE.matches(quoteChar) || DQUOTE.matches(quoteChar),
+ "Value must be qoute escaped with ''' or '\"'.");
+
+ }
+
+}
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.sonatype.plexus</groupId>
<artifactId>plexus-build-api</artifactId>
+ <scope>provided</scope>
</dependency>
</dependencies>
<artifactId>maven-artifact</artifactId>
<version>2.0</version>
</dependency>
- <dependency>
- <groupId>com.jcabi</groupId>
- <artifactId>jcabi-maven-slf4j</artifactId>
- <version>0.8</version>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>yang-parser-impl</artifactId>
</dependency>
</dependencies>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.sonatype.sisu</groupId>
- <artifactId>sisu-inject-plexus</artifactId>
- <version>2.5.0</version>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
<reporting>
<plugins>
<plugin>
*/
package org.opendaylight.yangtools.yang2sources.plugin;
+import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
-
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
-import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
-import org.slf4j.impl.StaticLoggerBinder;
+import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
import org.sonatype.plexus.build.incremental.BuildContext;
-import com.google.common.annotations.VisibleForTesting;
-
/**
* Generate sources from yang files using user provided set of
- * {@link CodeGenerator}s. Steps of this process:
+ * {@link BasicCodeGenerator}s. Steps of this process:
* <ol>
* <li>List yang files from {@link #yangFilesRootDir}</li>
* <li>Process yang files using {@link YangParserImpl}</li>
- * <li>For each {@link CodeGenerator} from {@link #codeGenerators}:
+ * <li>For each {@link BasicCodeGenerator} from {@link #codeGenerators}:
* <ol>
* <li>Instantiate using default constructor</li>
- * <li>Call {@link CodeGenerator#generateSources(SchemaContext, File, Set)}</li>
+ * <li>Call {@link BasicCodeGenerator#generateSources(SchemaContext, File, Set)}</li>
* </ol></li>
* </ol>
*/
public static final String PLUGIN_NAME = "org.opendaylight.yangtools:yang-maven-plugin";
/**
- * Classes implementing {@link CodeGenerator} interface. An instance will be
+ * Classes implementing {@link BasicCodeGenerator} interface. An instance will be
* created out of every class using default constructor. Method {@link
* CodeGenerator#generateSources(SchemaContext, File, Set<String>
* yangModulesNames)} will be called on every instance.
public YangToSourcesMojo() {
}
- public void setProject(MavenProject project) {
+ public void setProject(final MavenProject project) {
this.project = project;
}
@VisibleForTesting
- YangToSourcesMojo(YangToSourcesProcessor processor) {
+ YangToSourcesMojo(final YangToSourcesProcessor processor) {
this.yangToSourcesProcessor = processor;
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
- StaticLoggerBinder.getSingleton().setMavenLog(this.getLog());
-
Util.checkClasspath(project, repoSystem, localRepository, remoteRepos, getLog());
if (yangToSourcesProcessor == null) {
yangToSourcesProcessor.execute();
}
- private static List<CodeGeneratorArg> processCodeGenerators(CodeGeneratorArg[] codeGenerators) {
+ private static List<CodeGeneratorArg> processCodeGenerators(final CodeGeneratorArg[] codeGenerators) {
List<CodeGeneratorArg> codeGeneratorArgs;
if (codeGenerators == null) {
codeGeneratorArgs = Collections.emptyList();
return codeGeneratorArgs;
}
- private static File processYangFilesRootDir(String yangFilesRootDir, File baseDir) {
+ private static File processYangFilesRootDir(final String yangFilesRootDir, final File baseDir) {
File yangFilesRootFile;
if (yangFilesRootDir == null) {
yangFilesRootFile = new File(baseDir, "src" + File.separator + "main" + File.separator + "yang");
return yangFilesRootFile;
}
- private static File[] processExcludeFiles(String[] excludeFiles, File baseDir) {
+ private static File[] processExcludeFiles(final String[] excludeFiles, final File baseDir) {
if (excludeFiles == null) {
return new File[] {};
}
*/
package org.opendaylight.yangtools.yang.model.api;
-import java.util.Set;
-
-import org.opendaylight.yangtools.yang.common.QName;
/**
- *
* The ChoiceNode defines a set of alternatives. It consists of a number of
* branches defined as ChoiceCaseNode objects.
+ *
+ * @deprecated This interface is deprecated in favor of {@link ChoiceSchemaNode} and
+ * will be removed in a future release.
*/
-public interface ChoiceNode extends DataSchemaNode, AugmentationTarget {
-
- /**
- * Returns cases of choice.
- *
- * @return set of ChoiceCaseNode objects defined in this node which
- * represents set of arguments of the YANG <code>case</code>
- * substatement of the <code>choice</code> statement
- */
- Set<ChoiceCaseNode> getCases();
-
- /**
- *
- * Returns the concrete case according to specified Q name.
- *
- * @param name
- * QName of seeked Choice Case Node
- * @return child case node of this Choice if child with given name is
- * present, <code>null</code> otherwise
- */
- ChoiceCaseNode getCaseNodeByName(QName name);
-
- /**
- * Returns the concrete case according to specified name.
- *
- * @param name
- * name of seeked child as String
- * @return child case node (or local name of case node) of this Choice if
- * child with given name is present, <code>null</code> otherwise
- */
- ChoiceCaseNode getCaseNodeByName(String name);
-
- /**
- *
- * Returns name of case which is in the choice specified as default
- *
- * @return string with the name of case which is specified in the argument
- * of the YANG <code>default</code> substatement of
- * <code>choice</code> statement.
- */
- String getDefaultCase();
+@Deprecated
+public interface ChoiceNode extends ChoiceSchemaNode {
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.model.api;
+
+import java.util.Set;
+import org.opendaylight.yangtools.yang.common.QName;
+
+/**
+ * A ChoiceSchemaNode defines a set of alternatives. It consists of a number of
+ * branches defined as ChoiceCaseSchemaNode objects.
+ */
+public interface ChoiceSchemaNode extends DataSchemaNode, AugmentationTarget {
+ /**
+ * Returns cases of choice.
+ *
+ * @return set of ChoiceCaseNode objects defined in this node which
+ * represents set of arguments of the YANG <code>case</code>
+ * substatement of the <code>choice</code> statement
+ */
+ Set<ChoiceCaseNode> getCases();
+
+ /**
+ *
+ * Returns the concrete case according to specified Q name.
+ *
+ * @param name
+ * QName of seeked Choice Case Node
+ * @return child case node of this Choice if child with given name is
+ * present, <code>null</code> otherwise
+ */
+ ChoiceCaseNode getCaseNodeByName(QName name);
+
+ /**
+ * Returns the concrete case according to specified name.
+ *
+ * @param name
+ * name of seeked child as String
+ * @return child case node (or local name of case node) of this Choice if
+ * child with given name is present, <code>null</code> otherwise
+ */
+ ChoiceCaseNode getCaseNodeByName(String name);
+
+ /**
+ *
+ * Returns name of case which is in the choice specified as default
+ *
+ * @return string with the name of case which is specified in the argument
+ * of the YANG <code>default</code> substatement of
+ * <code>choice</code> statement.
+ */
+ String getDefaultCase();
+
+}
* <dd>{@link org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode}
*
* <dt>choice
- * <dd>{@link org.opendaylight.yangtools.yang.model.api.ChoiceNode}
+ * <dd>{@link org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode}
*
* <dt>config
* <dd>{@link org.opendaylight.yangtools.yang.model.api.DataSchemaNode#isConfiguration()}
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
emitLeafList((LeafListSchemaNode) child);
} else if (child instanceof ListSchemaNode) {
emitList((ListSchemaNode) child);
- } else if (child instanceof ChoiceNode) {
- emitChoice((ChoiceNode) child);
+ } else if (child instanceof ChoiceSchemaNode) {
+ emitChoice((ChoiceSchemaNode) child);
} else if (child instanceof AnyXmlSchemaNode) {
emitAnyxml((AnyXmlSchemaNode) child);
} else {
}
- private void emitChoice(final ChoiceNode choice) {
+ private void emitChoice(final ChoiceSchemaNode choice) {
writer.startChoiceNode(choice.getQName());
emitWhen(choice.getConstraints().getWhenCondition());
// FIXME: BUG-2444: *(ifFeatureNode )
emitRefineLeafListNodes((LeafListSchemaNode) value);
} else if (value instanceof ListSchemaNode) {
emitRefineListNodes((ListSchemaNode) value);
- } else if (value instanceof ChoiceNode) {
- emitRefineChoiceNodes((ChoiceNode) value);
+ } else if (value instanceof ChoiceSchemaNode) {
+ emitRefineChoiceNodes((ChoiceSchemaNode) value);
} else if (value instanceof ChoiceCaseNode) {
emitRefineCaseNodes((ChoiceCaseNode) value);
} else if (value instanceof ContainerSchemaNode) {
}
- private void emitRefineChoiceNodes(final ChoiceNode value) {
- final ChoiceNode original = getOriginalChecked(value);
+ private void emitRefineChoiceNodes(final ChoiceSchemaNode value) {
+ final ChoiceSchemaNode original = getOriginalChecked(value);
// FIXME: BUG-2444: defaultNode //FIXME: BUG-2444: Optional
if (Objects.deepEquals(original.isConfiguration(), value.isConfiguration())) {
}
}
- private boolean isArgumentYinElement(StatementDefinition currentStatement2) {
- // FIXME: Implement this
+ private boolean isArgumentYinElement(StatementDefinition currentStatement) {
+ if (currentStatement instanceof Rfc6020Mapping) {
+ return ((Rfc6020Mapping) currentStatement).isArgumentYinElement();
+ } else if (currentStatement instanceof ExtensionStatement) {
+ return ((ExtensionStatement) currentStatement).isArgumentYinElement();
+ }
return false;
}
import java.util.Iterator;
import java.util.List;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
private final DataNodeContainer container;
private final List<ListSchemaNode> allLists;
private final List<ContainerSchemaNode> allContainers;
- private final List<ChoiceNode> allChoices;
+ private final List<ChoiceSchemaNode> allChoices;
private final List<DataSchemaNode> allChilds;
private final List<GroupingDefinition> allGroupings;
private final List<TypeDefinition<?>> allTypedefs;
*
* @return Returns list all containers present in subtree.
*/
- public List<ChoiceNode> allChoices() {
+ public List<ChoiceSchemaNode> allChoices() {
return allChoices;
}
final ListSchemaNode list = (ListSchemaNode) childNode;
allLists.add(list);
traverse(list);
- } else if (childNode instanceof ChoiceNode) {
- final ChoiceNode choiceNode = (ChoiceNode) childNode;
+ } else if (childNode instanceof ChoiceSchemaNode) {
+ final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) childNode;
allChoices.add(choiceNode);
final Set<ChoiceCaseNode> cases = choiceNode.getCases();
if (cases != null) {
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.model.util;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.UsesNode;
+
+/**
+ * Proxy for AugmentationSchema. Child node schemas are replaced with actual schemas from parent.
+ *
+ * FIXME: Make this class final, once derived deprecated class is removed.
+ */
+public class EffectiveAugmentationSchema implements AugmentationSchema {
+ private final AugmentationSchema delegate;
+ private final Set<DataSchemaNode> realChildSchemas;
+ private final Map<QName, DataSchemaNode> mappedChildSchemas;
+
+ public EffectiveAugmentationSchema(final AugmentationSchema augmentSchema, final Set<DataSchemaNode> realChildSchemas) {
+ this.delegate = augmentSchema;
+ this.realChildSchemas = realChildSchemas;
+
+ final Map<QName, DataSchemaNode> m = new HashMap<>(realChildSchemas.size());
+ for (DataSchemaNode realChildSchema : realChildSchemas) {
+ m.put(realChildSchema.getQName(), realChildSchema);
+ }
+
+ this.mappedChildSchemas = ImmutableMap.copyOf(m);
+ }
+
+ @Override
+ public RevisionAwareXPath getWhenCondition() {
+ return delegate.getWhenCondition();
+ }
+
+ @Override
+ public String getDescription() {
+ return delegate.getDescription();
+ }
+
+ @Override
+ public String getReference() {
+ return delegate.getReference();
+ }
+
+ @Override
+ public Status getStatus() {
+ return delegate.getStatus();
+ }
+
+ @Override
+ public SchemaPath getTargetPath() {
+ return delegate.getTargetPath();
+ }
+
+ @Override
+ public List<UnknownSchemaNode> getUnknownSchemaNodes() {
+ return delegate.getUnknownSchemaNodes();
+ }
+
+ @Override
+ public Set<TypeDefinition<?>> getTypeDefinitions() {
+ return delegate.getTypeDefinitions();
+ }
+
+ @Override
+ public Set<DataSchemaNode> getChildNodes() {
+ return realChildSchemas;
+ }
+
+ @Override
+ public Set<GroupingDefinition> getGroupings() {
+ return delegate.getGroupings();
+ }
+
+ @Override
+ public DataSchemaNode getDataChildByName(final QName name) {
+ return mappedChildSchemas.get(name);
+ }
+
+ @Override
+ public DataSchemaNode getDataChildByName(final String name) {
+ // Unused
+ throw new UnsupportedOperationException("Unable to retrieve child node by name");
+ }
+
+ @Override
+ public Set<UsesNode> getUses() {
+ return delegate.getUses();
+ }
+
+ @Override
+ public Optional<AugmentationSchema> getOriginalDefinition() {
+ return delegate.getOriginalDefinition();
+ }
+}
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
}
}
- if (foundNode == null && parent instanceof ChoiceNode) {
- foundNode = ((ChoiceNode) parent).getCaseNodeByName(current);
+ if (foundNode == null && parent instanceof ChoiceSchemaNode) {
+ foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
if (foundNode != null && nextPath.iterator().hasNext()) {
foundNode = findNodeIn(foundNode, nextPath);
}
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-
import com.google.common.collect.Sets;
import java.net.URI;
import java.net.URISyntaxException;
revision2 = SimpleDateFormatUtil.getRevisionFormat().parse("2015-01-15");
}
- private SchemaContext mockSchema(Module... module) {
+ private SchemaContext mockSchema(final Module... module) {
SchemaContext mock = mock(SchemaContext.class);
doReturn(Sets.newHashSet(module)).when(mock).getModules();
assertProxyContext(filteringSchemaContextProxy, moduleConfig, module2, module3, module4);
}
- private void assertProxyContext(FilteringSchemaContextProxy filteringSchemaContextProxy, Module... expected) {
+ private void assertProxyContext(final FilteringSchemaContextProxy filteringSchemaContextProxy, final Module... expected) {
Set<Module> modSet = Sets.newHashSet();
}
}
- private FilteringSchemaContextProxy createProxySchemaCtx(SchemaContext schemaContext, Set<Module> additionalModules, Module... modules) {
+ private FilteringSchemaContextProxy createProxySchemaCtx(final SchemaContext schemaContext, final Set<Module> additionalModules, final Module... modules) {
- Set<Module> modulesSet = new HashSet();
+ Set<Module> modulesSet = new HashSet<>();
if(modules!=null) {
return new FilteringSchemaContextProxy(schemaContext, createModuleIds(modulesSet) , createModuleIds(additionalModules));
}
- private Set<ModuleId> createModuleIds(Set<Module> modules) {
+ private Set<ModuleId> createModuleIds(final Set<Module> modules) {
Set<ModuleId> moduleIds = Sets.newHashSet();
return moduleIds;
}
- private void mockSubmodules(Module mainModule, Module... submodules){
+ private void mockSubmodules(final Module mainModule, final Module... submodules){
Set<Module> submodulesSet = new HashSet<>();
submodulesSet.addAll(Arrays.asList(submodules));
doReturn(submodulesSet).when(mainModule).getSubmodules();
}
- private void mockModuleImport(Module importer, Module... imports) {
+ private void mockModuleImport(final Module importer, final Module... imports) {
Set<ModuleImport> mockedImports = Sets.newHashSet();
for (final Module module : imports) {
mockedImports.add(new ModuleImport() {
}
//mock module with revision
- private Module mockModule(String name, final Date rev){
+ private Module mockModule(final String name, final Date rev){
final Module mod = mockModule(name);
}
//mock module with default revision
- private Module mockModule(String mName) {
+ private Module mockModule(final String mName) {
Module mockedModule = mock(Module.class);
doReturn(mName).when(mockedModule).getName();
<artifactId>concepts</artifactId>
</dependency>
<dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
+ <groupId>com.google.code.findbugs</groupId>
+ <artifactId>jsr305</artifactId>
</dependency>
- <dependency>
- <groupId>com.google.code.findbugs</groupId>
- <artifactId>jsr305</artifactId>
- </dependency>
</dependencies>
<build>
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.common.io.ByteSource;
+import com.google.common.io.ByteStreams;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Set;
import java.util.TreeMap;
import org.antlr.v4.runtime.tree.ParseTree;
-import org.apache.commons.io.IOUtils;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Belongs_to_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_header_stmtsContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_stmtContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
if (node instanceof AnyXmlSchemaNode) {
return new AnyXmlBuilder(moduleName, line, qname, schemaPath, ((AnyXmlSchemaNode) node));
- } else if (node instanceof ChoiceNode) {
- return new ChoiceBuilder(moduleName, line, qname, schemaPath, ((ChoiceNode) node));
+ } else if (node instanceof ChoiceSchemaNode) {
+ return new ChoiceBuilder(moduleName, line, qname, schemaPath, ((ChoiceSchemaNode) node));
} else if (node instanceof ContainerSchemaNode) {
return new ContainerSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((ContainerSchemaNode) node));
} else if (node instanceof LeafSchemaNode) {
private static final class ByteSourceImpl extends ByteSource {
private final String toString;
- private final ByteArrayOutputStream output = new ByteArrayOutputStream();
+ private final byte[] data;
private ByteSourceImpl(final InputStream input) throws IOException {
toString = input.toString();
- IOUtils.copy(input, output);
+ data = ByteStreams.toByteArray(input);
}
@Override
public InputStream openStream() throws IOException {
- return new NamedByteArrayInputStream(output.toByteArray(), toString);
+ return new NamedByteArrayInputStream(data, toString);
}
}
*/
package org.opendaylight.yangtools.yang.parser.builder.impl;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
import org.opendaylight.yangtools.yang.parser.builder.util.AbstractSchemaNodeBuilder;
import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
import org.opendaylight.yangtools.yang.parser.util.YangParseException;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
public final class ChoiceBuilder extends AbstractSchemaNodeBuilder implements DataSchemaNodeBuilder,
AugmentationTargetBuilder {
private boolean augmenting;
private boolean addedByUses;
private boolean configuration;
- private ChoiceNode originalNode;
+ private ChoiceSchemaNode originalNode;
private ChoiceBuilder originalBuilder;
private final ConstraintsBuilder constraints;
// AugmentationTarget args
}
public ChoiceBuilder(final String moduleName, final int line, final QName qname, final SchemaPath path,
- final ChoiceNode base) {
+ final ChoiceSchemaNode base) {
super(moduleName, line, qname);
this.schemaPath = path;
constraints = new ConstraintsBuilderImpl(moduleName, line, base.getConstraints());
}
@Override
- public ChoiceNode build() {
+ public ChoiceSchemaNode build() {
if (instance != null) {
return instance;
}
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
-final class ChoiceNodeImpl implements ChoiceNode, DerivableSchemaNode {
+// FIXME: BUG-1513: remove ChoiceNode in Beryllium timeframe
+final class ChoiceNodeImpl implements ChoiceNode, ChoiceSchemaNode, DerivableSchemaNode {
private final QName qname;
private final SchemaPath path;
String description;
Status status;
boolean augmenting;
boolean addedByUses;
- ChoiceNode original;
+ ChoiceSchemaNode original;
boolean configuration;
ConstraintDefinition constraints;
ImmutableSet<ChoiceCaseNode> cases;
}
@Override
- public Optional<ChoiceNode> getOriginal() {
+ public Optional<ChoiceSchemaNode> getOriginal() {
return Optional.fromNullable(original);
}
*/
package org.opendaylight.yangtools.yang.parser.builder.impl;
+import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteSource;
import java.io.IOException;
-import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
-import org.apache.commons.io.IOUtils;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
}
public void setSource(final ByteSource byteSource) throws IOException {
- try (InputStream stream = byteSource.openStream()) {
- setSource(IOUtils.toString(stream));
- }
+ setSource(byteSource.asCharSource(Charsets.UTF_8).read());
}
public void setSource(final String source) {
return refines;
}
- @SuppressWarnings("unused")
public List<UnknownSchemaNode> getUnknownSchemaNodes() {
return unknownNodes;
}
import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.processAugmentation;
import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveType;
import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveTypeUnion;
-
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashBiMap;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition;
for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue().entrySet()) {
final ModuleBuilder moduleBuilder = childEntry.getValue();
final Module module = moduleBuilder.build();
- final List<ChoiceNode> allChoicesFromModule = getChoicesFrom(module);
+ final List<ChoiceSchemaNode> allChoicesFromModule = getChoicesFrom(module);
- for (ChoiceNode choiceNode : allChoicesFromModule) {
+ for (ChoiceSchemaNode choiceNode : allChoicesFromModule) {
findDuplicityNodesIn(choiceNode, module, moduleBuilder, modules);
}
}
}
}
- private void findDuplicityNodesIn(final ChoiceNode choiceNode, final Module module, final ModuleBuilder moduleBuilder,
+ private void findDuplicityNodesIn(final ChoiceSchemaNode choiceNode, final Module module, final ModuleBuilder moduleBuilder,
final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
final Set<QName> duplicityTestSet = new HashSet<QName>();
}
}
- private List<ChoiceNode> getChoicesFrom(final Module module) {
- final List<ChoiceNode> allChoices = new ArrayList<ChoiceNode>();
+ private List<ChoiceSchemaNode> getChoicesFrom(final Module module) {
+ final List<ChoiceSchemaNode> allChoices = new ArrayList<ChoiceSchemaNode>();
for (DataSchemaNode dataSchemaNode : module.getChildNodes()) {
findChoicesIn(dataSchemaNode, allChoices);
return allChoices;
}
- private void findChoicesIn(final SchemaNode schemaNode, final Collection<ChoiceNode> choiceNodes) {
+ private void findChoicesIn(final SchemaNode schemaNode, final Collection<ChoiceSchemaNode> choiceNodes) {
if (schemaNode instanceof ContainerSchemaNode) {
final ContainerSchemaNode contSchemaNode = (ContainerSchemaNode) schemaNode;
for (DataSchemaNode dataSchemaNode : contSchemaNode.getChildNodes()) {
for (DataSchemaNode dataSchemaNode : listSchemaNode.getChildNodes()) {
findChoicesIn(dataSchemaNode, choiceNodes);
}
- } else if (schemaNode instanceof ChoiceNode) {
- choiceNodes.add((ChoiceNode) schemaNode);
+ } else if (schemaNode instanceof ChoiceSchemaNode) {
+ choiceNodes.add((ChoiceSchemaNode) schemaNode);
}
}
package org.opendaylight.yangtools.yang.parser.util;
+import com.google.common.io.ByteStreams;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
-import org.apache.commons.io.IOUtils;
public class NamedByteArrayInputStream extends ByteArrayInputStream implements NamedInputStream {
private final String toString;
}
public static ByteArrayInputStream create(InputStream originalIS) throws IOException {
- String content = IOUtils.toString(originalIS);
+ final byte[] data = ByteStreams.toByteArray(originalIS);
+
if (originalIS instanceof NamedInputStream) {
- return new NamedByteArrayInputStream(content.getBytes(), originalIS.toString());
+ return new NamedByteArrayInputStream(data, originalIS.toString());
} else {
- return new ByteArrayInputStream(content.getBytes());
+ return new ByteArrayInputStream(data);
}
}
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
LeafSchemaNode ds0ChannelNumber = (LeafSchemaNode) augment.getDataChildByName("ds0ChannelNumber");
LeafSchemaNode interfaceId = (LeafSchemaNode) augment.getDataChildByName("interface-id");
ContainerSchemaNode schemas = (ContainerSchemaNode) augment.getDataChildByName("schemas");
- ChoiceNode odl = (ChoiceNode) augment.getDataChildByName("odl");
+ ChoiceSchemaNode odl = (ChoiceSchemaNode) augment.getDataChildByName("odl");
assertNotNull(ds0ChannelNumber);
assertNotNull(interfaceId);
LeafSchemaNode ds0ChannelNumber = (LeafSchemaNode) augmentHolder.getDataChildByName("ds0ChannelNumber");
LeafSchemaNode interfaceId = (LeafSchemaNode) augmentHolder.getDataChildByName("interface-id");
ContainerSchemaNode schemas = (ContainerSchemaNode) augmentHolder.getDataChildByName("schemas");
- ChoiceNode odl = (ChoiceNode) augmentHolder.getDataChildByName("odl");
+ ChoiceSchemaNode odl = (ChoiceSchemaNode) augmentHolder.getDataChildByName("odl");
assertNotNull(ds0ChannelNumber);
assertNotNull(interfaceId);
// foo.yang
// augment "/br:interfaces/br:ifEntry/bz:augment-holder"
- ChoiceNode odl = (ChoiceNode) augmentedHolder.getDataChildByName("odl");
+ ChoiceSchemaNode odl = (ChoiceSchemaNode) augmentedHolder.getDataChildByName("odl");
assertNotNull(odl);
Set<ChoiceCaseNode> cases = odl.getCases();
assertEquals(4, cases.size());
ContainerSchemaNode input = submit.getInput();
QName inputQName = QName.create(NS_BAR, revision, "input");
assertEquals(inputQName, input.getQName());
- ChoiceNode arguments = (ChoiceNode) input.getDataChildByName("arguments");
+ ChoiceSchemaNode arguments = (ChoiceSchemaNode) input.getDataChildByName("arguments");
QName argumentsQName = QName.create(NS_BAR, revision, "arguments");
assertEquals(argumentsQName, arguments.getQName());
assertFalse(arguments.isAugmenting());
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-
import java.io.File;
import java.io.IOException;
import java.net.URI;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
import org.opendaylight.yangtools.yang.model.api.MustDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.UsesNode;
import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
assertFalse(data_u.equals(data_g));
assertEquals(data_g, SchemaNodeUtils.getRootOriginalIfPossible(data_u));
- ChoiceNode how_u = (ChoiceNode) destination.getDataChildByName("how");
+ ChoiceSchemaNode how_u = (ChoiceSchemaNode) destination.getDataChildByName("how");
assertNotNull(how_u);
TestUtils.checkIsAddedByUses(how_u, true);
assertEquals(2, how_u.getCases().size());
- ChoiceNode how_g = (ChoiceNode) grouping.getDataChildByName("how");
+ ChoiceSchemaNode how_g = (ChoiceSchemaNode) grouping.getDataChildByName("how");
assertNotNull(how_g);
TestUtils.checkIsAddedByUses(how_g, false);
assertEquals(2, how_g.getCases().size());
assertFalse(data_u.equals(data_g));
assertEquals(data_g, SchemaNodeUtils.getRootOriginalIfPossible(data_u));
- ChoiceNode how_u = (ChoiceNode) foo.getDataChildByName("how");
+ ChoiceSchemaNode how_u = (ChoiceSchemaNode) foo.getDataChildByName("how");
assertNotNull(how_u);
TestUtils.checkIsAddedByUses(how_u, true);
assertFalse(how_u.isAugmenting());
LeafSchemaNode intervalLeaf = (LeafSchemaNode) interval.getDataChildByName("interval");
assertFalse(intervalLeaf.isAugmenting());
- ChoiceNode how_g = (ChoiceNode) grouping.getDataChildByName("how");
+ ChoiceSchemaNode how_g = (ChoiceSchemaNode) grouping.getDataChildByName("how");
assertNotNull(how_g);
TestUtils.checkIsAddedByUses(how_g, false);
assertFalse(how_u.equals(how_g));
.getDataChildByName("my-container"))
.getDataChildByName("my-leaf");
- TypeDefinition impType = null;
+ TypeDefinition<?> impType = null;
Set<TypeDefinition<?>> typeDefinitions = imp.getTypeDefinitions();
for (TypeDefinition<?> typeDefinition : typeDefinitions) {
if (typeDefinition.getQName().getLocalName().equals("imp-type")) {
import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
checkIsAugmenting(child, expected);
}
- } else if (node instanceof ChoiceNode) {
- for (ChoiceCaseNode caseNode : ((ChoiceNode) node).getCases()) {
+ } else if (node instanceof ChoiceSchemaNode) {
+ for (ChoiceCaseNode caseNode : ((ChoiceSchemaNode) node).getCases()) {
checkIsAugmenting(caseNode, expected);
}
}
for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
checkIsAddedByUses(child, expected);
}
- } else if (node instanceof ChoiceNode) {
- for (ChoiceCaseNode caseNode : ((ChoiceNode) node).getCases()) {
+ } else if (node instanceof ChoiceSchemaNode) {
+ for (ChoiceCaseNode caseNode : ((ChoiceSchemaNode) node).getCases()) {
checkIsAddedByUses(caseNode, expected);
}
}
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
assertEquals(expectedPath, box.getPath());
assertTrue(box.isAddedByUses());
// * |-- |-- |-- |-- |-- choice address-family
- ChoiceNode af = (ChoiceNode) endpoints.getDataChildByName("address-family");
+ ChoiceSchemaNode af = (ChoiceSchemaNode) endpoints.getDataChildByName("address-family");
assertNotNull(af);
expectedQName = QName.create(UG_NS, UG_REV, "address-family");
assertEquals(expectedQName, af.getQName());
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
public void testChoice() {
Module foo = TestUtils.findModule(modules, "foo");
ContainerSchemaNode transfer = (ContainerSchemaNode) foo.getDataChildByName("transfer");
- ChoiceNode how = (ChoiceNode) transfer.getDataChildByName("how");
+ ChoiceSchemaNode how = (ChoiceSchemaNode) transfer.getDataChildByName("how");
Set<ChoiceCaseNode> cases = how.getCases();
assertEquals(5, cases.size());
ChoiceCaseNode input = null;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import com.google.common.collect.Lists;
import java.io.File;
import java.io.FileInputStream;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Deviation;
assertFalse(data_g.isAddedByUses());
assertFalse(data_u.equals(data_g));
- ChoiceNode how_u = (ChoiceNode) destination.getDataChildByName("how");
+ ChoiceSchemaNode how_u = (ChoiceSchemaNode) destination.getDataChildByName("how");
assertNotNull(how_u);
assertTrue(how_u.isAddedByUses());
- ChoiceNode how_g = (ChoiceNode) grouping.getDataChildByName("how");
+ ChoiceSchemaNode how_g = (ChoiceSchemaNode) grouping.getDataChildByName("how");
assertNotNull(how_g);
assertFalse(how_g.isAddedByUses());
assertFalse(how_u.equals(how_g));
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
+import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
-import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
@Override
public InputStream openStream() throws IOException {
- return IOUtils.toInputStream("running");
+ return new ByteArrayInputStream("running".getBytes(Charsets.UTF_8));
}
});
}
*/
package org.opendaylight.yangtools.yang.parser.util;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.text.ParseException;
+import java.util.Collections;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
import org.opendaylight.yangtools.yang.model.util.Int32;
import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.text.ParseException;
-import java.util.Collections;
-
-import static org.junit.Assert.*;
-
public class SchemaContextUtilTest {
@Mock
private SchemaContext mockSchemaContext;
assertNotNull(foundNode);
assertEquals(testNode, foundNode);
- testNode = ((ChoiceNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName("one").getDataChildByName(
+ testNode = ((ChoiceSchemaNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName("one").getDataChildByName(
"my-choice-leaf-one");
path = SchemaPath.create(true, QName.create(myModule.getQNameModule(), "my-choice"),
assertNull(testNode);
assertNull(foundNode);
- testNode = ((ChoiceNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName("one").getDataChildByName(
+ testNode = ((ChoiceSchemaNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName("one").getDataChildByName(
"no-choice-leaf");
path = SchemaPath.create(true, QName.create(myModule.getQNameModule(), "my-choice"),
assertEquals(testNode, foundNode);
// find grouping in case
- dataContainer = (DataNodeContainer) ((ChoiceNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName(
+ dataContainer = (DataNodeContainer) ((ChoiceSchemaNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName(
"one").getDataChildByName("my-container-in-case");
testNode = getGroupingByName(dataContainer, "my-grouping-in-case");
assertNull(foundNode);
// find grouping in case
- dataContainer = (DataNodeContainer) ((ChoiceNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName(
+ dataContainer = (DataNodeContainer) ((ChoiceSchemaNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName(
"one").getDataChildByName("my-container-in-case");
testNode = getGroupingByName(dataContainer, "my-grouping-in-case2");
}
- private static GroupingDefinition getGroupingByName(DataNodeContainer dataNodeContainer, String name) {
+ private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final String name) {
for (GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
if (grouping.getQName().getLocalName().equals(name)) {
return grouping;
return null;
}
- private static RpcDefinition getRpcByName(Module module, String name) {
+ private static RpcDefinition getRpcByName(final Module module, final String name) {
for (RpcDefinition rpc : module.getRpcs()) {
if (rpc.getQName().getLocalName().equals(name)) {
return rpc;
return null;
}
- private static NotificationDefinition getNotificationByName(Module module, String name) {
+ private static NotificationDefinition getNotificationByName(final Module module, final String name) {
for (NotificationDefinition notification : module.getNotifications()) {
if (notification.getQName().getLocalName().equals(name)) {
return notification;
Module myModule = context.findModuleByNamespaceAndRevision(new URI("uri:my-module"),
QName.parseRevision("2014-10-07"));
- ChoiceNode choice = (ChoiceNode)getRpcByName(myModule,"my-name").getInput().getDataChildByName("my-choice");
+ ChoiceSchemaNode choice = (ChoiceSchemaNode)getRpcByName(myModule,"my-name").getInput().getDataChildByName("my-choice");
SchemaNode testNode = choice.getCaseNodeByName("case-two").getDataChildByName("two");
SchemaPath path = SchemaPath.create(true, QName.create(myModule.getQNameModule(), "my-name"),