1ea337039e99465bb56fa425b5f2e112b406f632
[yangtools.git] / yang / yang-data-codec-xml / src / main / java / org / opendaylight / yangtools / yang / data / codec / xml / XmlParserStream.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.yangtools.yang.data.codec.xml;
10
11 import com.google.common.base.Preconditions;
12 import java.io.Closeable;
13 import java.io.Flushable;
14 import java.io.IOException;
15 import java.io.StringReader;
16 import java.net.URI;
17 import java.net.URISyntaxException;
18 import java.util.Deque;
19 import java.util.HashSet;
20 import java.util.Set;
21 import javax.xml.parsers.DocumentBuilder;
22 import javax.xml.parsers.DocumentBuilderFactory;
23 import javax.xml.parsers.ParserConfigurationException;
24 import javax.xml.stream.XMLStreamConstants;
25 import javax.xml.stream.XMLStreamException;
26 import javax.xml.stream.XMLStreamReader;
27 import javax.xml.transform.dom.DOMSource;
28 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
29 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
30 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
31 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
32 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
33 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
34 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
35 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
36 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
37 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
38 import org.opendaylight.yangtools.yang.data.util.RpcAsContainer;
39 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
40 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.YangModeledAnyXmlSchemaNode;
46 import org.w3c.dom.Document;
47 import org.xml.sax.InputSource;
48 import org.xml.sax.SAXException;
49
50 /**
51  * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
52  * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
53  * the XML source are wrapped in a root element.
54  */
55 public final class XmlParserStream implements Closeable, Flushable {
56
57     private String rootElement = null;
58     private final NormalizedNodeStreamWriter writer;
59     private final XmlCodecFactory codecs;
60     private final SchemaContext schema;
61     private final DataSchemaNode parentNode;
62
63     private XmlParserStream(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
64                              final DataSchemaNode parentNode) {
65         this.schema = Preconditions.checkNotNull(schemaContext);
66         this.writer = Preconditions.checkNotNull(writer);
67         this.codecs = XmlCodecFactory.create(schemaContext);
68         this.parentNode = parentNode;
69     }
70
71     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
72             final SchemaNode parentNode ) {
73         if (parentNode instanceof RpcDefinition) {
74             return new XmlParserStream(writer, schemaContext, new RpcAsContainer((RpcDefinition) parentNode));
75         }
76         Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
77         return new XmlParserStream(writer, schemaContext, (DataSchemaNode) parentNode);
78     }
79
80     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext) {
81         return new XmlParserStream(writer, schemaContext, schemaContext);
82     }
83
84     /**
85      * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
86      * YANG-modeled data contained in the XML source.
87      *
88      * @param reader
89      *              StAX reader which is to used to walk through the XML source
90      * @return
91      *              instance of XmlParserStream
92      * @throws XMLStreamException
93      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
94      * @throws URISyntaxException
95      *              if the namespace URI of an XML element contains a syntax error
96      * @throws IOException
97      *              if an error occurs while parsing the value of an anyxml node
98      * @throws ParserConfigurationException
99      *              if an error occurs while parsing the value of an anyxml node
100      * @throws SAXException
101      *              if an error occurs while parsing the value of an anyxml node
102      */
103     public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
104             IOException, ParserConfigurationException, SAXException {
105         if (reader.hasNext()) {
106             final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
107             reader.nextTag();
108             rootElement = reader.getLocalName();
109             read(reader, compositeNodeDataWithSchema);
110             compositeNodeDataWithSchema.write(writer);
111         }
112
113         return this;
114     }
115
116     private static String readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
117         String result = "";
118         String anyXmlElementName = in.getLocalName();
119
120         while (in.hasNext()) {
121             int eventType = in.next();
122
123             if (eventType == XMLStreamConstants.START_ELEMENT) {
124                 result += "<" + in.getLocalName() + ">";
125             } else if (eventType == XMLStreamConstants.END_ELEMENT) {
126                 if (in.getLocalName().equals(anyXmlElementName)) {
127                     break;
128                 }
129
130                 result += "</" + in.getLocalName() + ">";
131             } else if (eventType == XMLStreamConstants.CHARACTERS) {
132                 result += in.getText();
133             }
134         }
135
136         return result;
137     }
138
139     private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema parent) throws XMLStreamException,
140             URISyntaxException, ParserConfigurationException, SAXException, IOException {
141         if (in.hasNext()) {
142             if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
143                 setValue(parent, in.getElementText().trim());
144                 in.nextTag();
145                 return;
146             } else if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
147                 String parentSchemaName = parent.getSchema().getQName().getLocalName();
148                 String xmlElementName = in.getLocalName();
149                 while (xmlElementName.equals(parentSchemaName)) {
150                     AbstractNodeDataWithSchema newChild = newEntryNode(parent);
151                     read(in, newChild);
152                     xmlElementName = in.getLocalName();
153                 }
154
155                 return;
156             } else if (parent instanceof AnyXmlNodeDataWithSchema) {
157                 setValue(parent, readAnyXmlValue(in));
158                 in.nextTag();
159                 return;
160             }
161
162             switch (in.nextTag()) {
163                 case XMLStreamConstants.START_ELEMENT:
164                     final Set<String> namesakes = new HashSet<>();
165                     while (in.hasNext()) {
166                         String xmlElementName = in.getLocalName();
167                         String xmlElementNamespace = in.getNamespaceURI();
168
169                         if (xmlElementName.equals(rootElement)) {
170                             break;
171                         }
172
173                         DataSchemaNode parentSchema = parent.getSchema();
174                         if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
175                             parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
176                         }
177
178                         String parentSchemaName = parentSchema.getQName().getLocalName();
179                         if (parentSchemaName.equals(xmlElementName)
180                                 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
181                             in.nextTag();
182                             break;
183                         }
184
185                         if (namesakes.contains(xmlElementName)) {
186                             int lineNumber = in.getLocation().getLineNumber();
187                             int columnNumber = in.getLocation().getColumnNumber();
188                             throw new IllegalStateException("Duplicate element \"" + xmlElementName + "\" in XML " +
189                                     "input at: line " + lineNumber + " column " + columnNumber);
190                         }
191                         namesakes.add(xmlElementName);
192
193                         Deque<DataSchemaNode> childDataSchemaNodes = ParserStreamUtils.findSchemaNodeByNameAndNamespace(
194                                 parentSchema, xmlElementName, new URI(xmlElementNamespace));
195
196                         if (childDataSchemaNodes.isEmpty()) {
197                             throw new IllegalStateException("Schema for node with name " + xmlElementName +
198                                     " and namespace " + xmlElementNamespace + " doesn't exist.");
199                         }
200
201                         AbstractNodeDataWithSchema newChild =
202                                 ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
203
204                         read(in, newChild);
205                     }
206                     break;
207                 case XMLStreamConstants.END_ELEMENT:
208                     in.nextTag();
209                     break;
210             }
211         }
212     }
213
214     private void setValue(final AbstractNodeDataWithSchema parent, final String value) throws
215             ParserConfigurationException, SAXException, IOException {
216         Preconditions.checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
217                 parent.getSchema().getQName());
218         final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
219         Preconditions.checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
220                 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
221
222         final Object translatedValue = translateValueByType(value, parentSimpleNode.getSchema());
223         parentSimpleNode.setValue(translatedValue);
224     }
225
226     private Object translateValueByType(final String value, final DataSchemaNode node) throws IOException,
227             SAXException, ParserConfigurationException {
228         if (node instanceof AnyXmlSchemaNode) {
229             /*
230              *  FIXME: Figure out some YANG extension dispatch, which will
231              *  reuse JSON parsing or XML parsing - anyxml is not well-defined in
232              * JSON.
233              */
234             DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
235             Document doc = db.parse( new InputSource(new StringReader(value)));
236             doc.normalize();
237             DOMSource anyXmlValueSource = new DOMSource(doc);
238
239             return anyXmlValueSource;
240         }
241         return codecs.codecFor(node).deserialize(value);
242     }
243
244     private static AbstractNodeDataWithSchema newEntryNode(final AbstractNodeDataWithSchema parent) {
245         AbstractNodeDataWithSchema newChild;
246         if (parent instanceof ListNodeDataWithSchema) {
247             newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
248         } else {
249             newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
250         }
251         ((CompositeNodeDataWithSchema) parent).addChild(newChild);
252         return newChild;
253     }
254
255     @Override
256     public void close() throws IOException {
257         writer.flush();
258         writer.close();
259     }
260
261     @Override
262     public void flush() throws IOException {
263         writer.flush();
264     }
265 }