1 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
3 import com.google.common.annotations.Beta;
4 import com.google.common.annotations.VisibleForTesting;
5 import com.google.common.base.Optional;
6 import com.google.common.base.Preconditions;
8 import java.util.Collection;
9 import java.util.Collections;
11 import java.util.Map.Entry;
12 import javax.annotation.Nonnull;
13 import javax.annotation.Nullable;
14 import javax.xml.stream.XMLStreamException;
15 import javax.xml.stream.XMLStreamWriter;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
18 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
19 import org.opendaylight.yangtools.yang.data.api.Node;
20 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
22 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
23 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
24 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
25 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
32 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
33 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
34 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
35 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
41 * by no means final and subject to change as more functionality is centralized here.
44 public class XmlStreamUtils {
45 private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
46 private final XmlCodecProvider codecProvider;
47 private final Optional<SchemaContext> schemaContext;
49 protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
50 this(codecProvider, null);
53 private XmlStreamUtils(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
54 this.codecProvider = Preconditions.checkNotNull(codecProvider);
55 this.schemaContext = Optional.fromNullable(schemaContext);
59 * Create a new instance encapsulating a particular codec provider.
61 * @param codecProvider XML codec provider
62 * @return A new instance
64 public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
65 return new XmlStreamUtils(codecProvider);
69 * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
70 * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
72 * @param data Data node
73 * @return True if the data node will result in empty element body.
75 public static boolean isEmptyElement(final Node<?> data) {
80 if (data instanceof CompositeNode) {
81 return ((CompositeNode) data).getValue().isEmpty();
83 if (data instanceof SimpleNode) {
84 return data.getValue() == null;
92 * Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
93 * and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
95 * @param writer XML Stream writer
96 * @param id InstanceIdentifier
97 * @throws XMLStreamException
99 * @deprecated Use {@link #writeInstanceIdentifier(XMLStreamWriter, YangInstanceIdentifier)} instead.
102 public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
103 Preconditions.checkNotNull(writer, "Writer may not be null");
104 Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
106 final RandomPrefix prefixes = new RandomPrefix();
107 final String str = XmlUtils.encodeIdentifier(prefixes, id);
108 writeNamespaceDeclarations(writer,prefixes.getPrefixes());
109 writer.writeCharacters(str);
113 * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
115 * @param writer XML Stream writer
116 * @param data data node
117 * @param schema corresponding schema node, may be null
118 * @throws XMLStreamException if an encoding problem occurs
120 public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
121 // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
122 // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
124 writer.writeStartDocument();
125 writeElement(writer, data, schema);
126 writer.writeEndDocument();
131 * Short-hand for {@link #writeDocument(XMLStreamWriter, CompositeNode, SchemaNode)})} with
134 * @param writer XML Stream writer
135 * @param data data node
136 * @throws XMLStreamException if an encoding problem occurs
138 public void writeDocument(final XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
139 writeDocument(writer, data, null);
143 * Write an element into a XML stream writer. This includes the element start/end tags and
144 * the value of the element.
146 * @param writer XML Stream writer
147 * @param data data node
148 * @param schema Schema node
149 * @throws XMLStreamException if an encoding problem occurs
151 public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
152 final QName qname = data.getNodeType();
153 final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
154 final String pfx = "";
156 if (isEmptyElement(data)) {
157 if (hasAttributes(data)) {
158 writer.writeStartElement(pfx, qname.getLocalName(), ns);
159 final RandomPrefix randomPrefix = new RandomPrefix();
160 writeAttributes(writer, (AttributesContainer) data, randomPrefix);
161 writer.writeEndElement();
163 writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
168 writer.writeStartElement(pfx, qname.getLocalName(), ns);
169 writeValue(writer, data, schema);
170 writer.writeEndElement();
174 * Write a value into a XML stream writer. This method assumes the start and end of element is
175 * emitted by the caller.
177 * @param writer XML Stream writer
178 * @param data data node
179 * @param schema Schema node
180 * @throws XMLStreamException if an encoding problem occurs
182 public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
183 if (hasAttributes(data)) {
184 RandomPrefix randomPrefix = new RandomPrefix();
185 writeAttributes(writer, (AttributesContainer) data, randomPrefix);
188 if (data instanceof SimpleNode<?>) {
190 if (schema instanceof LeafListSchemaNode || schema instanceof LeafSchemaNode) {
191 writeValue(writer, schema, data.getValue());
193 Object value = data.getValue();
195 writer.writeCharacters(String.valueOf(value));
200 final CompositeNode castedData = ((CompositeNode) data);
201 final DataNodeContainer castedSchema;
202 if (schema instanceof DataNodeContainer) {
203 castedSchema = (DataNodeContainer) schema;
207 final Collection<QName> keyLeaves;
208 if (schema instanceof ListSchemaNode) {
209 keyLeaves = ((ListSchemaNode) schema).getKeyDefinition();
212 keyLeaves = Collections.emptyList();
215 for (QName key : keyLeaves) {
216 SimpleNode<?> keyLeaf = castedData.getFirstSimpleByName(key);
217 if(keyLeaf != null) {
218 writeChildElement(writer,keyLeaf,castedSchema);
222 for (Node<?> child : castedData.getValue()) {
223 if(keyLeaves.contains(child.getNodeType())) {
224 // Skip key leaf which was written by previous for loop.
227 writeChildElement(writer,child,castedSchema);
232 private void writeChildElement(final XMLStreamWriter writer, final Node<?> child, final DataNodeContainer parentSchema) throws XMLStreamException {
233 DataSchemaNode childSchema = null;
234 if (parentSchema != null) {
235 childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), parentSchema.getChildNodes()).orNull();
236 if ((childSchema == null) && LOG.isDebugEnabled()) {
237 LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
240 writeElement(writer, child, childSchema);
243 private static void writeAttributes(final XMLStreamWriter writer, final AttributesContainer data, final RandomPrefix randomPrefix) throws XMLStreamException {
244 for (Entry<QName, String> attribute : data.getAttributes().entrySet()) {
245 writeAttribute(writer, attribute, randomPrefix);
249 private static boolean hasAttributes(final Node<?> data) {
250 if (data instanceof AttributesContainer) {
251 final Map<QName, String> c = ((AttributesContainer) data).getAttributes();
252 return c != null && !c.isEmpty();
259 static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
260 throws XMLStreamException {
261 final QName key = attribute.getKey();
262 final String prefix = randomPrefix.encodePrefix(key.getNamespace());
263 writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
264 writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
268 * Write a value into a XML stream writer. This method assumes the start and end of element is
269 * emitted by the caller.
271 * @param writer XML Stream writer
272 * @param schemaNode Schema node that describes the value
273 * @param value data value
274 * @throws XMLStreamException if an encoding problem occurs
276 public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull SchemaNode schemaNode, final Object value) throws XMLStreamException {
278 LOG.debug("Value of {}:{} is null, not encoding it", schemaNode.getQName().getNamespace(), schemaNode.getQName().getLocalName());
282 Preconditions.checkArgument(schemaNode instanceof LeafSchemaNode || schemaNode instanceof LeafListSchemaNode,
283 "Unable to write value for node %s, only nodes of type: leaf and leaf-list can be written at this point", schemaNode.getQName());
285 TypeDefinition<?> type = schemaNode instanceof LeafSchemaNode ?
286 ((LeafSchemaNode) schemaNode).getType():
287 ((LeafListSchemaNode) schemaNode).getType();
289 TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
291 if (schemaContext.isPresent() && baseType instanceof LeafrefTypeDefinition) {
292 LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
293 baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaContext.get(), schemaNode);
296 writeValue(writer, baseType, value);
300 * Write a value into a XML stream writer. This method assumes the start and end of element is
301 * emitted by the caller.
303 * @param writer XML Stream writer
304 * @param type data type. In case of leaf ref this should be the type of leaf being referenced
305 * @param value data value
306 * @throws XMLStreamException if an encoding problem occurs
308 public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
310 LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
313 TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
315 if (baseType instanceof IdentityrefTypeDefinition) {
316 write(writer, (IdentityrefTypeDefinition) baseType, value);
317 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
318 write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
320 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
324 text = codec.serialize(value);
325 } catch (ClassCastException e) {
326 LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
327 text = String.valueOf(value);
330 LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
331 text = String.valueOf(value);
333 writer.writeCharacters(text);
337 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
338 if (value instanceof QName) {
339 final QName qname = (QName) value;
340 final String prefix = "x";
342 final String ns = qname.getNamespace().toString();
343 writer.writeNamespace(prefix, ns);
344 writer.writeCharacters(prefix + ':' + qname.getLocalName());
346 LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
347 writer.writeCharacters(String.valueOf(value));
351 private void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
352 if (value instanceof YangInstanceIdentifier) {
353 writeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
355 LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
356 writer.writeCharacters(String.valueOf(value));
360 public void writeInstanceIdentifier(XMLStreamWriter writer, YangInstanceIdentifier value) throws XMLStreamException {
361 if(schemaContext.isPresent()) {
362 RandomPrefixInstanceIdentifierSerializer iiCodec = new RandomPrefixInstanceIdentifierSerializer(schemaContext.get());
363 String serializedValue = iiCodec.serialize(value);
364 writeNamespaceDeclarations(writer,iiCodec.getPrefixes());
365 writer.writeCharacters(serializedValue);
367 LOG.warn("Schema context not present in {}, serializing {} without schema.",this,value);
372 private static void writeNamespaceDeclarations(XMLStreamWriter writer, Iterable<Entry<URI, String>> prefixes) throws XMLStreamException {
373 for (Entry<URI, String> e: prefixes) {
374 final String ns = e.getKey().toString();
375 final String p = e.getValue();
376 writer.writeNamespace(p, ns);
380 public static XmlStreamUtils create(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
381 return new XmlStreamUtils(codecProvider, schemaContext);