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.Preconditions;
8 import java.util.Map.Entry;
10 import javax.annotation.Nonnull;
11 import javax.annotation.Nullable;
12 import javax.xml.stream.XMLStreamException;
13 import javax.xml.stream.XMLStreamWriter;
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
17 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
18 import org.opendaylight.yangtools.yang.data.api.Node;
19 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
21 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
22 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
23 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
24 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
29 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
30 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
35 * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
36 * by no means final and subject to change as more functionality is centralized here.
39 public class XmlStreamUtils {
40 private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
41 private final XmlCodecProvider codecProvider;
43 protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
44 this.codecProvider = Preconditions.checkNotNull(codecProvider);
48 * Create a new instance encapsulating a particular codec provider.
50 * @param codecProvider XML codec provider
51 * @return A new instance
53 public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
54 return new XmlStreamUtils(codecProvider);
58 * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
59 * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
61 * @param data Data node
62 * @return True if the data node will result in empty element body.
64 public static boolean isEmptyElement(final Node<?> data) {
69 if (data instanceof CompositeNode) {
70 return ((CompositeNode) data).getValue().isEmpty();
72 if (data instanceof SimpleNode) {
73 return data.getValue() == null;
81 * Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
82 * and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
84 * @param writer XML Stream writer
85 * @param id InstanceIdentifier
86 * @throws XMLStreamException
88 public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
89 Preconditions.checkNotNull(writer, "Writer may not be null");
90 Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
92 final RandomPrefix prefixes = new RandomPrefix();
93 final String str = XmlUtils.encodeIdentifier(prefixes, id);
95 for (Entry<URI, String> e: prefixes.getPrefixes()) {
96 writer.writeNamespace(e.getValue(), e.getKey().toString());
98 writer.writeCharacters(str);
102 * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
104 * @param writer XML Stream writer
105 * @param data data node
106 * @param schema corresponding schema node, may be null
107 * @throws XMLStreamException if an encoding problem occurs
109 public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
110 // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
111 // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
113 writer.writeStartDocument();
114 writeElement(writer, data, schema);
115 writer.writeEndDocument();
120 * Short-hand for {@link #writeDataDocument(XMLStreamWriter, CompositeNode, SchemaNode, XmlCodecProvider)} with
123 * @param writer XML Stream writer
124 * @param data data node
125 * @param schema corresponding schema node, may be null
126 * @throws XMLStreamException if an encoding problem occurs
128 public void writeDocument(final XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
129 writeDocument(writer, data, null);
133 * Write an element into a XML stream writer. This includes the element start/end tags and
134 * the value of the element.
136 * @param writer XML Stream writer
137 * @param data data node
138 * @param schema Schema node
139 * @throws XMLStreamException if an encoding problem occurs
141 public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
142 final QName qname = data.getNodeType();
143 final String pfx = qname.getPrefix() != null ? qname.getPrefix() : "";
144 final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
146 if (isEmptyElement(data)) {
147 writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
151 writer.writeStartElement(pfx, qname.getLocalName(), ns);
152 writeValue(writer, data, schema);
153 writer.writeEndElement();
157 * Write a value into a XML stream writer. This method assumes the start and end of element is
158 * emitted by the caller.
160 * @param writer XML Stream writer
161 * @param data data node
162 * @param schema Schema node
163 * @throws XMLStreamException if an encoding problem occurs
165 public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
166 if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
167 RandomPrefix randomPrefix = new RandomPrefix();
168 for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
169 writeAttribute(writer, attribute, randomPrefix);
173 if (data instanceof SimpleNode<?>) {
175 if (schema instanceof LeafListSchemaNode) {
176 writeValue(writer, ((LeafListSchemaNode) schema).getType(), data.getValue());
177 } else if (schema instanceof LeafSchemaNode) {
178 writeValue(writer, ((LeafSchemaNode) schema).getType(), data.getValue());
180 Object value = data.getValue();
182 writer.writeCharacters(String.valueOf(value));
187 for (Node<?> child : ((CompositeNode) data).getValue()) {
188 DataSchemaNode childSchema = null;
189 if (schema instanceof DataNodeContainer) {
190 childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
191 if (LOG.isDebugEnabled()) {
192 if (childSchema == null) {
193 LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
198 writeElement(writer, child, childSchema);
204 static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
205 throws XMLStreamException {
206 final QName key = attribute.getKey();
207 final String prefix = randomPrefix.encodePrefix(key.getNamespace());
208 writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
209 writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
213 * Write a value into a XML stream writer. This method assumes the start and end of element is
214 * emitted by the caller.
216 * @param writer XML Stream writer
217 * @param type data type
218 * @param value data value
219 * @throws XMLStreamException if an encoding problem occurs
221 public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
223 LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
227 final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
228 if (baseType instanceof IdentityrefTypeDefinition) {
229 write(writer, (IdentityrefTypeDefinition) baseType, value);
230 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
231 write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
233 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
237 text = codec.serialize(value);
238 } catch (ClassCastException e) {
239 LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
240 text = String.valueOf(value);
243 LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
244 text = String.valueOf(value);
246 writer.writeCharacters(text);
250 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
251 if (value instanceof QName) {
252 final QName qname = (QName) value;
254 if (qname.getPrefix() != null && !qname.getPrefix().isEmpty()) {
255 prefix = qname.getPrefix();
260 writer.writeNamespace(prefix, qname.getNamespace().toString());
261 writer.writeCharacters(prefix + ':' + qname.getLocalName());
263 LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
264 writer.writeCharacters(String.valueOf(value));
268 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
269 if (value instanceof YangInstanceIdentifier) {
270 write(writer, (YangInstanceIdentifier)value);
272 LOG.debug("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
273 writer.writeCharacters(String.valueOf(value));