Mass-migrate to use EffectiveModelContext
[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.net.URI;
20 import java.util.regex.Pattern;
21 import javax.xml.transform.dom.DOMSource;
22 import org.checkerframework.checker.regex.qual.Regex;
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.StreamWriterMountPointExtension;
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.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 URI 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
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 DataNodeContainer rootNode, final URI 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 can be used emit multiple top level element,
171      * but does not start / close parent JSON object, which must be done
172      * by user providing {@code jsonWriter} instance in order for
173      * JSON to be valid. Closing this instance <strong>will not</strong>
174      * close the wrapped writer; the caller must take care of that.
175      *
176      * @param codecFactory JSON codec factory
177      * @param path Schema Path
178      * @param initialNs Initial namespace
179      * @param jsonWriter JsonWriter
180      * @return A stream writer instance
181      */
182     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
183             final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
184         return new Nested(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path), jsonWriter,
185             new JSONStreamWriterSharedRootContext(initialNs));
186     }
187
188     /**
189      * Create a new stream writer, which writes to the specified output stream.
190      *
191      * <p>
192      * The codec factory can be reused between multiple writers.
193      *
194      * <p>
195      * Returned writer can be used emit multiple top level element,
196      * but does not start / close parent JSON object, which must be done
197      * by user providing {@code jsonWriter} instance in order for
198      * JSON to be valid. Closing this instance <strong>will not</strong>
199      * close the wrapped writer; the caller must take care of that.
200      *
201      * @param codecFactory JSON codec factory
202      * @param rootNode Root node
203      * @param initialNs Initial namespace
204      * @param jsonWriter JsonWriter
205      * @return A stream writer instance
206      */
207     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
208             final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
209         return new Nested(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
210             new JSONStreamWriterSharedRootContext(initialNs));
211     }
212
213     @Override
214     public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
215         return ImmutableClassToInstanceMap.of(StreamWriterMountPointExtension.class, this);
216     }
217
218     @Override
219     public void startLeafNode(final NodeIdentifier name) throws IOException {
220         tracker.startLeafNode(name);
221         context.emittingChild(codecs.getEffectiveModelContext(), writer);
222         context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
223     }
224
225     @Override
226     public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
227         tracker.startLeafSet(name);
228         context = new JSONStreamWriterListContext(context, name);
229     }
230
231     @Override
232     public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
233         tracker.startLeafSetEntryNode(name);
234         context.emittingChild(codecs.getEffectiveModelContext(), writer);
235     }
236
237     @Override
238     public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
239         tracker.startLeafSet(name);
240         context = new JSONStreamWriterListContext(context, name);
241     }
242
243     /*
244      * Warning suppressed due to static final constant which triggers a warning
245      * for the call to schema.isPresenceContainer().
246      */
247     @Override
248     public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
249         final SchemaNode schema = tracker.startContainerNode(name);
250         final boolean isPresence = schema instanceof ContainerSchemaNode
251             ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
252         context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
253     }
254
255     @Override
256     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
257         tracker.startList(name);
258         context = new JSONStreamWriterListContext(context, name);
259     }
260
261     @Override
262     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
263         tracker.startListItem(name);
264         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
265     }
266
267     @Override
268     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
269         tracker.startList(name);
270         context = new JSONStreamWriterListContext(context, name);
271     }
272
273     @Override
274     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
275             throws IOException {
276         tracker.startListItem(identifier);
277         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
278     }
279
280     @Override
281     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
282         tracker.startList(name);
283         context = new JSONStreamWriterListContext(context, name);
284     }
285
286     @Override
287     public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
288         tracker.startChoiceNode(name);
289         context = new JSONStreamWriterInvisibleContext(context);
290     }
291
292     @Override
293     public final void startAugmentationNode(final AugmentationIdentifier identifier) {
294         tracker.startAugmentationNode(identifier);
295         context = new JSONStreamWriterInvisibleContext(context);
296     }
297
298     @Override
299     public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
300         if (NormalizedAnydata.class.isAssignableFrom(objectModel)) {
301             tracker.startAnydataNode(name);
302             context.emittingChild(codecs.getEffectiveModelContext(), writer);
303             context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
304             return true;
305         }
306
307         return false;
308     }
309
310     @Override
311     public final NormalizedNodeStreamWriter startMountPoint(final MountPointIdentifier mountId,
312             final MountPointContext mountCtx) throws IOException {
313         final EffectiveModelContext ctx = mountCtx.getEffectiveModelContext();
314         return new Nested(codecs.rebaseTo(ctx), SchemaTracker.create(ctx), writer,
315             new JSONStreamWriterSharedRootContext(context.getNamespace()));
316     }
317
318     @Override
319     public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
320         if (DOMSource.class.isAssignableFrom(objectModel)) {
321             tracker.startAnyxmlNode(name);
322             context.emittingChild(codecs.getEffectiveModelContext(), writer);
323             context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
324             return true;
325         }
326         return false;
327     }
328
329     @Override
330     public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
331             throws IOException {
332         tracker.startYangModeledAnyXmlNode(name);
333         context = new JSONStreamWriterNamedObjectContext(context, name, true);
334     }
335
336     @Override
337     public final void endNode() throws IOException {
338         tracker.endNode();
339         context = context.endNode(codecs.getEffectiveModelContext(), writer);
340     }
341
342     @Override
343     public final void flush() throws IOException {
344         writer.flush();
345     }
346
347     final void closeWriter() throws IOException {
348         if (!(context instanceof JSONStreamWriterRootContext)) {
349             throw new IOException("Unexpected root context " + context);
350         }
351
352         context.endNode(codecs.getEffectiveModelContext(), writer);
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(
391             codecs.rebaseTo(anydata.getEffectiveModelContext()),
392             new SingleChildDataNodeContainer(anydata.getContextNode()), context.getNamespace(), writer));
393     }
394
395     private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
396         writeXmlNode(anyXmlValue.getNode());
397     }
398
399     private void writeXmlNode(final Node node) throws IOException {
400         if (isArrayElement(node)) {
401             writeArrayContent(node);
402             return;
403         }
404         final Element firstChildElement = getFirstChildElement(node);
405         if (firstChildElement == null) {
406             writeXmlValue(node);
407         } else {
408             writeObjectContent(firstChildElement);
409         }
410     }
411
412     private void writeArrayContent(final Node node) throws IOException {
413         writer.beginArray();
414         handleArray(node);
415         writer.endArray();
416     }
417
418     private void writeObjectContent(final Element firstChildElement) throws IOException {
419         writer.beginObject();
420         writeObject(firstChildElement);
421         writer.endObject();
422     }
423
424     private static boolean isArrayElement(final Node node) {
425         if (ELEMENT_NODE == node.getNodeType()) {
426             final String nodeName = node.getNodeName();
427             for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
428                 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
429                     return true;
430                 }
431             }
432         }
433         return false;
434     }
435
436     private void handleArray(final Node node) throws IOException {
437         final Element parentNode = (Element)node.getParentNode();
438         final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
439         for (int i = 0, length = elementsList.getLength(); i < length; i++) {
440             final Node arrayElement = elementsList.item(i);
441             final Element parent = (Element)arrayElement.getParentNode();
442             if (parentNode.isSameNode(parent)) {
443                 final Element firstChildElement = getFirstChildElement(arrayElement);
444                 if (firstChildElement != null) {
445                     writeObjectContent(firstChildElement);
446                 } else {
447                     // It may be scalar
448                     writeXmlValue(arrayElement);
449                 }
450             }
451         }
452     }
453
454     private void writeObject(Node node) throws IOException {
455         String previousNodeName = "";
456         while (node != null) {
457             if (ELEMENT_NODE == node.getNodeType()) {
458                 if (!node.getNodeName().equals(previousNodeName)) {
459                     previousNodeName = node.getNodeName();
460                     writer.name(node.getNodeName());
461                     writeXmlNode(node);
462                 }
463             }
464             node = node.getNextSibling();
465         }
466     }
467
468     private void writeXmlValue(final Node node) throws IOException {
469         Text firstChild = getFirstChildText(node);
470         String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
471         childNodeText = childNodeText != null ? childNodeText.trim() : "";
472
473         if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
474             writer.value(parseNumber(childNodeText));
475             return;
476         }
477         switch (childNodeText) {
478             case "null":
479                 writer.nullValue();
480                 break;
481             case "false":
482                 writer.value(false);
483                 break;
484             case "true":
485                 writer.value(true);
486                 break;
487             default:
488                 writer.value(childNodeText);
489         }
490     }
491
492     private static Element getFirstChildElement(final Node node) {
493         final NodeList children = node.getChildNodes();
494         for (int i = 0, length = children.getLength(); i < length; i++) {
495             final Node childNode = children.item(i);
496             if (ELEMENT_NODE == childNode.getNodeType()) {
497                 return (Element) childNode;
498             }
499         }
500         return null;
501     }
502
503     private static Text getFirstChildText(final Node node) {
504         final NodeList children = node.getChildNodes();
505         for (int i = 0, length = children.getLength(); i < length; i++) {
506             final Node childNode = children.item(i);
507             if (TEXT_NODE == childNode.getNodeType()) {
508                 return (Text) childNode;
509             }
510         }
511         return null;
512     }
513
514     // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
515     private static Number parseNumber(final String numberText) {
516         if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
517             return Long.valueOf(numberText);
518         }
519
520         return Double.valueOf(numberText);
521     }
522 }