e1b3f1833ec033eb4a827e27bc190c02358c5c93
[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 com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.collect.ClassToInstanceMap;
14 import com.google.common.collect.ImmutableClassToInstanceMap;
15 import com.google.gson.stream.JsonWriter;
16 import java.io.IOException;
17 import java.util.NoSuchElementException;
18 import java.util.regex.Pattern;
19 import javax.xml.transform.dom.DOMSource;
20 import org.checkerframework.checker.regex.qual.Regex;
21 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
22 import org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier;
23 import org.opendaylight.yangtools.rfc8528.data.api.StreamWriterMountPointExtension;
24 import org.opendaylight.yangtools.yang.common.XMLNamespace;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedAnydata;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriterExtension;
32 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
33 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
37 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
38 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
40 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
42 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
43 import org.w3c.dom.Element;
44 import org.w3c.dom.Node;
45 import org.w3c.dom.NodeList;
46 import org.w3c.dom.Text;
47
48 /**
49  * This implementation will create JSON output as output stream.
50  *
51  * <p>
52  * Values of leaf and leaf-list are NOT translated according to codecs.
53  */
54 public abstract class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter,
55         StreamWriterMountPointExtension {
56     private static final class Exclusive extends JSONNormalizedNodeStreamWriter {
57         Exclusive(final JSONCodecFactory codecFactory, final SchemaTracker tracker, final JsonWriter writer,
58                 final JSONStreamWriterRootContext rootContext) {
59             super(codecFactory, tracker, writer, rootContext);
60         }
61
62         @Override
63         public void close() throws IOException {
64             flush();
65             closeWriter();
66         }
67     }
68
69     private static final class Nested extends JSONNormalizedNodeStreamWriter {
70         Nested(final JSONCodecFactory codecFactory, final SchemaTracker tracker, final JsonWriter writer,
71                 final JSONStreamWriterRootContext rootContext) {
72             super(codecFactory, tracker, writer, rootContext);
73         }
74
75         @Override
76         public void close() throws IOException {
77             flush();
78             // The caller "owns" the writer, let them close it
79         }
80     }
81
82     /**
83      * RFC6020 deviation: we are not required to emit empty containers unless they
84      * are marked as 'presence'.
85      */
86     private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
87
88     @Regex
89     private static final String NUMBER_STRING = "-?\\d+(\\.\\d+)?";
90     private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_STRING);
91
92     @Regex
93     private static final String NOT_DECIMAL_NUMBER_STRING = "-?\\d+";
94     private static final Pattern NOT_DECIMAL_NUMBER_PATTERN = Pattern.compile(NOT_DECIMAL_NUMBER_STRING);
95
96     private final SchemaTracker tracker;
97     private final JSONCodecFactory codecs;
98     private final JsonWriter writer;
99     private JSONStreamWriterContext context;
100
101     JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaTracker tracker,
102             final JsonWriter writer, final JSONStreamWriterRootContext rootContext) {
103         this.writer = requireNonNull(writer);
104         this.codecs = requireNonNull(codecFactory);
105         this.tracker = requireNonNull(tracker);
106         this.context = requireNonNull(rootContext);
107     }
108
109     /**
110      * Create a new stream writer, which writes to the specified output stream.
111      *
112      * <p>
113      * The codec factory can be reused between multiple writers.
114      *
115      * <p>
116      * Returned writer is exclusive user of JsonWriter, which means it will start
117      * top-level JSON element and ends it.
118      *
119      * <p>
120      * This instance of writer can be used only to emit one top level element,
121      * otherwise it will produce incorrect JSON. Closing this instance will close
122      * the writer too.
123      *
124      * @param codecFactory JSON codec factory
125      * @param path Schema Path
126      * @param initialNs Initial namespace
127      * @param jsonWriter JsonWriter
128      * @return A stream writer instance
129      */
130     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
131             final SchemaPath path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
132         return new Exclusive(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path),
133             jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
134     }
135
136     /**
137      * Create a new stream writer, which writes to the specified output stream.
138      *
139      * <p>
140      * The codec factory can be reused between multiple writers.
141      *
142      * <p>
143      * Returned writer is exclusive user of JsonWriter, which means it will start
144      * top-level JSON element and ends it.
145      *
146      * <p>
147      * This instance of writer can be used only to emit one top level element,
148      * otherwise it will produce incorrect JSON. Closing this instance will close
149      * the writer too.
150      *
151      * @param codecFactory JSON codec factory
152      * @param rootNode Root node inference
153      * @param initialNs Initial namespace
154      * @param jsonWriter JsonWriter
155      * @return A stream writer instance
156      */
157     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
158             final EffectiveStatementInference rootNode, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
159         return new Exclusive(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
160             new JSONStreamWriterExclusiveRootContext(initialNs));
161     }
162
163     /**
164      * Create a new stream writer, which writes to the specified output stream.
165      *
166      * <p>
167      * The codec factory can be reused between multiple writers.
168      *
169      * <p>
170      * Returned writer is exclusive user of JsonWriter, which means it will start
171      * top-level JSON element and ends it.
172      *
173      * <p>
174      * This instance of writer can be used only to emit one top level element,
175      * otherwise it will produce incorrect JSON. Closing this instance will close
176      * the writer too.
177      *
178      * @param codecFactory JSON codec factory
179      * @param path Schema Path
180      * @param initialNs Initial namespace
181      * @param jsonWriter JsonWriter
182      * @return A stream writer instance
183      */
184     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
185             final Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
186         return new Exclusive(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path),
187             jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
188     }
189
190     /**
191      * Create a new stream writer, which writes to the specified output stream.
192      *
193      * <p>
194      * The codec factory can be reused between multiple writers.
195      *
196      * <p>
197      * Returned writer can be used emit multiple top level element,
198      * but does not start / close parent JSON object, which must be done
199      * by user providing {@code jsonWriter} instance in order for
200      * JSON to be valid. Closing this instance <strong>will not</strong>
201      * close the wrapped writer; the caller must take care of that.
202      *
203      * @param codecFactory JSON codec factory
204      * @param path Schema Path
205      * @param initialNs Initial namespace
206      * @param jsonWriter JsonWriter
207      * @return A stream writer instance
208      */
209     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
210             final SchemaPath path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
211         return new Nested(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path), jsonWriter,
212             new JSONStreamWriterSharedRootContext(initialNs));
213     }
214
215     /**
216      * Create a new stream writer, which writes to the specified output stream.
217      *
218      * <p>
219      * The codec factory can be reused between multiple writers.
220      *
221      * <p>
222      * Returned writer can be used emit multiple top level element,
223      * but does not start / close parent JSON object, which must be done
224      * by user providing {@code jsonWriter} instance in order for
225      * JSON to be valid. Closing this instance <strong>will not</strong>
226      * close the wrapped writer; the caller must take care of that.
227      *
228      * @param codecFactory JSON codec factory
229      * @param path Schema Path
230      * @param initialNs Initial namespace
231      * @param jsonWriter JsonWriter
232      * @return A stream writer instance
233      */
234     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
235             final Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
236         return new Nested(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path), jsonWriter,
237             new JSONStreamWriterSharedRootContext(initialNs));
238     }
239
240     /**
241      * Create a new stream writer, which writes to the specified output stream.
242      *
243      * <p>
244      * The codec factory can be reused between multiple writers.
245      *
246      * <p>
247      * Returned writer can be used emit multiple top level element,
248      * but does not start / close parent JSON object, which must be done
249      * by user providing {@code jsonWriter} instance in order for
250      * JSON to be valid. Closing this instance <strong>will not</strong>
251      * close the wrapped writer; the caller must take care of that.
252      *
253      * @param codecFactory JSON codec factory
254      * @param rootNode Root node inference
255      * @param initialNs Initial namespace
256      * @param jsonWriter JsonWriter
257      * @return A stream writer instance
258      */
259     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
260             final EffectiveStatementInference rootNode, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
261         return new Nested(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
262             new JSONStreamWriterSharedRootContext(initialNs));
263     }
264
265     @Override
266     public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
267         return ImmutableClassToInstanceMap.of(StreamWriterMountPointExtension.class, this);
268     }
269
270     @Override
271     public void startLeafNode(final NodeIdentifier name) throws IOException {
272         tracker.startLeafNode(name);
273         context.emittingChild(codecs.getEffectiveModelContext(), writer);
274         context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
275     }
276
277     @Override
278     public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
279         tracker.startLeafSet(name);
280         context = new JSONStreamWriterListContext(context, name);
281     }
282
283     @Override
284     public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
285         tracker.startLeafSetEntryNode(name);
286         context.emittingChild(codecs.getEffectiveModelContext(), writer);
287     }
288
289     @Override
290     public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
291         tracker.startLeafSet(name);
292         context = new JSONStreamWriterListContext(context, name);
293     }
294
295     /*
296      * Warning suppressed due to static final constant which triggers a warning
297      * for the call to schema.isPresenceContainer().
298      */
299     @Override
300     public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
301         final SchemaNode schema = tracker.startContainerNode(name);
302         final boolean isPresence = schema instanceof ContainerSchemaNode
303             ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
304         context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
305     }
306
307     @Override
308     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
309         tracker.startList(name);
310         context = new JSONStreamWriterListContext(context, name);
311     }
312
313     @Override
314     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
315         tracker.startListItem(name);
316         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
317     }
318
319     @Override
320     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
321         tracker.startList(name);
322         context = new JSONStreamWriterListContext(context, name);
323     }
324
325     @Override
326     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
327             throws IOException {
328         tracker.startListItem(identifier);
329         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
330     }
331
332     @Override
333     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
334         tracker.startList(name);
335         context = new JSONStreamWriterListContext(context, name);
336     }
337
338     @Override
339     public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
340         tracker.startChoiceNode(name);
341         context = new JSONStreamWriterInvisibleContext(context);
342     }
343
344     @Override
345     public final void startAugmentationNode(final AugmentationIdentifier identifier) {
346         tracker.startAugmentationNode(identifier);
347         context = new JSONStreamWriterInvisibleContext(context);
348     }
349
350     @Override
351     public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
352         if (NormalizedAnydata.class.isAssignableFrom(objectModel)) {
353             tracker.startAnydataNode(name);
354             context.emittingChild(codecs.getEffectiveModelContext(), writer);
355             context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
356             return true;
357         }
358
359         return false;
360     }
361
362     @Override
363     public final NormalizedNodeStreamWriter startMountPoint(final MountPointIdentifier mountId,
364             final MountPointContext mountCtx) throws IOException {
365         final EffectiveModelContext ctx = mountCtx.getEffectiveModelContext();
366         return new Nested(codecs.rebaseTo(ctx), SchemaTracker.create(ctx), writer,
367             new JSONStreamWriterSharedRootContext(context.getNamespace()));
368     }
369
370     @Override
371     public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
372         if (DOMSource.class.isAssignableFrom(objectModel)) {
373             tracker.startAnyxmlNode(name);
374             context.emittingChild(codecs.getEffectiveModelContext(), writer);
375             context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
376             return true;
377         }
378         return false;
379     }
380
381     @Override
382     public final void endNode() throws IOException {
383         tracker.endNode();
384         context = context.endNode(codecs.getEffectiveModelContext(), writer);
385     }
386
387     @Override
388     public final void flush() throws IOException {
389         writer.flush();
390     }
391
392     final void closeWriter() throws IOException {
393         if (!(context instanceof JSONStreamWriterRootContext)) {
394             throw new IOException("Unexpected root context " + context);
395         }
396
397         context.endNode(codecs.getEffectiveModelContext(), writer);
398         writer.close();
399     }
400
401     @Override
402     public void scalarValue(final Object value) throws IOException {
403         final Object current = tracker.getParent();
404         if (current instanceof TypedDataSchemaNode) {
405             writeValue(value, codecs.codecFor((TypedDataSchemaNode) current));
406         } else if (current instanceof AnydataSchemaNode) {
407             writeAnydataValue(value);
408         } else {
409             throw new IllegalStateException(String.format("Cannot emit scalar %s for %s", value, current));
410         }
411     }
412
413     @Override
414     public void domSourceValue(final DOMSource value) throws IOException {
415         final Object current = tracker.getParent();
416         checkState(current instanceof AnyxmlSchemaNode, "Cannot emit DOMSource %s for %s", value, current);
417         // FIXME: should have a codec based on this :)
418         writeAnyXmlValue(value);
419     }
420
421     @SuppressWarnings("unchecked")
422     private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
423         ((JSONCodec<Object>) codec).writeValue(writer, value);
424     }
425
426     private void writeAnydataValue(final Object value) throws IOException {
427         if (value instanceof NormalizedAnydata) {
428             writeNormalizedAnydata((NormalizedAnydata) value);
429         } else {
430             throw new IllegalStateException("Unexpected anydata value " + value);
431         }
432     }
433
434     private void writeNormalizedAnydata(final NormalizedAnydata anydata) throws IOException {
435         // Adjust state to point to parent node and ensure it can handle data tree nodes
436         final SchemaInferenceStack.Inference inference;
437         try {
438             final SchemaInferenceStack stack = SchemaInferenceStack.ofInference(anydata.getInference());
439             stack.exitToDataTree();
440             inference = stack.toInference();
441         } catch (IllegalArgumentException | IllegalStateException | NoSuchElementException e) {
442             throw new IOException("Cannot emit " + anydata, e);
443         }
444
445         anydata.writeTo(JSONNormalizedNodeStreamWriter.createNestedWriter(
446             codecs.rebaseTo(inference.getEffectiveModelContext()), inference, context.getNamespace(), writer));
447     }
448
449     private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
450         writeXmlNode(anyXmlValue.getNode());
451     }
452
453     private void writeXmlNode(final Node node) throws IOException {
454         if (isArrayElement(node)) {
455             writeArrayContent(node);
456             return;
457         }
458         final Element firstChildElement = getFirstChildElement(node);
459         if (firstChildElement == null) {
460             writeXmlValue(node);
461         } else {
462             writeObjectContent(firstChildElement);
463         }
464     }
465
466     private void writeArrayContent(final Node node) throws IOException {
467         writer.beginArray();
468         handleArray(node);
469         writer.endArray();
470     }
471
472     private void writeObjectContent(final Element firstChildElement) throws IOException {
473         writer.beginObject();
474         writeObject(firstChildElement);
475         writer.endObject();
476     }
477
478     private static boolean isArrayElement(final Node node) {
479         if (Node.ELEMENT_NODE == node.getNodeType()) {
480             final String nodeName = node.getNodeName();
481             for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
482                 if (Node.ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
483                     return true;
484                 }
485             }
486         }
487         return false;
488     }
489
490     private void handleArray(final Node node) throws IOException {
491         final Element parentNode = (Element)node.getParentNode();
492         final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
493         for (int i = 0, length = elementsList.getLength(); i < length; i++) {
494             final Node arrayElement = elementsList.item(i);
495             final Element parent = (Element)arrayElement.getParentNode();
496             if (parentNode.isSameNode(parent)) {
497                 final Element firstChildElement = getFirstChildElement(arrayElement);
498                 if (firstChildElement != null) {
499                     writeObjectContent(firstChildElement);
500                 } else {
501                     // It may be scalar
502                     writeXmlValue(arrayElement);
503                 }
504             }
505         }
506     }
507
508     private void writeObject(Node node) throws IOException {
509         String previousNodeName = "";
510         while (node != null) {
511             if (Node.ELEMENT_NODE == node.getNodeType()) {
512                 if (!node.getNodeName().equals(previousNodeName)) {
513                     previousNodeName = node.getNodeName();
514                     writer.name(node.getNodeName());
515                     writeXmlNode(node);
516                 }
517             }
518             node = node.getNextSibling();
519         }
520     }
521
522     private void writeXmlValue(final Node node) throws IOException {
523         Text firstChild = getFirstChildText(node);
524         String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
525         childNodeText = childNodeText != null ? childNodeText.trim() : "";
526
527         if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
528             writer.value(parseNumber(childNodeText));
529             return;
530         }
531         switch (childNodeText) {
532             case "null":
533                 writer.nullValue();
534                 break;
535             case "false":
536                 writer.value(false);
537                 break;
538             case "true":
539                 writer.value(true);
540                 break;
541             default:
542                 writer.value(childNodeText);
543         }
544     }
545
546     private static Element getFirstChildElement(final Node node) {
547         final NodeList children = node.getChildNodes();
548         for (int i = 0, length = children.getLength(); i < length; i++) {
549             final Node childNode = children.item(i);
550             if (Node.ELEMENT_NODE == childNode.getNodeType()) {
551                 return (Element) childNode;
552             }
553         }
554         return null;
555     }
556
557     private static Text getFirstChildText(final Node node) {
558         final NodeList children = node.getChildNodes();
559         for (int i = 0, length = children.getLength(); i < length; i++) {
560             final Node childNode = children.item(i);
561             if (Node.TEXT_NODE == childNode.getNodeType()) {
562                 return (Text) childNode;
563             }
564         }
565         return null;
566     }
567
568     // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
569     private static Number parseNumber(final String numberText) {
570         if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
571             return Long.valueOf(numberText);
572         }
573
574         return Double.valueOf(numberText);
575     }
576 }