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