Allow startAnyxmlNode() to handle differing object models
[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.SchemaContext;
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.getSchemaContext(), path), jsonWriter,
133             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.getSchemaContext(), 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.getSchemaContext(), writer);
222         context.writeChildJsonIdentifier(codecs.getSchemaContext(), 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.getSchemaContext(), 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.getSchemaContext(), writer);
303             context.writeChildJsonIdentifier(codecs.getSchemaContext(), 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 SchemaContext ctx = mountCtx.getSchemaContext();
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.getSchemaContext(), writer);
323             context.writeChildJsonIdentifier(codecs.getSchemaContext(), 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.getSchemaContext(), writer);
340
341         if (context instanceof JSONStreamWriterRootContext) {
342             context.endNode(codecs.getSchemaContext(), writer);
343         }
344     }
345
346     @Override
347     public final void flush() throws IOException {
348         writer.flush();
349     }
350
351     final void closeWriter() throws IOException {
352         writer.close();
353     }
354
355     @Override
356     public void scalarValue(final Object value) throws IOException {
357         final Object current = tracker.getParent();
358         if (current instanceof TypedDataSchemaNode) {
359             writeValue(value, codecs.codecFor((TypedDataSchemaNode) current));
360         } else if (current instanceof AnydataSchemaNode) {
361             writeAnydataValue(value);
362         } else {
363             throw new IllegalStateException(String.format("Cannot emit scalar %s for %s", value, current));
364         }
365     }
366
367     @Override
368     public void domSourceValue(final DOMSource value) throws IOException {
369         final Object current = tracker.getParent();
370         checkState(current instanceof AnyxmlSchemaNode, "Cannot emit DOMSource %s for %s", value, current);
371         // FIXME: should have a codec based on this :)
372         writeAnyXmlValue(value);
373     }
374
375     @SuppressWarnings("unchecked")
376     private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
377         ((JSONCodec<Object>) codec).writeValue(writer, value);
378     }
379
380     private void writeAnydataValue(final Object value) throws IOException {
381         if (value instanceof NormalizedAnydata) {
382             writeNormalizedAnydata((NormalizedAnydata) value);
383         } else {
384             throw new IllegalStateException("Unexpected anydata value " + value);
385         }
386     }
387
388     private void writeNormalizedAnydata(final NormalizedAnydata anydata) throws IOException {
389         anydata.writeTo(JSONNormalizedNodeStreamWriter.createNestedWriter(codecs.rebaseTo(anydata.getSchemaContext()),
390             new SingleChildDataNodeContainer(anydata.getContextNode()), context.getNamespace(), writer));
391     }
392
393     private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
394         writeXmlNode(anyXmlValue.getNode());
395     }
396
397     private void writeXmlNode(final Node node) throws IOException {
398         if (isArrayElement(node)) {
399             writeArrayContent(node);
400             return;
401         }
402         final Element firstChildElement = getFirstChildElement(node);
403         if (firstChildElement == null) {
404             writeXmlValue(node);
405         } else {
406             writeObjectContent(firstChildElement);
407         }
408     }
409
410     private void writeArrayContent(final Node node) throws IOException {
411         writer.beginArray();
412         handleArray(node);
413         writer.endArray();
414     }
415
416     private void writeObjectContent(final Element firstChildElement) throws IOException {
417         writer.beginObject();
418         writeObject(firstChildElement);
419         writer.endObject();
420     }
421
422     private static boolean isArrayElement(final Node node) {
423         if (ELEMENT_NODE == node.getNodeType()) {
424             final String nodeName = node.getNodeName();
425             for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
426                 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
427                     return true;
428                 }
429             }
430         }
431         return false;
432     }
433
434     private void handleArray(final Node node) throws IOException {
435         final Element parentNode = (Element)node.getParentNode();
436         final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
437         for (int i = 0, length = elementsList.getLength(); i < length; i++) {
438             final Node arrayElement = elementsList.item(i);
439             final Element parent = (Element)arrayElement.getParentNode();
440             if (parentNode.isSameNode(parent)) {
441                 final Element firstChildElement = getFirstChildElement(arrayElement);
442                 if (firstChildElement != null) {
443                     writeObjectContent(firstChildElement);
444                 } else {
445                     // It may be scalar
446                     writeXmlValue(arrayElement);
447                 }
448             }
449         }
450     }
451
452     private void writeObject(Node node) throws IOException {
453         String previousNodeName = "";
454         while (node != null) {
455             if (ELEMENT_NODE == node.getNodeType()) {
456                 if (!node.getNodeName().equals(previousNodeName)) {
457                     previousNodeName = node.getNodeName();
458                     writer.name(node.getNodeName());
459                     writeXmlNode(node);
460                 }
461             }
462             node = node.getNextSibling();
463         }
464     }
465
466     private void writeXmlValue(final Node node) throws IOException {
467         Text firstChild = getFirstChildText(node);
468         String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
469         childNodeText = childNodeText != null ? childNodeText.trim() : "";
470
471         if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
472             writer.value(parseNumber(childNodeText));
473             return;
474         }
475         switch (childNodeText) {
476             case "null":
477                 writer.nullValue();
478                 break;
479             case "false":
480                 writer.value(false);
481                 break;
482             case "true":
483                 writer.value(true);
484                 break;
485             default:
486                 writer.value(childNodeText);
487         }
488     }
489
490     private static Element getFirstChildElement(final Node node) {
491         final NodeList children = node.getChildNodes();
492         for (int i = 0, length = children.getLength(); i < length; i++) {
493             final Node childNode = children.item(i);
494             if (ELEMENT_NODE == childNode.getNodeType()) {
495                 return (Element) childNode;
496             }
497         }
498         return null;
499     }
500
501     private static Text getFirstChildText(final Node node) {
502         final NodeList children = node.getChildNodes();
503         for (int i = 0, length = children.getLength(); i < length; i++) {
504             final Node childNode = children.item(i);
505             if (TEXT_NODE == childNode.getNodeType()) {
506                 return (Text) childNode;
507             }
508         }
509         return null;
510     }
511
512     // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
513     private static Number parseNumber(final String numberText) {
514         if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
515             return Long.valueOf(numberText);
516         }
517
518         return Double.valueOf(numberText);
519     }
520 }