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 public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
100 Preconditions.checkNotNull(writer, "Writer may not be null");
101 Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
103 final RandomPrefix prefixes = new RandomPrefix();
104 final String str = XmlUtils.encodeIdentifier(prefixes, id);
106 for (Entry<URI, String> e: prefixes.getPrefixes()) {
107 final String ns = e.getKey().toString();
108 final String p = e.getValue();
110 writer.writeNamespace(p, ns);
112 writer.writeCharacters(str);
116 * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
118 * @param writer XML Stream writer
119 * @param data data node
120 * @param schema corresponding schema node, may be null
121 * @throws XMLStreamException if an encoding problem occurs
123 public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
124 // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
125 // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
127 writer.writeStartDocument();
128 writeElement(writer, data, schema);
129 writer.writeEndDocument();
134 * Short-hand for {@link #writeDocument(XMLStreamWriter, CompositeNode, SchemaNode)})} with
137 * @param writer XML Stream writer
138 * @param data data node
139 * @throws XMLStreamException if an encoding problem occurs
141 public void writeDocument(final XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
142 writeDocument(writer, data, null);
146 * Write an element into a XML stream writer. This includes the element start/end tags and
147 * the value of the element.
149 * @param writer XML Stream writer
150 * @param data data node
151 * @param schema Schema node
152 * @throws XMLStreamException if an encoding problem occurs
154 public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
155 final QName qname = data.getNodeType();
156 final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
157 final String pfx = "";
159 if (isEmptyElement(data)) {
160 if (hasAttributes(data)) {
161 writer.writeStartElement(pfx, qname.getLocalName(), ns);
162 final RandomPrefix randomPrefix = new RandomPrefix();
163 writeAttributes(writer, (AttributesContainer) data, randomPrefix);
164 writer.writeEndElement();
166 writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
171 writer.writeStartElement(pfx, qname.getLocalName(), ns);
172 writeValue(writer, data, schema);
173 writer.writeEndElement();
177 * Write a value into a XML stream writer. This method assumes the start and end of element is
178 * emitted by the caller.
180 * @param writer XML Stream writer
181 * @param data data node
182 * @param schema Schema node
183 * @throws XMLStreamException if an encoding problem occurs
185 public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
186 if (hasAttributes(data)) {
187 RandomPrefix randomPrefix = new RandomPrefix();
188 writeAttributes(writer, (AttributesContainer) data, randomPrefix);
191 if (data instanceof SimpleNode<?>) {
193 if (schema instanceof LeafListSchemaNode || schema instanceof LeafSchemaNode) {
194 writeValue(writer, schema, data.getValue());
196 Object value = data.getValue();
198 writer.writeCharacters(String.valueOf(value));
203 final CompositeNode castedData = ((CompositeNode) data);
204 final DataNodeContainer castedSchema;
205 if (schema instanceof DataNodeContainer) {
206 castedSchema = (DataNodeContainer) schema;
210 final Collection<QName> keyLeaves;
211 if (schema instanceof ListSchemaNode) {
212 keyLeaves = ((ListSchemaNode) schema).getKeyDefinition();
215 keyLeaves = Collections.emptyList();
218 for (QName key : keyLeaves) {
219 SimpleNode<?> keyLeaf = castedData.getFirstSimpleByName(key);
220 if(keyLeaf != null) {
221 writeChildElement(writer,keyLeaf,castedSchema);
225 for (Node<?> child : castedData.getValue()) {
226 if(keyLeaves.contains(child.getNodeType())) {
227 // Skip key leaf which was written by previous for loop.
230 writeChildElement(writer,child,castedSchema);
235 private void writeChildElement(final XMLStreamWriter writer, final Node<?> child, final DataNodeContainer parentSchema) throws XMLStreamException {
236 DataSchemaNode childSchema = null;
237 if (parentSchema != null) {
238 childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), parentSchema.getChildNodes()).orNull();
239 if ((childSchema == null) && LOG.isDebugEnabled()) {
240 LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
243 writeElement(writer, child, childSchema);
246 private static void writeAttributes(final XMLStreamWriter writer, final AttributesContainer data, final RandomPrefix randomPrefix) throws XMLStreamException {
247 for (Entry<QName, String> attribute : data.getAttributes().entrySet()) {
248 writeAttribute(writer, attribute, randomPrefix);
252 private static boolean hasAttributes(final Node<?> data) {
253 if (data instanceof AttributesContainer) {
254 final Map<QName, String> c = ((AttributesContainer) data).getAttributes();
255 return c != null && !c.isEmpty();
262 static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
263 throws XMLStreamException {
264 final QName key = attribute.getKey();
265 final String prefix = randomPrefix.encodePrefix(key.getNamespace());
266 writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
267 writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
271 * Write a value into a XML stream writer. This method assumes the start and end of element is
272 * emitted by the caller.
274 * @param writer XML Stream writer
275 * @param schemaNode Schema node that describes the value
276 * @param value data value
277 * @throws XMLStreamException if an encoding problem occurs
279 public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull SchemaNode schemaNode, final Object value) throws XMLStreamException {
281 LOG.debug("Value of {}:{} is null, not encoding it", schemaNode.getQName().getNamespace(), schemaNode.getQName().getLocalName());
285 Preconditions.checkArgument(schemaNode instanceof LeafSchemaNode || schemaNode instanceof LeafListSchemaNode,
286 "Unable to write value for node %s, only nodes of type: leaf and leaf-list can be written at this point", schemaNode.getQName());
288 TypeDefinition<?> type = schemaNode instanceof LeafSchemaNode ?
289 ((LeafSchemaNode) schemaNode).getType():
290 ((LeafListSchemaNode) schemaNode).getType();
292 TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
294 if (schemaContext.isPresent() && baseType instanceof LeafrefTypeDefinition) {
295 LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
296 baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaContext.get(), schemaNode);
299 writeValue(writer, baseType, value);
303 * Write a value into a XML stream writer. This method assumes the start and end of element is
304 * emitted by the caller.
306 * @param writer XML Stream writer
307 * @param type data type. In case of leaf ref this should be the type of leaf being referenced
308 * @param value data value
309 * @throws XMLStreamException if an encoding problem occurs
311 public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
313 LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
316 TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
318 if (baseType instanceof IdentityrefTypeDefinition) {
319 write(writer, (IdentityrefTypeDefinition) baseType, value);
320 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
321 write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
323 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
327 text = codec.serialize(value);
328 } catch (ClassCastException e) {
329 LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
330 text = String.valueOf(value);
333 LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
334 text = String.valueOf(value);
336 writer.writeCharacters(text);
340 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
341 if (value instanceof QName) {
342 final QName qname = (QName) value;
343 final String prefix = "x";
345 final String ns = qname.getNamespace().toString();
346 writer.writeNamespace(prefix, ns);
347 writer.writeCharacters(prefix + ':' + qname.getLocalName());
349 LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
350 writer.writeCharacters(String.valueOf(value));
354 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
355 if (value instanceof YangInstanceIdentifier) {
356 write(writer, (YangInstanceIdentifier)value);
358 LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
359 writer.writeCharacters(String.valueOf(value));
363 public static XmlStreamUtils create(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
364 return new XmlStreamUtils(codecProvider, schemaContext);