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