Merge "Remove unnecessary casts"
[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.getType());
191
192         context.emittingChild(codecs.getSchemaContext(), writer);
193         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
194
195         writeValue(value, codec);
196     }
197
198     @Override
199     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
200         tracker.startLeafSet(name);
201         context = new JSONStreamWriterListContext(context, name);
202     }
203
204     @Override
205     public void leafSetEntryNode(final Object value) throws IOException {
206         final LeafListSchemaNode schema = tracker.leafSetEntryNode();
207         final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
208
209         context.emittingChild(codecs.getSchemaContext(), writer);
210
211         writeValue(value, codec);
212     }
213
214     /*
215      * Warning suppressed due to static final constant which triggers a warning
216      * for the call to schema.isPresenceContainer().
217      */
218     @SuppressWarnings("unused")
219     @Override
220     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
221         final SchemaNode schema = tracker.startContainerNode(name);
222
223         // FIXME this code ignores presence for containers
224         // but datastore does as well and it needs be fixed first (2399)
225         context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
226     }
227
228     @Override
229     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
230         tracker.startList(name);
231         context = new JSONStreamWriterListContext(context, name);
232     }
233
234     @Override
235     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
236         tracker.startListItem(name);
237         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
238     }
239
240     @Override
241     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
242         tracker.startList(name);
243         context = new JSONStreamWriterListContext(context, name);
244     }
245
246     @Override
247     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
248             throws IOException {
249         tracker.startListItem(identifier);
250         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
251     }
252
253     @Override
254     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
255         tracker.startList(name);
256         context = new JSONStreamWriterListContext(context, name);
257     }
258
259     @Override
260     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
261         tracker.startChoiceNode(name);
262         context = new JSONStreamWriterInvisibleContext(context);
263     }
264
265     @Override
266     public void startAugmentationNode(final AugmentationIdentifier identifier) {
267         tracker.startAugmentationNode(identifier);
268         context = new JSONStreamWriterInvisibleContext(context);
269     }
270
271     @Override
272     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
273         @SuppressWarnings("unused")
274         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
275         // FIXME: should have a codec based on this :)
276
277         context.emittingChild(codecs.getSchemaContext(), writer);
278         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
279         // FIXME this kind of serialization is incorrect since the value for AnyXml is now a DOMSource
280         writer.value(String.valueOf(value));
281     }
282
283     @Override
284     public void endNode() throws IOException {
285         tracker.endNode();
286         context = context.endNode(codecs.getSchemaContext(), writer);
287
288         if(context instanceof JSONStreamWriterRootContext) {
289             context.emitEnd(writer);
290         }
291     }
292
293     private void writeValue(Object value, JSONCodec<Object> codec)
294             throws IOException {
295         codec.serializeToWriter(writer,value);
296     }
297
298     @Override
299     public void flush() throws IOException {
300         writer.flush();
301     }
302
303     @Override
304     public void close() throws IOException {
305         writer.flush();
306         writer.close();
307     }
308
309
310
311 }