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.Map.Entry;
9 import javax.annotation.Nonnull;
10 import javax.xml.stream.XMLStreamException;
11 import javax.xml.stream.XMLStreamWriter;
12 import org.opendaylight.yangtools.yang.common.QName;
13 import org.opendaylight.yangtools.yang.common.QNameModule;
14 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
15 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
16 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
17 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
18 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
19 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
20 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
21 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
22 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
23 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
24 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
30 * by no means final and subject to change as more functionality is centralized here.
33 public class XmlStreamUtils {
34 private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
35 private final XmlCodecProvider codecProvider;
36 private final Optional<SchemaContext> schemaContext;
38 protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
39 this(codecProvider, null);
42 private XmlStreamUtils(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
43 this.codecProvider = Preconditions.checkNotNull(codecProvider);
44 this.schemaContext = Optional.fromNullable(schemaContext);
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 * Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
59 * and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
61 * @param writer XML Stream writer
62 * @param id InstanceIdentifier
63 * @throws XMLStreamException
65 * @deprecated Use {@link #writeInstanceIdentifier(XMLStreamWriter, YangInstanceIdentifier)} instead.
68 public static void write(@Nonnull final XMLStreamWriter writer, @Nonnull final YangInstanceIdentifier id) throws XMLStreamException {
69 Preconditions.checkNotNull(writer, "Writer may not be null");
70 Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
72 final RandomPrefix prefixes = new RandomPrefix();
73 final String str = XmlUtils.encodeIdentifier(prefixes, id);
74 writeNamespaceDeclarations(writer, prefixes.getPrefixes());
75 writer.writeCharacters(str);
79 static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
80 throws XMLStreamException {
81 final QName key = attribute.getKey();
82 final String prefix = randomPrefix.encodePrefix(key.getNamespace());
83 writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
84 writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
88 * Write a value into a XML stream writer. This method assumes the start and end of element is
89 * emitted by the caller.
91 * @param writer XML Stream writer
92 * @param schemaNode Schema node that describes the value
93 * @param value data value
94 * @param parent optional parameter of a module QName owning the leaf definition
95 * @throws XMLStreamException if an encoding problem occurs
97 public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
99 LOG.debug("Value of {}:{} is null, not encoding it", schemaNode.getQName().getNamespace(), schemaNode.getQName().getLocalName());
103 Preconditions.checkArgument(schemaNode instanceof LeafSchemaNode || schemaNode instanceof LeafListSchemaNode,
104 "Unable to write value for node %s, only nodes of type: leaf and leaf-list can be written at this point", schemaNode.getQName());
106 TypeDefinition<?> type = schemaNode instanceof LeafSchemaNode ?
107 ((LeafSchemaNode) schemaNode).getType():
108 ((LeafListSchemaNode) schemaNode).getType();
110 TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
112 if (schemaContext.isPresent() && baseType instanceof LeafrefTypeDefinition) {
113 LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
114 baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaContext.get(), schemaNode);
117 writeValue(writer, baseType, value, parent);
120 public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value) throws XMLStreamException {
121 writeValue(writer, schemaNode, value, Optional.<QNameModule>absent());
124 public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value, final QNameModule parent) throws XMLStreamException {
125 writeValue(writer, schemaNode, value, Optional.of(parent));
129 * Write a value into a XML stream writer. This method assumes the start and end of element is
130 * emitted by the caller.
132 * @param writer XML Stream writer
133 * @param type data type. In case of leaf ref this should be the type of leaf being referenced
134 * @param value data value
135 * @param parent optional parameter of a module QName owning the leaf definition
136 * @throws XMLStreamException if an encoding problem occurs
138 public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
140 LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
143 TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
145 if (baseType instanceof IdentityrefTypeDefinition) {
146 if (parent.isPresent()) {
147 write(writer, (IdentityrefTypeDefinition) baseType, value, parent);
149 write(writer, (IdentityrefTypeDefinition) baseType, value, Optional.<QNameModule>absent());
151 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
152 write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
154 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(type);
158 text = codec.serialize(value);
159 } catch (ClassCastException e) {
160 LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, type, e);
161 text = String.valueOf(value);
164 LOG.error("Failed to find codec for {}, falling back to using stream", type);
165 text = String.valueOf(value);
167 writer.writeCharacters(text);
171 public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value, final QNameModule parent) throws XMLStreamException {
172 writeValue(writer, type, value, Optional.of(parent));
175 public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value) throws XMLStreamException {
176 writeValue(writer, type, value, Optional.<QNameModule>absent());
180 static void write(@Nonnull final XMLStreamWriter writer, @Nonnull final IdentityrefTypeDefinition type, @Nonnull final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
181 if (value instanceof QName) {
182 final QName qname = (QName) value;
183 final String prefix = "x";
185 //in case parent is present and same as element namespace write value without namespace
186 if (parent.isPresent() && qname.getNamespace().equals(parent.get().getNamespace())){
187 writer.writeCharacters(qname.getLocalName());
189 final String ns = qname.getNamespace().toString();
190 writer.writeNamespace(prefix, ns);
191 writer.writeCharacters(prefix + ':' + qname.getLocalName());
195 LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
196 writer.writeCharacters(String.valueOf(value));
200 private void write(@Nonnull final XMLStreamWriter writer, @Nonnull final InstanceIdentifierTypeDefinition type, @Nonnull final Object value) throws XMLStreamException {
201 if (value instanceof YangInstanceIdentifier) {
202 writeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
204 LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
205 writer.writeCharacters(String.valueOf(value));
209 public void writeInstanceIdentifier(XMLStreamWriter writer, YangInstanceIdentifier value) throws XMLStreamException {
210 if(schemaContext.isPresent()) {
211 RandomPrefixInstanceIdentifierSerializer iiCodec = new RandomPrefixInstanceIdentifierSerializer(schemaContext.get());
212 String serializedValue = iiCodec.serialize(value);
213 writeNamespaceDeclarations(writer,iiCodec.getPrefixes());
214 writer.writeCharacters(serializedValue);
216 LOG.warn("Schema context not present in {}, serializing {} without schema.",this,value);
221 private static void writeNamespaceDeclarations(XMLStreamWriter writer, Iterable<Entry<URI, String>> prefixes) throws XMLStreamException {
222 for (Entry<URI, String> e: prefixes) {
223 final String ns = e.getKey().toString();
224 final String p = e.getValue();
225 writer.writeNamespace(p, ns);
229 public static XmlStreamUtils create(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
230 return new XmlStreamUtils(codecProvider, schemaContext);