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