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