BUG-7983: unify JSONCodec and XmlCodec methods
[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 org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream.ANYXML_ARRAY_ELEMENT_ID;
11 import static org.w3c.dom.Node.ELEMENT_NODE;
12 import static org.w3c.dom.Node.TEXT_NODE;
13
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Throwables;
16 import com.google.gson.stream.JsonWriter;
17 import java.io.IOException;
18 import java.net.URI;
19 import java.util.regex.Pattern;
20 import javax.annotation.RegEx;
21 import javax.xml.transform.dom.DOMSource;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
26 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
27 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
28 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
33 import org.w3c.dom.Node;
34 import org.w3c.dom.NodeList;
35
36 /**
37  * This implementation will create JSON output as output stream.
38  *
39  * Values of leaf and leaf-list are NOT translated according to codecs.
40  *
41  */
42 public final class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
43     /**
44      * RFC6020 deviation: we are not required to emit empty containers unless they
45      * are marked as 'presence'.
46      */
47     private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
48
49     @RegEx
50     private static final String NUMBER_STRING = "-?\\d+(\\.\\d+)?";
51     private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_STRING);
52
53     @RegEx
54     private static final String NOT_DECIMAL_NUMBER_STRING = "-?\\d+";
55     private static final Pattern NOT_DECIMAL_NUMBER_PATTERN = Pattern.compile(NOT_DECIMAL_NUMBER_STRING);
56
57     private final SchemaTracker tracker;
58     private final JSONCodecFactory codecs;
59     private final JsonWriter writer;
60     private JSONStreamWriterContext context;
61
62     private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path, final JsonWriter JsonWriter, final JSONStreamWriterRootContext rootContext) {
63         this.writer = Preconditions.checkNotNull(JsonWriter);
64         this.codecs = Preconditions.checkNotNull(codecFactory);
65         this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
66         this.context = Preconditions.checkNotNull(rootContext);
67     }
68
69     /**
70      * Create a new stream writer, which writes to the specified output stream.
71      *
72      * The codec factory can be reused between multiple writers.
73      *
74      * Returned writer is exclusive user of JsonWriter, which means it will start
75      * top-level JSON element and ends it.
76      *
77      * This instance of writer can be used only to emit one top level element,
78      * otherwise it will produce incorrect JSON.
79      *
80      * @param codecFactory JSON codec factory
81      * @param path Schema Path
82      * @param initialNs Initial namespace
83      * @param jsonWriter JsonWriter
84      * @return A stream writer instance
85      */
86     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory, final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
87         return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
88     }
89
90     /**
91      * Create a new stream writer, which writes to the specified output stream.
92      *
93      * The codec factory can be reused between multiple writers.
94      *
95      * Returned writer can be used emit multiple top level element,
96      * but does not start / close parent JSON object, which must be done
97      * by user providing {@code jsonWriter} instance in order for
98      * JSON to be valid.
99      *
100      * @param codecFactory JSON codec factory
101      * @param path Schema Path
102      * @param initialNs Initial namespace
103      * @param jsonWriter JsonWriter
104      * @return A stream writer instance
105      */
106     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory, final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
107         return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
108     }
109
110     @Override
111     public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
112         final LeafSchemaNode schema = tracker.leafNode(name);
113         final JSONCodec<?> codec = codecs.codecFor(schema);
114         context.emittingChild(codecs.getSchemaContext(), writer);
115         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
116         writeValue(value, codec);
117     }
118
119     @Override
120     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
121         tracker.startLeafSet(name);
122         context = new JSONStreamWriterListContext(context, name);
123     }
124
125     @Override
126     public void leafSetEntryNode(final QName name, final Object value) throws IOException {
127         final LeafListSchemaNode schema = tracker.leafSetEntryNode(name);
128         final JSONCodec<?> codec = codecs.codecFor(schema);
129         context.emittingChild(codecs.getSchemaContext(), writer);
130         writeValue(value, codec);
131     }
132
133     @Override
134     public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
135         tracker.startLeafSet(name);
136         context = new JSONStreamWriterListContext(context, name);
137     }
138
139     /*
140      * Warning suppressed due to static final constant which triggers a warning
141      * for the call to schema.isPresenceContainer().
142      */
143     @SuppressWarnings("unused")
144     @Override
145     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
146         final SchemaNode schema = tracker.startContainerNode(name);
147
148         // FIXME this code ignores presence for containers
149         // but datastore does as well and it needs be fixed first (2399)
150         context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
151     }
152
153     @Override
154     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
155         tracker.startList(name);
156         context = new JSONStreamWriterListContext(context, name);
157     }
158
159     @Override
160     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
161         tracker.startListItem(name);
162         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
163     }
164
165     @Override
166     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
167         tracker.startList(name);
168         context = new JSONStreamWriterListContext(context, name);
169     }
170
171     @Override
172     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
173             throws IOException {
174         tracker.startListItem(identifier);
175         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
176     }
177
178     @Override
179     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
180         tracker.startList(name);
181         context = new JSONStreamWriterListContext(context, name);
182     }
183
184     @Override
185     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
186         tracker.startChoiceNode(name);
187         context = new JSONStreamWriterInvisibleContext(context);
188     }
189
190     @Override
191     public void startAugmentationNode(final AugmentationIdentifier identifier) {
192         tracker.startAugmentationNode(identifier);
193         context = new JSONStreamWriterInvisibleContext(context);
194     }
195
196     @Override
197     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
198         @SuppressWarnings("unused")
199         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
200         // FIXME: should have a codec based on this :)
201
202         context.emittingChild(codecs.getSchemaContext(), writer);
203         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
204
205         writeAnyXmlValue((DOMSource) value);
206     }
207
208     @Override
209     public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
210         tracker.startYangModeledAnyXmlNode(name);
211         context = new JSONStreamWriterNamedObjectContext(context, name, true);
212     }
213
214     @Override
215     public void endNode() throws IOException {
216         tracker.endNode();
217         context = context.endNode(codecs.getSchemaContext(), writer);
218
219         if (context instanceof JSONStreamWriterRootContext) {
220             context.emitEnd(writer);
221         }
222     }
223
224     @SuppressWarnings("unchecked")
225     private void writeValue(final Object value, final JSONCodec<?> codec)
226             throws IOException {
227         try {
228             ((JSONCodec<Object>) codec).writeValue(writer, value);
229         } catch (IOException e) {
230             throw e;
231         } catch (Exception e) {
232             Throwables.propagateIfPossible(e);
233             throw new RuntimeException(e);
234         }
235     }
236
237     private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
238         final Node documentNode = anyXmlValue.getNode();
239         final Node firstChild = documentNode.getFirstChild();
240         if (ELEMENT_NODE == firstChild.getNodeType() && !ANYXML_ARRAY_ELEMENT_ID.equals(firstChild.getNodeName())) {
241             writer.beginObject();
242             traverseAnyXmlValue(documentNode);
243             writer.endObject();
244         } else {
245             traverseAnyXmlValue(documentNode);
246         }
247     }
248
249     private void traverseAnyXmlValue(final Node node) throws IOException {
250         final NodeList children = node.getChildNodes();
251         boolean inArray = false;
252
253         for (int i = 0, length = children.getLength(); i < length; i++) {
254             final Node childNode = children.item(i);
255             boolean inObject = false;
256
257             if (ELEMENT_NODE == childNode.getNodeType()) {
258                 final Node firstChild = childNode.getFirstChild();
259                 // beginning of an array
260                 if (ANYXML_ARRAY_ELEMENT_ID.equals(childNode.getNodeName()) && !inArray) {
261                     writer.beginArray();
262                     inArray = true;
263                     // object at the beginning of the array
264                     if (isJsonObjectInArray(childNode, firstChild)) {
265                         writer.beginObject();
266                         inObject = true;
267                     }
268                     // object in the array
269                 } else if (isJsonObjectInArray(childNode, firstChild)) {
270                     writer.beginObject();
271                     inObject = true;
272                     // object
273                 } else if (isJsonObject(firstChild)) {
274                     writer.name(childNode.getNodeName());
275                     writer.beginObject();
276                     inObject = true;
277                     // name
278                 } else if (!inArray){
279                     writer.name(childNode.getNodeName());
280                 }
281             }
282
283             // text value, i.e. a number, string, boolean or null
284             if (TEXT_NODE == childNode.getNodeType()) {
285                 final String childNodeText = childNode.getNodeValue();
286                 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
287                     writer.value(parseNumber(childNodeText));
288                 } else if ("true".equals(childNodeText) || "false".equals(childNodeText)) {
289                     writer.value(Boolean.parseBoolean(childNodeText));
290                 } else if ("null".equals(childNodeText)) {
291                     writer.nullValue();
292                 } else {
293                     writer.value(childNodeText);
294                 }
295
296                 return;
297             }
298
299             traverseAnyXmlValue(childNode);
300
301             if (inObject) {
302                 writer.endObject();
303             }
304         }
305
306         if (inArray) {
307             writer.endArray();
308         }
309     }
310
311     // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
312     private static Number parseNumber(final String numberText) {
313         if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
314             return Long.valueOf(numberText);
315         }
316
317         return Double.valueOf(numberText);
318     }
319
320     private static boolean isJsonObject(final Node firstChild) {
321         return !ANYXML_ARRAY_ELEMENT_ID.equals(firstChild.getNodeName()) && TEXT_NODE != firstChild.getNodeType();
322     }
323
324     private static boolean isJsonObjectInArray(final Node node, final Node firstChild) {
325         return ANYXML_ARRAY_ELEMENT_ID.equals(node.getNodeName())
326                 && !ANYXML_ARRAY_ELEMENT_ID.equals(firstChild.getNodeName())
327                 && TEXT_NODE != firstChild.getNodeType();
328     }
329
330     @Override
331     public void flush() throws IOException {
332         writer.flush();
333     }
334
335     @Override
336     public void close() throws IOException {
337         flush();
338         writer.close();
339     }
340 }