Make JSON serializer always serialize empty containers
[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.CharMatcher;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Strings;
13 import com.google.gson.stream.JsonWriter;
14 import java.io.IOException;
15 import java.io.Writer;
16 import java.net.URI;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
20 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
21 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
22 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
26 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
28
29 /**
30  * This implementation will create JSON output as output stream.
31  *
32  * Values of leaf and leaf-list are NOT translated according to codecs.
33  *
34  * FIXME: rewrite this in terms of {@link JsonWriter}.
35  */
36 public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
37     /**
38      * RFC6020 deviation: we are not required to emit empty containers unless they
39      * are marked as 'presence'.
40      */
41     private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
42
43     /**
44      * Matcher used to check if a string needs to be escaped.
45      */
46     private static final CharMatcher JSON_ILLEGAL_STRING_CHARACTERS = CharMatcher.anyOf("\\\"\n\r");
47
48     private final SchemaTracker tracker;
49     private final JSONCodecFactory codecs;
50     private final Writer writer;
51     private final String indent;
52     private JSONStreamWriterContext context;
53
54     private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path,
55             final Writer writer, final URI initialNs, final int indentSize) {
56         this.writer = Preconditions.checkNotNull(writer);
57
58         Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
59         if (indentSize != 0) {
60             indent = Strings.repeat(" ", indentSize);
61         } else {
62             indent = null;
63         }
64         this.codecs = Preconditions.checkNotNull(codecFactory);
65         this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
66         this.context = new JSONStreamWriterRootContext(initialNs);
67     }
68
69     /**
70      * Create a new stream writer, which writes to the specified {@link Writer}.
71      *
72      * @param schemaContext Schema context
73      * @param writer Output writer
74      * @return A stream writer instance
75      */
76     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
77         return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, 0);
78     }
79
80     /**
81      * Create a new stream writer, which writes to the specified {@link Writer}.
82      *
83      * @param schemaContext Schema context
84      * @param path Root schemapath
85      * @param writer Output writer
86      * @return A stream writer instance
87      */
88     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path, final Writer writer) {
89         return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, null, 0);
90     }
91
92     /**
93      * Create a new stream writer, which writes to the specified {@link Writer}.
94      *
95      * @param schemaContext Schema context
96      * @param path Root schemapath
97      * @param writer Output writer
98      * @param initialNs Initial namespace
99      * @return A stream writer instance
100      */
101     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path,
102             final URI initialNs, final Writer writer) {
103         return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, initialNs, 0);
104     }
105
106     /**
107      * Create a new stream writer, which writes to the specified output stream.
108      *
109      * @param schemaContext Schema context
110      * @param writer Output writer
111      * @param indentSize indentation size
112      * @return A stream writer instance
113      */
114     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
115         return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, indentSize);
116     }
117
118     /**
119      * Create a new stream writer, which writes to the specified output stream. The codec factory
120      * can be reused between multiple writers.
121      *
122      * @param codecFactory JSON codec factory
123      * @param writer Output writer
124      * @param indentSize indentation size
125      * @return A stream writer instance
126      */
127     public static NormalizedNodeStreamWriter create(final JSONCodecFactory codecFactory, final Writer writer, final int indentSize) {
128         return new JSONNormalizedNodeStreamWriter(codecFactory, SchemaPath.ROOT, writer, null, indentSize);
129     }
130
131     @Override
132     public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
133         final LeafSchemaNode schema = tracker.leafNode(name);
134         final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
135
136         context.emittingChild(codecs.getSchemaContext(), writer, indent);
137         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
138         writeValue(codec.serialize(value), codec.needQuotes());
139     }
140
141     @Override
142     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
143         tracker.startLeafSet(name);
144         context = new JSONStreamWriterListContext(context, name);
145     }
146
147     @Override
148     public void leafSetEntryNode(final Object value) throws IOException {
149         final LeafListSchemaNode schema = tracker.leafSetEntryNode();
150         final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
151
152         context.emittingChild(codecs.getSchemaContext(), writer, indent);
153         writeValue(codec.serialize(value), codec.needQuotes());
154     }
155
156     /*
157      * Warning suppressed due to static final constant which triggers a warning
158      * for the call to schema.isPresenceContainer().
159      */
160     @SuppressWarnings("unused")
161     @Override
162     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
163         final SchemaNode schema = tracker.startContainerNode(name);
164
165         // FIXME this code ignores presence for containers
166         // but datastore does as well and it needs be fixed first (2399)
167         context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
168     }
169
170     @Override
171     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
172         tracker.startList(name);
173         context = new JSONStreamWriterListContext(context, name);
174     }
175
176     @Override
177     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
178         tracker.startListItem(name);
179         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
180     }
181
182     @Override
183     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
184         tracker.startList(name);
185         context = new JSONStreamWriterListContext(context, name);
186     }
187
188     @Override
189     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
190             throws IOException {
191         tracker.startListItem(identifier);
192         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
193     }
194
195     @Override
196     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
197         tracker.startList(name);
198         context = new JSONStreamWriterListContext(context, name);
199     }
200
201     @Override
202     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
203         tracker.startChoiceNode(name);
204         context = new JSONStreamWriterInvisibleContext(context);
205     }
206
207     @Override
208     public void startAugmentationNode(final AugmentationIdentifier identifier) {
209         tracker.startAugmentationNode(identifier);
210         context = new JSONStreamWriterInvisibleContext(context);
211     }
212
213     @Override
214     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
215         @SuppressWarnings("unused")
216         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
217         // FIXME: should have a codec based on this :)
218
219         context.emittingChild(codecs.getSchemaContext(), writer, indent);
220         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
221         writeValue(String.valueOf(value), true);
222     }
223
224     @Override
225     public void endNode() throws IOException {
226         tracker.endNode();
227         context = context.endNode(codecs.getSchemaContext(), writer, indent);
228     }
229
230     private void writeValue(final String str, final boolean needQuotes) throws IOException {
231         if (needQuotes) {
232             writer.append('"');
233
234             final int needEscape = JSON_ILLEGAL_STRING_CHARACTERS.countIn(str);
235             if (needEscape != 0) {
236                 final char[] escaped = new char[str.length() + needEscape];
237                 int offset = 0;
238
239                 for (int i = 0; i < str.length(); i++) {
240                     final char c = str.charAt(i);
241                     if (JSON_ILLEGAL_STRING_CHARACTERS.matches(c)) {
242                         escaped[offset++] = '\\';
243                     }
244                     escaped[offset++] = c;
245                 }
246                 writer.write(escaped);
247             } else {
248                 writer.append(str);
249             }
250
251             writer.append('"');
252         } else {
253             writer.append(str);
254         }
255     }
256
257     @Override
258     public void flush() throws IOException {
259         writer.flush();
260     }
261
262     @Override
263     public void close() throws IOException {
264         writer.flush();
265         writer.close();
266     }
267
268 }