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.AnyXmlSchemaNode;
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     @SuppressWarnings("unused")
235     @Override
236     public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
237         final SchemaNode schema = tracker.startContainerNode(name);
238
239         // FIXME this code ignores presence for containers
240         // but datastore does as well and it needs be fixed first (2399)
241         context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
242     }
243
244     @Override
245     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
246         tracker.startList(name);
247         context = new JSONStreamWriterListContext(context, name);
248     }
249
250     @Override
251     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
252         tracker.startListItem(name);
253         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
254     }
255
256     @Override
257     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
258         tracker.startList(name);
259         context = new JSONStreamWriterListContext(context, name);
260     }
261
262     @Override
263     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
264             throws IOException {
265         tracker.startListItem(identifier);
266         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
267     }
268
269     @Override
270     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
271         tracker.startList(name);
272         context = new JSONStreamWriterListContext(context, name);
273     }
274
275     @Override
276     public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
277         tracker.startChoiceNode(name);
278         context = new JSONStreamWriterInvisibleContext(context);
279     }
280
281     @Override
282     public final void startAugmentationNode(final AugmentationIdentifier identifier) {
283         tracker.startAugmentationNode(identifier);
284         context = new JSONStreamWriterInvisibleContext(context);
285     }
286
287     @Override
288     public final void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
289         @SuppressWarnings("unused")
290         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
291         // FIXME: should have a codec based on this :)
292
293         context.emittingChild(codecs.getSchemaContext(), writer);
294         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
295
296         writeAnyXmlValue((DOMSource) value);
297     }
298
299     @Override
300     public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
301             throws IOException {
302         tracker.startYangModeledAnyXmlNode(name);
303         context = new JSONStreamWriterNamedObjectContext(context, name, true);
304     }
305
306     @Override
307     public final void endNode() throws IOException {
308         tracker.endNode();
309         context = context.endNode(codecs.getSchemaContext(), writer);
310
311         if (context instanceof JSONStreamWriterRootContext) {
312             context.emitEnd(writer);
313         }
314     }
315
316     @Override
317     public final void flush() throws IOException {
318         writer.flush();
319     }
320
321     final void closeWriter() throws IOException {
322         writer.close();
323     }
324
325     @SuppressWarnings("unchecked")
326     private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
327         ((JSONCodec<Object>) codec).writeValue(writer, value);
328     }
329
330     private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
331         writeXmlNode(anyXmlValue.getNode());
332     }
333
334     private void writeXmlNode(final Node node) throws IOException {
335         if (isArrayElement(node)) {
336             writeArrayContent(node);
337             return;
338         }
339         final Element firstChildElement = getFirstChildElement(node);
340         if (firstChildElement == null) {
341             writeXmlValue(node);
342         } else {
343             writeObjectContent(firstChildElement);
344         }
345     }
346
347     private void writeArrayContent(final Node node) throws IOException {
348         writer.beginArray();
349         handleArray(node);
350         writer.endArray();
351     }
352
353     private void writeObjectContent(final Element firstChildElement) throws IOException {
354         writer.beginObject();
355         writeObject(firstChildElement);
356         writer.endObject();
357     }
358
359     private static boolean isArrayElement(final Node node) {
360         if (ELEMENT_NODE == node.getNodeType()) {
361             final String nodeName = node.getNodeName();
362             for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
363                 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
364                     return true;
365                 }
366             }
367         }
368         return false;
369     }
370
371     private void handleArray(final Node node) throws IOException {
372         final Element parentNode = (Element)node.getParentNode();
373         final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
374         for (int i = 0, length = elementsList.getLength(); i < length; i++) {
375             final Node arrayElement = elementsList.item(i);
376             final Element parent = (Element)arrayElement.getParentNode();
377             if (parentNode.isSameNode(parent)) {
378                 final Element firstChildElement = getFirstChildElement(arrayElement);
379                 if (firstChildElement != null) {
380                     writeObjectContent(firstChildElement);
381                 } else {
382                     // It may be scalar
383                     writeXmlValue(arrayElement);
384                 }
385             }
386         }
387     }
388
389     private void writeObject(Node node) throws IOException {
390         String previousNodeName = "";
391         while (node != null) {
392             if (ELEMENT_NODE == node.getNodeType()) {
393                 if (!node.getNodeName().equals(previousNodeName)) {
394                     previousNodeName = node.getNodeName();
395                     writer.name(node.getNodeName());
396                     writeXmlNode(node);
397                 }
398             }
399             node = node.getNextSibling();
400         }
401     }
402
403     private void writeXmlValue(final Node node) throws IOException {
404         Text firstChild = getFirstChildText(node);
405         String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
406         childNodeText = childNodeText != null ? childNodeText.trim() : "";
407
408         if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
409             writer.value(parseNumber(childNodeText));
410             return;
411         }
412         switch (childNodeText) {
413             case "null":
414                 writer.nullValue();
415                 break;
416             case "false":
417                 writer.value(false);
418                 break;
419             case "true":
420                 writer.value(true);
421                 break;
422             default:
423                 writer.value(childNodeText);
424         }
425     }
426
427     private static Element getFirstChildElement(final Node node) {
428         final NodeList children = node.getChildNodes();
429         for (int i = 0, length = children.getLength(); i < length; i++) {
430             final Node childNode = children.item(i);
431             if (ELEMENT_NODE == childNode.getNodeType()) {
432                 return (Element) childNode;
433             }
434         }
435         return null;
436     }
437
438     private static Text getFirstChildText(final Node node) {
439         final NodeList children = node.getChildNodes();
440         for (int i = 0, length = children.getLength(); i < length; i++) {
441             final Node childNode = children.item(i);
442             if (TEXT_NODE == childNode.getNodeType()) {
443                 return (Text) childNode;
444             }
445         }
446         return null;
447     }
448
449     // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
450     private static Number parseNumber(final String numberText) {
451         if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
452             return Long.valueOf(numberText);
453         }
454
455         return Double.valueOf(numberText);
456     }
457 }