Allow JSON/XML writers to be instantiated with root node
[yangtools.git] / yang / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / JSONNormalizedNodeStreamWriter.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.yangtools.yang.data.codec.gson;
9
10 import static java.util.Objects.requireNonNull;
11 import static org.w3c.dom.Node.ELEMENT_NODE;
12 import static org.w3c.dom.Node.TEXT_NODE;
13
14 import com.google.gson.stream.JsonWriter;
15 import java.io.IOException;
16 import java.net.URI;
17 import java.util.regex.Pattern;
18 import javax.annotation.RegEx;
19 import javax.xml.transform.dom.DOMSource;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
24 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
25 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
26 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
28 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
32 import org.w3c.dom.Element;
33 import org.w3c.dom.Node;
34 import org.w3c.dom.NodeList;
35 import org.w3c.dom.Text;
36
37 /**
38  * This implementation will create JSON output as output stream.
39  *
40  * <p>
41  * Values of leaf and leaf-list are NOT translated according to codecs.
42  */
43 public abstract class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
44     private static final class Exclusive extends JSONNormalizedNodeStreamWriter {
45         Exclusive(final JSONCodecFactory codecFactory, final SchemaTracker tracker, final JsonWriter writer,
46                 final JSONStreamWriterRootContext rootContext) {
47             super(codecFactory, tracker, writer, rootContext);
48         }
49
50         @Override
51         public void close() throws IOException {
52             flush();
53             closeWriter();
54         }
55     }
56
57     private static final class Nested extends JSONNormalizedNodeStreamWriter {
58         Nested(final JSONCodecFactory codecFactory, final SchemaTracker tracker, final JsonWriter writer,
59                 final JSONStreamWriterRootContext rootContext) {
60             super(codecFactory, tracker, writer, rootContext);
61         }
62
63         @Override
64         public void close() throws IOException {
65             flush();
66             // The caller "owns" the writer, let them close it
67         }
68     }
69
70     /**
71      * RFC6020 deviation: we are not required to emit empty containers unless they
72      * are marked as 'presence'.
73      */
74     private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
75
76     @RegEx
77     private static final String NUMBER_STRING = "-?\\d+(\\.\\d+)?";
78     private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_STRING);
79
80     @RegEx
81     private static final String NOT_DECIMAL_NUMBER_STRING = "-?\\d+";
82     private static final Pattern NOT_DECIMAL_NUMBER_PATTERN = Pattern.compile(NOT_DECIMAL_NUMBER_STRING);
83
84     private final SchemaTracker tracker;
85     private final JSONCodecFactory codecs;
86     private final JsonWriter writer;
87     private JSONStreamWriterContext context;
88
89     JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaTracker tracker,
90             final JsonWriter writer, final JSONStreamWriterRootContext rootContext) {
91         this.writer = requireNonNull(writer);
92         this.codecs = requireNonNull(codecFactory);
93         this.tracker = requireNonNull(tracker);
94         this.context = requireNonNull(rootContext);
95     }
96
97     /**
98      * Create a new stream writer, which writes to the specified output stream.
99      *
100      * <p>
101      * The codec factory can be reused between multiple writers.
102      *
103      * <p>
104      * Returned writer is exclusive user of JsonWriter, which means it will start
105      * top-level JSON element and ends it.
106      *
107      * <p>
108      * This instance of writer can be used only to emit one top level element,
109      * otherwise it will produce incorrect JSON. Closing this instance will close
110      * the writer too.
111      *
112      * @param codecFactory JSON codec factory
113      * @param path Schema Path
114      * @param initialNs Initial namespace
115      * @param jsonWriter JsonWriter
116      * @return A stream writer instance
117      */
118     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
119             final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
120         return new Exclusive(codecFactory, SchemaTracker.create(codecFactory.getSchemaContext(), path), jsonWriter,
121             new JSONStreamWriterExclusiveRootContext(initialNs));
122     }
123
124     /**
125      * Create a new stream writer, which writes to the specified output stream.
126      *
127      * <p>
128      * The codec factory can be reused between multiple writers.
129      *
130      * <p>
131      * Returned writer is exclusive user of JsonWriter, which means it will start
132      * top-level JSON element and ends it.
133      *
134      * <p>
135      * This instance of writer can be used only to emit one top level element,
136      * otherwise it will produce incorrect JSON. Closing this instance will close
137      * the writer too.
138      *
139      * @param codecFactory JSON codec factory
140      * @param rootNode Root node
141      * @param initialNs Initial namespace
142      * @param jsonWriter JsonWriter
143      * @return A stream writer instance
144      */
145     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
146             final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
147         return new Exclusive(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
148             new JSONStreamWriterExclusiveRootContext(initialNs));
149     }
150
151     /**
152      * Create a new stream writer, which writes to the specified output stream.
153      *
154      * <p>
155      * The codec factory can be reused between multiple writers.
156      *
157      * <p>
158      * Returned writer can be used emit multiple top level element,
159      * but does not start / close parent JSON object, which must be done
160      * by user providing {@code jsonWriter} instance in order for
161      * JSON to be valid. Closing this instance <strong>will not</strong>
162      * close the wrapped writer; the caller must take care of that.
163      *
164      * @param codecFactory JSON codec factory
165      * @param path Schema Path
166      * @param initialNs Initial namespace
167      * @param jsonWriter JsonWriter
168      * @return A stream writer instance
169      */
170     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
171             final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
172         return new Nested(codecFactory, SchemaTracker.create(codecFactory.getSchemaContext(), path), jsonWriter,
173             new JSONStreamWriterSharedRootContext(initialNs));
174     }
175
176     /**
177      * Create a new stream writer, which writes to the specified output stream.
178      *
179      * <p>
180      * The codec factory can be reused between multiple writers.
181      *
182      * <p>
183      * Returned writer can be used emit multiple top level element,
184      * but does not start / close parent JSON object, which must be done
185      * by user providing {@code jsonWriter} instance in order for
186      * JSON to be valid. Closing this instance <strong>will not</strong>
187      * close the wrapped writer; the caller must take care of that.
188      *
189      * @param codecFactory JSON codec factory
190      * @param rootNode Root node
191      * @param initialNs Initial namespace
192      * @param jsonWriter JsonWriter
193      * @return A stream writer instance
194      */
195     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
196             final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
197         return new Nested(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
198             new JSONStreamWriterSharedRootContext(initialNs));
199     }
200
201     @Override
202     public final void leafNode(final NodeIdentifier name, final Object value) throws IOException {
203         final LeafSchemaNode schema = tracker.leafNode(name);
204         final JSONCodec<?> codec = codecs.codecFor(schema);
205         context.emittingChild(codecs.getSchemaContext(), writer);
206         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
207         writeValue(value, codec);
208     }
209
210     @Override
211     public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
212         tracker.startLeafSet(name);
213         context = new JSONStreamWriterListContext(context, name);
214     }
215
216     @Override
217     public final void leafSetEntryNode(final QName name, final Object value) throws IOException {
218         final LeafListSchemaNode schema = tracker.leafSetEntryNode(name);
219         final JSONCodec<?> codec = codecs.codecFor(schema);
220         context.emittingChild(codecs.getSchemaContext(), writer);
221         writeValue(value, codec);
222     }
223
224     @Override
225     public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
226         tracker.startLeafSet(name);
227         context = new JSONStreamWriterListContext(context, name);
228     }
229
230     /*
231      * Warning suppressed due to static final constant which triggers a warning
232      * for the call to schema.isPresenceContainer().
233      */
234     @Override
235     public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
236         final SchemaNode schema = tracker.startContainerNode(name);
237         final boolean isPresence = schema instanceof ContainerSchemaNode
238             ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
239         context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
240     }
241
242     @Override
243     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
244         tracker.startList(name);
245         context = new JSONStreamWriterListContext(context, name);
246     }
247
248     @Override
249     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
250         tracker.startListItem(name);
251         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
252     }
253
254     @Override
255     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
256         tracker.startList(name);
257         context = new JSONStreamWriterListContext(context, name);
258     }
259
260     @Override
261     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
262             throws IOException {
263         tracker.startListItem(identifier);
264         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
265     }
266
267     @Override
268     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
269         tracker.startList(name);
270         context = new JSONStreamWriterListContext(context, name);
271     }
272
273     @Override
274     public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
275         tracker.startChoiceNode(name);
276         context = new JSONStreamWriterInvisibleContext(context);
277     }
278
279     @Override
280     public final void startAugmentationNode(final AugmentationIdentifier identifier) {
281         tracker.startAugmentationNode(identifier);
282         context = new JSONStreamWriterInvisibleContext(context);
283     }
284
285     @Override
286     public final void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
287         // FIXME: should have a codec based on this :)
288         tracker.anyxmlNode(name);
289
290         context.emittingChild(codecs.getSchemaContext(), writer);
291         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
292
293         writeAnyXmlValue((DOMSource) value);
294     }
295
296     @Override
297     public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
298             throws IOException {
299         tracker.startYangModeledAnyXmlNode(name);
300         context = new JSONStreamWriterNamedObjectContext(context, name, true);
301     }
302
303     @Override
304     public final void endNode() throws IOException {
305         tracker.endNode();
306         context = context.endNode(codecs.getSchemaContext(), writer);
307
308         if (context instanceof JSONStreamWriterRootContext) {
309             context.emitEnd(writer);
310         }
311     }
312
313     @Override
314     public final void flush() throws IOException {
315         writer.flush();
316     }
317
318     final void closeWriter() throws IOException {
319         writer.close();
320     }
321
322     @SuppressWarnings("unchecked")
323     private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
324         ((JSONCodec<Object>) codec).writeValue(writer, value);
325     }
326
327     private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
328         writeXmlNode(anyXmlValue.getNode());
329     }
330
331     private void writeXmlNode(final Node node) throws IOException {
332         if (isArrayElement(node)) {
333             writeArrayContent(node);
334             return;
335         }
336         final Element firstChildElement = getFirstChildElement(node);
337         if (firstChildElement == null) {
338             writeXmlValue(node);
339         } else {
340             writeObjectContent(firstChildElement);
341         }
342     }
343
344     private void writeArrayContent(final Node node) throws IOException {
345         writer.beginArray();
346         handleArray(node);
347         writer.endArray();
348     }
349
350     private void writeObjectContent(final Element firstChildElement) throws IOException {
351         writer.beginObject();
352         writeObject(firstChildElement);
353         writer.endObject();
354     }
355
356     private static boolean isArrayElement(final Node node) {
357         if (ELEMENT_NODE == node.getNodeType()) {
358             final String nodeName = node.getNodeName();
359             for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
360                 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
361                     return true;
362                 }
363             }
364         }
365         return false;
366     }
367
368     private void handleArray(final Node node) throws IOException {
369         final Element parentNode = (Element)node.getParentNode();
370         final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
371         for (int i = 0, length = elementsList.getLength(); i < length; i++) {
372             final Node arrayElement = elementsList.item(i);
373             final Element parent = (Element)arrayElement.getParentNode();
374             if (parentNode.isSameNode(parent)) {
375                 final Element firstChildElement = getFirstChildElement(arrayElement);
376                 if (firstChildElement != null) {
377                     writeObjectContent(firstChildElement);
378                 } else {
379                     // It may be scalar
380                     writeXmlValue(arrayElement);
381                 }
382             }
383         }
384     }
385
386     private void writeObject(Node node) throws IOException {
387         String previousNodeName = "";
388         while (node != null) {
389             if (ELEMENT_NODE == node.getNodeType()) {
390                 if (!node.getNodeName().equals(previousNodeName)) {
391                     previousNodeName = node.getNodeName();
392                     writer.name(node.getNodeName());
393                     writeXmlNode(node);
394                 }
395             }
396             node = node.getNextSibling();
397         }
398     }
399
400     private void writeXmlValue(final Node node) throws IOException {
401         Text firstChild = getFirstChildText(node);
402         String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
403         childNodeText = childNodeText != null ? childNodeText.trim() : "";
404
405         if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
406             writer.value(parseNumber(childNodeText));
407             return;
408         }
409         switch (childNodeText) {
410             case "null":
411                 writer.nullValue();
412                 break;
413             case "false":
414                 writer.value(false);
415                 break;
416             case "true":
417                 writer.value(true);
418                 break;
419             default:
420                 writer.value(childNodeText);
421         }
422     }
423
424     private static Element getFirstChildElement(final Node node) {
425         final NodeList children = node.getChildNodes();
426         for (int i = 0, length = children.getLength(); i < length; i++) {
427             final Node childNode = children.item(i);
428             if (ELEMENT_NODE == childNode.getNodeType()) {
429                 return (Element) childNode;
430             }
431         }
432         return null;
433     }
434
435     private static Text getFirstChildText(final Node node) {
436         final NodeList children = node.getChildNodes();
437         for (int i = 0, length = children.getLength(); i < length; i++) {
438             final Node childNode = children.item(i);
439             if (TEXT_NODE == childNode.getNodeType()) {
440                 return (Text) childNode;
441             }
442         }
443         return null;
444     }
445
446     // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
447     private static Number parseNumber(final String numberText) {
448         if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
449             return Long.valueOf(numberText);
450         }
451
452         return Double.valueOf(numberText);
453     }
454 }