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