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