Merge "Bug 2864: Fixed (de)serialization of leafrefs"
[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 com.google.common.base.Preconditions;
11 import com.google.gson.stream.JsonWriter;
12 import java.io.IOException;
13 import java.io.Writer;
14 import java.net.URI;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
18 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
19 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
20 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
21 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
22 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
24 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
26
27 /**
28  * This implementation will create JSON output as output stream.
29  *
30  * Values of leaf and leaf-list are NOT translated according to codecs.
31  *
32  */
33 public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
34     /**
35      * RFC6020 deviation: we are not required to emit empty containers unless they
36      * are marked as 'presence'.
37      */
38     private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
39
40     private final SchemaTracker tracker;
41     private final JSONCodecFactory codecs;
42     private final JsonWriter writer;
43     private JSONStreamWriterContext context;
44
45     private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path, JsonWriter JsonWriter, JSONStreamWriterRootContext rootContext) {
46         this.writer = Preconditions.checkNotNull(JsonWriter);
47         this.codecs = Preconditions.checkNotNull(codecFactory);
48         this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
49         this.context = Preconditions.checkNotNull(rootContext);
50     }
51
52     /**
53      * Create a new stream writer, which writes to the specified {@link Writer}.
54      *
55      * This instance of writer can be used only to emit one top level element,
56      * therwise it will produce incorrect JSON.
57      *
58      * @param schemaContext Schema context
59      * @param writer Output writer
60      * @return A stream writer instance
61      */
62     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
63         return create(schemaContext, SchemaPath.ROOT, null, writer);
64     }
65
66     /**
67      * Create a new stream writer, which writes to the specified {@link Writer}.
68      *
69      * This instance of writer can be used only to emit one top level element,
70      * therwise it will produce incorrect JSON.
71      *
72      * @param schemaContext Schema context
73      * @param path Root schemapath
74      * @param writer Output writer
75      * @return A stream writer instance
76      */
77     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path, final Writer writer) {
78         return create(schemaContext, path, null, writer);
79     }
80
81     /**
82      * Create a new stream writer, which writes to the specified {@link Writer}.
83      *
84      * This instance of writer can be used only to emit one top level element,
85      * therwise it will produce incorrect JSON.
86      *
87      * @param schemaContext Schema context
88      * @param path Root schemapath
89      * @param writer Output writer
90      * @param initialNs Initial namespace
91      * @return A stream writer instance
92      */
93     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path,
94             final URI initialNs, final Writer writer) {
95         return createExclusiveWriter(JSONCodecFactory.create(schemaContext), path, initialNs, JsonWriterFactory.createJsonWriter(writer));
96     }
97
98     /**
99      * Create a new stream writer, which writes to the specified output stream.
100      *
101      * This instance of writer can be used only to emit one top level element,
102      * therwise it will produce incorrect JSON.
103      *
104      * @param schemaContext Schema context
105      * @param writer Output writer
106      * @param indentSize indentation size
107      * @return A stream writer instance
108      */
109     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
110         return createExclusiveWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, null,JsonWriterFactory.createJsonWriter(writer, indentSize));
111     }
112
113     /**
114      * Create a new stream writer, which writes to the specified output stream. The codec factory
115      * can be reused between multiple writers.
116      *
117      * This instance of writer can be used only to emit one top level element,
118      * therwise it will produce incorrect JSON.
119      *
120      * @param codecFactory JSON codec factory
121      * @param writer Output writer
122      * @param indentSize indentation size
123      * @return A stream writer instance
124      */
125     public static NormalizedNodeStreamWriter create(final JSONCodecFactory codecFactory, final Writer writer, final int indentSize) {
126         return createExclusiveWriter(codecFactory, SchemaPath.ROOT, null, JsonWriterFactory.createJsonWriter(writer,indentSize));
127     }
128
129     /**
130      * Create a new stream writer, which writes to the specified output stream.
131      *
132      * This instance of writer can be used only to emit one top level element,
133      * therwise it will produce incorrect JSON.
134      *
135      * @param schemaContext Schema context
136      * @param path Schema Path
137      * @param initialNs Initial namespace
138      * @param jsonWriter JsonWriter
139      * @return A stream writer instance
140      */
141     public static NormalizedNodeStreamWriter create(SchemaContext schemaContext, SchemaPath path, URI initialNs,
142             JsonWriter jsonWriter) {
143         return createExclusiveWriter(JSONCodecFactory.create(schemaContext), path, initialNs, jsonWriter);
144     }
145
146     /**
147      * Create a new stream writer, which writes to the specified output stream.
148      *
149      * The codec factory can be reused between multiple writers.
150      *
151      * Returned writer is exclusive user of JsonWriter, which means it will start
152      * top-level JSON element and ends it.
153      *
154      * This instance of writer can be used only to emit one top level element,
155      * therwise it will produce incorrect JSON.
156      *
157      * @param codecFactory JSON codec factory
158      * @param path Schema Path
159      * @param initialNs Initial namespace
160      * @param jsonWriter JsonWriter
161      * @return A stream writer instance
162      */
163     public static NormalizedNodeStreamWriter createExclusiveWriter(JSONCodecFactory codecFactory, SchemaPath path, URI initialNs, JsonWriter jsonWriter) {
164         return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
165     }
166
167     /**
168      * Create a new stream writer, which writes to the specified output stream.
169      *
170      * The codec factory can be reused between multiple writers.
171      *
172      * Returned writer can be used emit multiple top level element,
173      * but does not start / close parent JSON object, which must be done
174      * by user providing {@code jsonWriter} instance in order for
175      * JSON to be valid.
176      *
177      * @param codecFactory JSON codec factory
178      * @param path Schema Path
179      * @param initialNs Initial namespace
180      * @param jsonWriter JsonWriter
181      * @return A stream writer instance
182      */
183     public static NormalizedNodeStreamWriter createNestedWriter(JSONCodecFactory codecFactory, SchemaPath path, URI initialNs, JsonWriter jsonWriter) {
184         return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
185     }
186
187     @Override
188     public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
189         final LeafSchemaNode schema = tracker.leafNode(name);
190         final JSONCodec<Object> codec = codecs.codecFor(schema);
191         context.emittingChild(codecs.getSchemaContext(), writer);
192         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
193         writeValue(value, codec);
194     }
195
196     @Override
197     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
198         tracker.startLeafSet(name);
199         context = new JSONStreamWriterListContext(context, name);
200     }
201
202     @Override
203     public void leafSetEntryNode(final Object value) throws IOException {
204         final LeafListSchemaNode schema = tracker.leafSetEntryNode();
205         final JSONCodec<Object> codec = codecs.codecFor(schema);
206         context.emittingChild(codecs.getSchemaContext(), writer);
207         writeValue(value, codec);
208     }
209
210     /*
211      * Warning suppressed due to static final constant which triggers a warning
212      * for the call to schema.isPresenceContainer().
213      */
214     @SuppressWarnings("unused")
215     @Override
216     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
217         final SchemaNode schema = tracker.startContainerNode(name);
218
219         // FIXME this code ignores presence for containers
220         // but datastore does as well and it needs be fixed first (2399)
221         context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
222     }
223
224     @Override
225     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
226         tracker.startList(name);
227         context = new JSONStreamWriterListContext(context, name);
228     }
229
230     @Override
231     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
232         tracker.startListItem(name);
233         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
234     }
235
236     @Override
237     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
238         tracker.startList(name);
239         context = new JSONStreamWriterListContext(context, name);
240     }
241
242     @Override
243     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
244             throws IOException {
245         tracker.startListItem(identifier);
246         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
247     }
248
249     @Override
250     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
251         tracker.startList(name);
252         context = new JSONStreamWriterListContext(context, name);
253     }
254
255     @Override
256     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
257         tracker.startChoiceNode(name);
258         context = new JSONStreamWriterInvisibleContext(context);
259     }
260
261     @Override
262     public void startAugmentationNode(final AugmentationIdentifier identifier) {
263         tracker.startAugmentationNode(identifier);
264         context = new JSONStreamWriterInvisibleContext(context);
265     }
266
267     @Override
268     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
269         @SuppressWarnings("unused")
270         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
271         // FIXME: should have a codec based on this :)
272
273         context.emittingChild(codecs.getSchemaContext(), writer);
274         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
275         // FIXME this kind of serialization is incorrect since the value for AnyXml is now a DOMSource
276         writer.value(String.valueOf(value));
277     }
278
279     @Override
280     public void endNode() throws IOException {
281         tracker.endNode();
282         context = context.endNode(codecs.getSchemaContext(), writer);
283
284         if(context instanceof JSONStreamWriterRootContext) {
285             context.emitEnd(writer);
286         }
287     }
288
289     private void writeValue(Object value, JSONCodec<Object> codec)
290             throws IOException {
291         codec.serializeToWriter(writer,value);
292     }
293
294     @Override
295     public void flush() throws IOException {
296         writer.flush();
297     }
298
299     @Override
300     public void close() throws IOException {
301         writer.flush();
302         writer.close();
303     }
304
305
306
307 }