23aa8565c4ded44484efc5e03db486ba74cd6ce2
[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.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream.ANYXML_ARRAY_ELEMENT_ID;
12 import static org.w3c.dom.Node.ELEMENT_NODE;
13 import static org.w3c.dom.Node.TEXT_NODE;
14
15 import com.google.gson.stream.JsonWriter;
16 import java.io.IOException;
17 import java.net.URI;
18 import java.util.regex.Pattern;
19 import javax.annotation.RegEx;
20 import javax.xml.transform.dom.DOMSource;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
25 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
26 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
27 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
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 SchemaPath path, final JsonWriter writer,
46                 final JSONStreamWriterRootContext rootContext) {
47             super(codecFactory, path, 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 SchemaPath path, final JsonWriter writer,
59                 final JSONStreamWriterRootContext rootContext) {
60             super(codecFactory, path, 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 SchemaPath path, final JsonWriter writer,
90             final JSONStreamWriterRootContext rootContext) {
91         this.writer = requireNonNull(writer);
92         this.codecs = requireNonNull(codecFactory);
93         this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
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, path, jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
121     }
122
123     /**
124      * Create a new stream writer, which writes to the specified output stream.
125      *
126      * <p>
127      * The codec factory can be reused between multiple writers.
128      *
129      * <p>
130      * Returned writer can be used emit multiple top level element,
131      * but does not start / close parent JSON object, which must be done
132      * by user providing {@code jsonWriter} instance in order for
133      * JSON to be valid. Closing this instance <strong>will not</strong>
134      * close the wrapped writer; the caller must take care of that.
135      *
136      * @param codecFactory JSON codec factory
137      * @param path Schema Path
138      * @param initialNs Initial namespace
139      * @param jsonWriter JsonWriter
140      * @return A stream writer instance
141      */
142     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
143             final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
144         return new Nested(codecFactory, path, jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
145     }
146
147     @Override
148     public final void leafNode(final NodeIdentifier name, final Object value) throws IOException {
149         final LeafSchemaNode schema = tracker.leafNode(name);
150         final JSONCodec<?> codec = codecs.codecFor(schema);
151         context.emittingChild(codecs.getSchemaContext(), writer);
152         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
153         writeValue(value, codec);
154     }
155
156     @Override
157     public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
158         tracker.startLeafSet(name);
159         context = new JSONStreamWriterListContext(context, name);
160     }
161
162     @Override
163     public final void leafSetEntryNode(final QName name, final Object value) throws IOException {
164         final LeafListSchemaNode schema = tracker.leafSetEntryNode(name);
165         final JSONCodec<?> codec = codecs.codecFor(schema);
166         context.emittingChild(codecs.getSchemaContext(), writer);
167         writeValue(value, codec);
168     }
169
170     @Override
171     public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
172         tracker.startLeafSet(name);
173         context = new JSONStreamWriterListContext(context, name);
174     }
175
176     /*
177      * Warning suppressed due to static final constant which triggers a warning
178      * for the call to schema.isPresenceContainer().
179      */
180     @SuppressWarnings("unused")
181     @Override
182     public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
183         final SchemaNode schema = tracker.startContainerNode(name);
184
185         // FIXME this code ignores presence for containers
186         // but datastore does as well and it needs be fixed first (2399)
187         context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
188     }
189
190     @Override
191     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
192         tracker.startList(name);
193         context = new JSONStreamWriterListContext(context, name);
194     }
195
196     @Override
197     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
198         tracker.startListItem(name);
199         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
200     }
201
202     @Override
203     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
204         tracker.startList(name);
205         context = new JSONStreamWriterListContext(context, name);
206     }
207
208     @Override
209     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
210             throws IOException {
211         tracker.startListItem(identifier);
212         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
213     }
214
215     @Override
216     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
217         tracker.startList(name);
218         context = new JSONStreamWriterListContext(context, name);
219     }
220
221     @Override
222     public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
223         tracker.startChoiceNode(name);
224         context = new JSONStreamWriterInvisibleContext(context);
225     }
226
227     @Override
228     public final void startAugmentationNode(final AugmentationIdentifier identifier) {
229         tracker.startAugmentationNode(identifier);
230         context = new JSONStreamWriterInvisibleContext(context);
231     }
232
233     @Override
234     public final void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
235         @SuppressWarnings("unused")
236         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
237         // FIXME: should have a codec based on this :)
238
239         context.emittingChild(codecs.getSchemaContext(), writer);
240         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
241
242         writeAnyXmlValue((DOMSource) value);
243     }
244
245     @Override
246     public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
247             throws IOException {
248         tracker.startYangModeledAnyXmlNode(name);
249         context = new JSONStreamWriterNamedObjectContext(context, name, true);
250     }
251
252     @Override
253     public final void endNode() throws IOException {
254         tracker.endNode();
255         context = context.endNode(codecs.getSchemaContext(), writer);
256
257         if (context instanceof JSONStreamWriterRootContext) {
258             context.emitEnd(writer);
259         }
260     }
261
262     @Override
263     public final void flush() throws IOException {
264         writer.flush();
265     }
266
267     final void closeWriter() throws IOException {
268         writer.close();
269     }
270
271     @SuppressWarnings("unchecked")
272     private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
273         ((JSONCodec<Object>) codec).writeValue(writer, value);
274     }
275
276     private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
277         writeXmlNode(anyXmlValue.getNode());
278     }
279
280     private void writeXmlNode(final Node node) throws IOException {
281         final Element firstChildElement = getFirstChildElement(node);
282         if (firstChildElement == null) {
283             writeXmlValue(node);
284         } else if (ANYXML_ARRAY_ELEMENT_ID.equals(firstChildElement.getNodeName())) {
285             writer.beginArray();
286             writeArray(firstChildElement);
287             writer.endArray();
288         } else {
289             writer.beginObject();
290             writeObject(firstChildElement);
291             writer.endObject();
292         }
293     }
294
295     private void writeArray(Node node) throws IOException {
296         while (node != null) {
297             if (ELEMENT_NODE == node.getNodeType()) {
298                 writeXmlNode(node);
299             }
300             node = node.getNextSibling();
301         }
302     }
303
304     private void writeObject(Node node) throws IOException {
305         while (node != null) {
306             if (ELEMENT_NODE == node.getNodeType()) {
307                 writer.name(node.getNodeName());
308                 writeXmlNode(node);
309             }
310             node = node.getNextSibling();
311         }
312     }
313
314     private void writeXmlValue(final Node node) throws IOException {
315         Text firstChild = getFirstChildText(node);
316         String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
317         childNodeText = childNodeText != null ? childNodeText.trim() : "";
318
319         if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
320             writer.value(parseNumber(childNodeText));
321             return;
322         }
323         switch (childNodeText) {
324             case "null":
325                 writer.nullValue();
326                 break;
327             case "false":
328                 writer.value(false);
329                 break;
330             case "true":
331                 writer.value(true);
332                 break;
333             default:
334                 writer.value(childNodeText);
335         }
336     }
337
338     private static Element getFirstChildElement(final Node node) {
339         final NodeList children = node.getChildNodes();
340         for (int i = 0, length = children.getLength(); i < length; i++) {
341             final Node childNode = children.item(i);
342             if (ELEMENT_NODE == childNode.getNodeType()) {
343                 return (Element) childNode;
344             }
345         }
346         return null;
347     }
348
349     private static Text getFirstChildText(final Node node) {
350         final NodeList children = node.getChildNodes();
351         for (int i = 0, length = children.getLength(); i < length; i++) {
352             final Node childNode = children.item(i);
353             if (TEXT_NODE == childNode.getNodeType()) {
354                 return (Text) childNode;
355             }
356         }
357         return null;
358     }
359
360     // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
361     private static Number parseNumber(final String numberText) {
362         if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
363             return Long.valueOf(numberText);
364         }
365
366         return Double.valueOf(numberText);
367     }
368 }