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