Bump odlparent to 5.0.0
[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.xml.transform.dom.DOMSource;
19 import org.checkerframework.checker.regex.qual.Regex;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
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.ContainerSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
31 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
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 void startLeafNode(final NodeIdentifier name) throws IOException {
203         tracker.startLeafNode(name);
204         context.emittingChild(codecs.getSchemaContext(), writer);
205         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
206     }
207
208     @Override
209     public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
210         tracker.startLeafSet(name);
211         context = new JSONStreamWriterListContext(context, name);
212     }
213
214     @Override
215     public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
216         tracker.startLeafSetEntryNode(name);
217         context.emittingChild(codecs.getSchemaContext(), writer);
218     }
219
220     @Override
221     public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
222         tracker.startLeafSet(name);
223         context = new JSONStreamWriterListContext(context, name);
224     }
225
226     /*
227      * Warning suppressed due to static final constant which triggers a warning
228      * for the call to schema.isPresenceContainer().
229      */
230     @Override
231     public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
232         final SchemaNode schema = tracker.startContainerNode(name);
233         final boolean isPresence = schema instanceof ContainerSchemaNode
234             ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
235         context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
236     }
237
238     @Override
239     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
240         tracker.startList(name);
241         context = new JSONStreamWriterListContext(context, name);
242     }
243
244     @Override
245     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
246         tracker.startListItem(name);
247         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
248     }
249
250     @Override
251     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
252         tracker.startList(name);
253         context = new JSONStreamWriterListContext(context, name);
254     }
255
256     @Override
257     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
258             throws IOException {
259         tracker.startListItem(identifier);
260         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
261     }
262
263     @Override
264     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
265         tracker.startList(name);
266         context = new JSONStreamWriterListContext(context, name);
267     }
268
269     @Override
270     public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
271         tracker.startChoiceNode(name);
272         context = new JSONStreamWriterInvisibleContext(context);
273     }
274
275     @Override
276     public final void startAugmentationNode(final AugmentationIdentifier identifier) {
277         tracker.startAugmentationNode(identifier);
278         context = new JSONStreamWriterInvisibleContext(context);
279     }
280
281     @Override
282     public final void startAnyxmlNode(final NodeIdentifier name) throws IOException {
283         tracker.startAnyxmlNode(name);
284         context.emittingChild(codecs.getSchemaContext(), writer);
285         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
286     }
287
288     @Override
289     public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
290             throws IOException {
291         tracker.startYangModeledAnyXmlNode(name);
292         context = new JSONStreamWriterNamedObjectContext(context, name, true);
293     }
294
295     @Override
296     public final void endNode() throws IOException {
297         tracker.endNode();
298         context = context.endNode(codecs.getSchemaContext(), writer);
299
300         if (context instanceof JSONStreamWriterRootContext) {
301             context.emitEnd(writer);
302         }
303     }
304
305     @Override
306     public final void flush() throws IOException {
307         writer.flush();
308     }
309
310     final void closeWriter() throws IOException {
311         writer.close();
312     }
313
314     @Override
315     public void nodeValue(final Object value) throws IOException {
316         final Object current = tracker.getParent();
317         if (current instanceof TypedDataSchemaNode) {
318             final JSONCodec<?> codec = codecs.codecFor((TypedDataSchemaNode) current);
319             writeValue(value, codec);
320         } else if (current instanceof AnyXmlSchemaNode) {
321             // FIXME: should have a codec based on this :)
322             writeAnyXmlValue((DOMSource) value);
323         } else {
324             throw new IllegalStateException("Cannot emit scalar for " + current);
325         }
326     }
327
328     @SuppressWarnings("unchecked")
329     private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
330         ((JSONCodec<Object>) codec).writeValue(writer, value);
331     }
332
333     private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
334         writeXmlNode(anyXmlValue.getNode());
335     }
336
337     private void writeXmlNode(final Node node) throws IOException {
338         if (isArrayElement(node)) {
339             writeArrayContent(node);
340             return;
341         }
342         final Element firstChildElement = getFirstChildElement(node);
343         if (firstChildElement == null) {
344             writeXmlValue(node);
345         } else {
346             writeObjectContent(firstChildElement);
347         }
348     }
349
350     private void writeArrayContent(final Node node) throws IOException {
351         writer.beginArray();
352         handleArray(node);
353         writer.endArray();
354     }
355
356     private void writeObjectContent(final Element firstChildElement) throws IOException {
357         writer.beginObject();
358         writeObject(firstChildElement);
359         writer.endObject();
360     }
361
362     private static boolean isArrayElement(final Node node) {
363         if (ELEMENT_NODE == node.getNodeType()) {
364             final String nodeName = node.getNodeName();
365             for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
366                 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
367                     return true;
368                 }
369             }
370         }
371         return false;
372     }
373
374     private void handleArray(final Node node) throws IOException {
375         final Element parentNode = (Element)node.getParentNode();
376         final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
377         for (int i = 0, length = elementsList.getLength(); i < length; i++) {
378             final Node arrayElement = elementsList.item(i);
379             final Element parent = (Element)arrayElement.getParentNode();
380             if (parentNode.isSameNode(parent)) {
381                 final Element firstChildElement = getFirstChildElement(arrayElement);
382                 if (firstChildElement != null) {
383                     writeObjectContent(firstChildElement);
384                 } else {
385                     // It may be scalar
386                     writeXmlValue(arrayElement);
387                 }
388             }
389         }
390     }
391
392     private void writeObject(Node node) throws IOException {
393         String previousNodeName = "";
394         while (node != null) {
395             if (ELEMENT_NODE == node.getNodeType()) {
396                 if (!node.getNodeName().equals(previousNodeName)) {
397                     previousNodeName = node.getNodeName();
398                     writer.name(node.getNodeName());
399                     writeXmlNode(node);
400                 }
401             }
402             node = node.getNextSibling();
403         }
404     }
405
406     private void writeXmlValue(final Node node) throws IOException {
407         Text firstChild = getFirstChildText(node);
408         String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
409         childNodeText = childNodeText != null ? childNodeText.trim() : "";
410
411         if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
412             writer.value(parseNumber(childNodeText));
413             return;
414         }
415         switch (childNodeText) {
416             case "null":
417                 writer.nullValue();
418                 break;
419             case "false":
420                 writer.value(false);
421                 break;
422             case "true":
423                 writer.value(true);
424                 break;
425             default:
426                 writer.value(childNodeText);
427         }
428     }
429
430     private static Element getFirstChildElement(final Node node) {
431         final NodeList children = node.getChildNodes();
432         for (int i = 0, length = children.getLength(); i < length; i++) {
433             final Node childNode = children.item(i);
434             if (ELEMENT_NODE == childNode.getNodeType()) {
435                 return (Element) childNode;
436             }
437         }
438         return null;
439     }
440
441     private static Text getFirstChildText(final Node node) {
442         final NodeList children = node.getChildNodes();
443         for (int i = 0, length = children.getLength(); i < length; i++) {
444             final Node childNode = children.item(i);
445             if (TEXT_NODE == childNode.getNodeType()) {
446                 return (Text) childNode;
447             }
448         }
449         return null;
450     }
451
452     // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
453     private static Number parseNumber(final String numberText) {
454         if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
455             return Long.valueOf(numberText);
456         }
457
458         return Double.valueOf(numberText);
459     }
460 }