import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
+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 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;
import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class XmlStreamUtils {
private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
private final XmlCodecProvider codecProvider;
+ private final Optional<SchemaContext> schemaContext;
protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
+ this(codecProvider, null);
+ }
+
+ private XmlStreamUtils(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
this.codecProvider = Preconditions.checkNotNull(codecProvider);
+ this.schemaContext = Optional.fromNullable(schemaContext);
}
/**
* @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);
}
}
/**
- * Short-hand for {@link #writeDataDocument(XMLStreamWriter, CompositeNode, SchemaNode, XmlCodecProvider)} with
+ * Short-hand for {@link #writeDocument(XMLStreamWriter, CompositeNode, SchemaNode)})} with
* null SchemaNode.
*
* @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 XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
*/
public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
final QName qname = data.getNodeType();
- final String pfx = qname.getPrefix() != null ? qname.getPrefix() : "";
final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
+ final String pfx = "";
if (isEmptyElement(data)) {
if (hasAttributes(data)) {
if (data instanceof SimpleNode<?>) {
// Simple node
- if (schema instanceof LeafListSchemaNode) {
- writeValue(writer, ((LeafListSchemaNode) schema).getType(), data.getValue());
- } else if (schema instanceof LeafSchemaNode) {
- writeValue(writer, ((LeafSchemaNode) schema).getType(), data.getValue());
+ if (schema instanceof LeafListSchemaNode || schema instanceof LeafSchemaNode) {
+ writeValue(writer, schema, data.getValue());
} else {
Object value = data.getValue();
if (value != null) {
}
} else {
// CompositeNode
- for (Node<?> child : ((CompositeNode) data).getValue()) {
- DataSchemaNode childSchema = null;
- if (schema instanceof DataNodeContainer) {
- childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
- if (LOG.isDebugEnabled()) {
- if (childSchema == null) {
- LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
- }
- }
+ 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);
+ }
+ }
+ }
- writeElement(writer, child, childSchema);
+ 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 {
* emitted by the caller.
*
* @param writer XML Stream writer
- * @param type data type
+ * @param schemaNode Schema node that describes the value
+ * @param value data value
+ * @throws XMLStreamException if an encoding problem occurs
+ */
+ public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull SchemaNode schemaNode, final Object value) throws XMLStreamException {
+ if (value == null) {
+ LOG.debug("Value of {}:{} is null, not encoding it", schemaNode.getQName().getNamespace(), schemaNode.getQName().getLocalName());
+ return;
+ }
+
+ Preconditions.checkArgument(schemaNode instanceof LeafSchemaNode || schemaNode instanceof LeafListSchemaNode,
+ "Unable to write value for node %s, only nodes of type: leaf and leaf-list can be written at this point", schemaNode.getQName());
+
+ TypeDefinition<?> type = schemaNode instanceof LeafSchemaNode ?
+ ((LeafSchemaNode) schemaNode).getType():
+ ((LeafListSchemaNode) schemaNode).getType();
+
+ TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
+
+ if (schemaContext.isPresent() && baseType instanceof LeafrefTypeDefinition) {
+ LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
+ baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaContext.get(), schemaNode);
+ }
+
+ writeValue(writer, baseType, value);
+ }
+
+ /**
+ * 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 type data type. In case of leaf ref this should be the type of leaf being referenced
* @param value data value
* @throws XMLStreamException if an encoding problem occurs
*/
LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
return;
}
+ TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
- final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
if (baseType instanceof IdentityrefTypeDefinition) {
write(writer, (IdentityrefTypeDefinition) baseType, value);
} else if (baseType instanceof InstanceIdentifierTypeDefinition) {
}
}
- @SuppressWarnings("deprecation")
private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
if (value instanceof QName) {
final QName qname = (QName) value;
- final String prefix;
- if (qname.getPrefix() != null && !qname.getPrefix().isEmpty()) {
- prefix = qname.getPrefix();
- } else {
- prefix = "x";
- }
+ final String prefix = "x";
final String ns = qname.getNamespace().toString();
writer.writeNamespace(prefix, ns);
}
}
- 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);
+ }
}