Add notification support to SchemaTracker
[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.ContainerSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
27 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
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 codecFactory 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 SchemaNode schema = tracker.startContainerNode(name);
165
166         final boolean isPresence = schema instanceof ContainerSchemaNode ?
167                 ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
168
169         context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
170     }
171
172     @Override
173     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
174         tracker.startList(name);
175         context = new JSONStreamWriterListContext(context, name);
176     }
177
178     @Override
179     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
180         tracker.startListItem(name);
181         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
182     }
183
184     @Override
185     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
186         tracker.startList(name);
187         context = new JSONStreamWriterListContext(context, name);
188     }
189
190     @Override
191     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
192             throws IOException {
193         tracker.startListItem(identifier);
194         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
195     }
196
197     @Override
198     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
199         tracker.startList(name);
200         context = new JSONStreamWriterListContext(context, name);
201     }
202
203     @Override
204     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
205         tracker.startChoiceNode(name);
206         context = new JSONStreamWriterInvisibleContext(context);
207     }
208
209     @Override
210     public void startAugmentationNode(final AugmentationIdentifier identifier) {
211         tracker.startAugmentationNode(identifier);
212         context = new JSONStreamWriterInvisibleContext(context);
213     }
214
215     @Override
216     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
217         @SuppressWarnings("unused")
218         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
219         // FIXME: should have a codec based on this :)
220
221         context.emittingChild(codecs.getSchemaContext(), writer, indent);
222         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
223         writeValue(String.valueOf(value), true);
224     }
225
226     @Override
227     public void endNode() throws IOException {
228         tracker.endNode();
229         context = context.endNode(codecs.getSchemaContext(), writer, indent);
230     }
231
232     private void writeValue(final String str, final boolean needQuotes) throws IOException {
233         if (needQuotes) {
234             writer.append('"');
235
236             final int needEscape = JSON_ILLEGAL_STRING_CHARACTERS.countIn(str);
237             if (needEscape != 0) {
238                 final char[] escaped = new char[str.length() + needEscape];
239                 int offset = 0;
240
241                 for (int i = 0; i < str.length(); i++) {
242                     final char c = str.charAt(i);
243                     if (JSON_ILLEGAL_STRING_CHARACTERS.matches(c)) {
244                         escaped[offset++] = '\\';
245                     }
246                     escaped[offset++] = c;
247                 }
248                 writer.write(escaped);
249             } else {
250                 writer.append(str);
251             }
252
253             writer.append('"');
254         } else {
255             writer.append(str);
256         }
257     }
258
259     @Override
260     public void flush() throws IOException {
261         writer.flush();
262     }
263
264     @Override
265     public void close() throws IOException {
266         writer.flush();
267         writer.close();
268     }
269
270 }