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;
9 import javax.annotation.Nonnull;
10 import javax.annotation.Nullable;
11 import javax.xml.stream.XMLStreamException;
12 import javax.xml.stream.XMLStreamWriter;
13 import org.opendaylight.yangtools.yang.common.QName;
14 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
15 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
16 import org.opendaylight.yangtools.yang.data.api.Node;
17 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
20 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
21 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
22 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
27 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
28 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
34 * by no means final and subject to change as more functionality is centralized here.
37 public class XmlStreamUtils {
38 private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
39 private final XmlCodecProvider codecProvider;
41 protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
42 this.codecProvider = Preconditions.checkNotNull(codecProvider);
46 * Create a new instance encapsulating a particular codec provider.
48 * @param codecProvider XML codec provider
49 * @return A new instance
51 public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
52 return new XmlStreamUtils(codecProvider);
56 * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
57 * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
59 * @param data Data node
60 * @return True if the data node will result in empty element body.
62 public static boolean isEmptyElement(final Node<?> data) {
67 if (data instanceof CompositeNode) {
68 return ((CompositeNode) data).getValue().isEmpty();
70 if (data instanceof SimpleNode) {
71 return data.getValue() == null;
79 * Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
80 * and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
82 * @param writer XML Stream writer
83 * @param id InstanceIdentifier
84 * @throws XMLStreamException
86 public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
87 Preconditions.checkNotNull(writer, "Writer may not be null");
88 Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
90 final RandomPrefix prefixes = new RandomPrefix();
91 final String str = XmlUtils.encodeIdentifier(prefixes, id);
93 for (Entry<URI, String> e: prefixes.getPrefixes()) {
94 final String ns = e.getKey().toString();
95 final String p = e.getValue();
97 writer.writeNamespace(p, ns);
99 writer.writeCharacters(str);
103 * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
105 * @param writer XML Stream writer
106 * @param data data node
107 * @param schema corresponding schema node, may be null
108 * @throws XMLStreamException if an encoding problem occurs
110 public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
111 // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
112 // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
114 writer.writeStartDocument();
115 writeElement(writer, data, schema);
116 writer.writeEndDocument();
121 * Short-hand for {@link #writeDocument(XMLStreamWriter, CompositeNode, SchemaNode)})} with
124 * @param writer XML Stream writer
125 * @param data data node
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 if (hasAttributes(data)) {
148 writer.writeStartElement(pfx, qname.getLocalName(), ns);
149 final RandomPrefix randomPrefix = new RandomPrefix();
150 writeAttributes(writer, (AttributesContainer) data, randomPrefix);
151 writer.writeEndElement();
153 writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
158 writer.writeStartElement(pfx, qname.getLocalName(), ns);
159 writeValue(writer, data, schema);
160 writer.writeEndElement();
164 * Write a value into a XML stream writer. This method assumes the start and end of element is
165 * emitted by the caller.
167 * @param writer XML Stream writer
168 * @param data data node
169 * @param schema Schema node
170 * @throws XMLStreamException if an encoding problem occurs
172 public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
173 if (hasAttributes(data)) {
174 RandomPrefix randomPrefix = new RandomPrefix();
175 writeAttributes(writer, (AttributesContainer) data, randomPrefix);
178 if (data instanceof SimpleNode<?>) {
180 if (schema instanceof LeafListSchemaNode) {
181 writeValue(writer, ((LeafListSchemaNode) schema).getType(), data.getValue());
182 } else if (schema instanceof LeafSchemaNode) {
183 writeValue(writer, ((LeafSchemaNode) schema).getType(), data.getValue());
185 Object value = data.getValue();
187 writer.writeCharacters(String.valueOf(value));
192 for (Node<?> child : ((CompositeNode) data).getValue()) {
193 DataSchemaNode childSchema = null;
194 if (schema instanceof DataNodeContainer) {
195 childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
196 } else if ((childSchema == null) && LOG.isDebugEnabled()) {
197 LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
199 writeElement(writer, child, childSchema);
204 private static void writeAttributes(final XMLStreamWriter writer, final AttributesContainer data, final RandomPrefix randomPrefix) throws XMLStreamException {
205 for (Entry<QName, String> attribute : data.getAttributes().entrySet()) {
206 writeAttribute(writer, attribute, randomPrefix);
210 private static boolean hasAttributes(final Node<?> data) {
211 if (data instanceof AttributesContainer) {
212 final Map<QName, String> c = ((AttributesContainer) data).getAttributes();
213 return c != null && !c.isEmpty();
220 static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
221 throws XMLStreamException {
222 final QName key = attribute.getKey();
223 final String prefix = randomPrefix.encodePrefix(key.getNamespace());
224 writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
225 writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
229 * Write a value into a XML stream writer. This method assumes the start and end of element is
230 * emitted by the caller.
232 * @param writer XML Stream writer
233 * @param type data type
234 * @param value data value
235 * @throws XMLStreamException if an encoding problem occurs
237 public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
239 LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
243 final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
244 if (baseType instanceof IdentityrefTypeDefinition) {
245 write(writer, (IdentityrefTypeDefinition) baseType, value);
246 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
247 write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
249 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
253 text = codec.serialize(value);
254 } catch (ClassCastException e) {
255 LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
256 text = String.valueOf(value);
259 LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
260 text = String.valueOf(value);
262 writer.writeCharacters(text);
266 @SuppressWarnings("deprecation")
267 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
268 if (value instanceof QName) {
269 final QName qname = (QName) value;
271 if (qname.getPrefix() != null && !qname.getPrefix().isEmpty()) {
272 prefix = qname.getPrefix();
277 final String ns = qname.getNamespace().toString();
278 writer.writeNamespace(prefix, ns);
279 writer.writeCharacters(prefix + ':' + qname.getLocalName());
281 LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
282 writer.writeCharacters(String.valueOf(value));
286 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
287 if (value instanceof YangInstanceIdentifier) {
288 write(writer, (YangInstanceIdentifier)value);
290 LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
291 writer.writeCharacters(String.valueOf(value));