Merge "Fixed SchemaTracker behaviour in choice nodes."
[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.Preconditions;
11 import com.google.common.base.Strings;
12 import com.google.gson.stream.JsonWriter;
13 import java.io.IOException;
14 import java.io.Writer;
15 import java.net.URI;
16 import java.util.ArrayDeque;
17 import java.util.Deque;
18 import org.opendaylight.yangtools.concepts.Codec;
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.LeafListSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.Module;
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     private static enum NodeType {
41         OBJECT,
42         LIST,
43         OTHER,
44     }
45
46     private static class TypeInfo {
47         private boolean hasAtLeastOneChild = false;
48         private final NodeType type;
49         private final URI uri;
50
51         public TypeInfo(final NodeType type, final URI uri) {
52             this.type = type;
53             this.uri = uri;
54         }
55
56         public void setHasAtLeastOneChild(final boolean hasChildren) {
57             this.hasAtLeastOneChild = hasChildren;
58         }
59
60         public NodeType getType() {
61             return type;
62         }
63
64         public URI getNamespace() {
65             return uri;
66         }
67
68         public boolean hasAtLeastOneChild() {
69             return hasAtLeastOneChild;
70         }
71     }
72
73     private final Deque<TypeInfo> stack = new ArrayDeque<>();
74     private final SchemaContext schemaContext;
75     private final CodecFactory codecs;
76     private final SchemaTracker tracker;
77     private final Writer writer;
78     private final String indent;
79
80     private URI currentNamespace = null;
81     private int currentDepth = 0;
82
83     private JSONNormalizedNodeStreamWriter(final SchemaContext schemaContext,
84             final Writer writer, final int indentSize) {
85         this.schemaContext = Preconditions.checkNotNull(schemaContext);
86         this.writer = Preconditions.checkNotNull(writer);
87
88         Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
89         if (indentSize != 0) {
90             indent = Strings.repeat(" ", indentSize);
91         } else {
92             indent = null;
93         }
94
95         this.codecs = CodecFactory.create(schemaContext);
96         this.tracker = SchemaTracker.create(schemaContext);
97     }
98
99     private JSONNormalizedNodeStreamWriter(final SchemaContext schemaContext, final SchemaPath path,
100             final Writer writer, final int indentSize) {
101         this.schemaContext = Preconditions.checkNotNull(schemaContext);
102         this.writer = Preconditions.checkNotNull(writer);
103
104         Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
105         if (indentSize != 0) {
106             indent = Strings.repeat(" ", indentSize);
107         } else {
108             indent = null;
109         }
110
111         this.utils = SchemaContextUtils.create(schemaContext);
112         this.codecs = RestCodecFactory.create(utils);
113         this.tracker = SchemaTracker.create(schemaContext,path);
114     }
115
116     /**
117      * Create a new stream writer, which writes to the specified {@link Writer}.
118      *
119      * @param schemaContext Schema context
120      * @param writer Output writer
121      * @return A stream writer instance
122      */
123     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
124         return new JSONNormalizedNodeStreamWriter(schemaContext, writer, 0);
125     }
126
127     /**
128      * Create a new stream writer, which writes to the specified {@link Writer}.
129      *
130      * @param schemaContext Schema context
131      * @param writer Output writer
132      * @return A stream writer instance
133      */
134     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, SchemaPath path,final Writer writer) {
135         return new JSONNormalizedNodeStreamWriter(schemaContext, path, writer, 0);
136     }
137
138     /**
139      * Create a new stream writer, which writes to the specified output stream.
140      *
141      * @param schemaContext Schema context
142      * @param writer Output writer
143      * @param indentSize indentation size
144      * @return A stream writer instance
145      */
146     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
147         return new JSONNormalizedNodeStreamWriter(schemaContext, writer, indentSize);
148     }
149
150     @Override
151     public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
152         final LeafSchemaNode schema = tracker.leafNode(name);
153         final Codec<Object, Object> codec = codecs.codecFor(schema.getType());
154
155         separateElementFromPreviousElement();
156         writeJsonIdentifier(name);
157         currentNamespace = stack.peek().getNamespace();
158         writeValue(String.valueOf(codec.serialize(value)));
159         separateNextSiblingsWithComma();
160     }
161
162     @Override
163     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
164         tracker.startLeafSet(name);
165
166         separateElementFromPreviousElement();
167         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
168         writeJsonIdentifier(name);
169         writeStartList();
170         indentRight();
171     }
172
173     @Override
174     public void leafSetEntryNode(final Object value) throws IOException {
175         final LeafListSchemaNode schema = tracker.leafSetEntryNode();
176         final Codec<Object, Object> codec = codecs.codecFor(schema.getType());
177
178         separateElementFromPreviousElement();
179         writeValue(String.valueOf(codec.serialize(value)));
180         separateNextSiblingsWithComma();
181     }
182
183     @Override
184     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
185         tracker.startContainerNode(name);
186
187         separateElementFromPreviousElement();
188         stack.push(new TypeInfo(NodeType.OBJECT, name.getNodeType().getNamespace()));
189         writeJsonIdentifier(name);
190         writeStartObject();
191         indentRight();
192     }
193
194     @Override
195     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
196         tracker.startList(name);
197
198         separateElementFromPreviousElement();
199         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
200         writeJsonIdentifier(name);
201         writeStartList();
202         indentRight();
203     }
204
205     @Override
206     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
207         tracker.startListItem(name);
208
209         stack.push(new TypeInfo(NodeType.OBJECT, name.getNodeType().getNamespace()));
210         separateElementFromPreviousElement();
211         writeStartObject();
212         indentRight();
213     }
214
215     @Override
216     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
217         tracker.startList(name);
218
219         separateElementFromPreviousElement();
220         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
221         writeJsonIdentifier(name);
222         writeStartList();
223         indentRight();
224     }
225
226     @Override
227     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
228             throws IOException {
229         tracker.startListItem(identifier);
230
231         stack.push(new TypeInfo(NodeType.OBJECT, identifier.getNodeType().getNamespace()));
232         separateElementFromPreviousElement();
233         writeStartObject();
234         indentRight();
235     }
236
237     @Override
238     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
239         tracker.startListItem(name);
240
241         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
242         separateElementFromPreviousElement();
243         writeJsonIdentifier(name);
244         writeStartList();
245         indentRight();
246     }
247
248     @Override
249     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
250         tracker.startChoiceNode(name);
251         handleInvisibleNode(name.getNodeType().getNamespace());
252     }
253
254     @Override
255     public void startAugmentationNode(final AugmentationIdentifier identifier) throws IllegalArgumentException {
256         tracker.startAugmentationNode(identifier);
257         handleInvisibleNode(currentNamespace);
258     }
259
260     @Override
261     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
262         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
263         // FIXME: should have a codec based on this :)
264
265         separateElementFromPreviousElement();
266         writeJsonIdentifier(name);
267         currentNamespace = stack.peek().getNamespace();
268         writeValue(value.toString());
269         separateNextSiblingsWithComma();
270     }
271
272     @Override
273     public void endNode() throws IOException {
274         tracker.endNode();
275
276         final TypeInfo t = stack.pop();
277         switch (t.getType()) {
278         case LIST:
279             indentLeft();
280             newLine();
281             writer.append(']');
282             break;
283         case OBJECT:
284             indentLeft();
285             newLine();
286             writer.append('}');
287             break;
288         default:
289             break;
290         }
291
292         currentNamespace = stack.isEmpty() ? null : stack.peek().getNamespace();
293         separateNextSiblingsWithComma();
294     }
295
296     private void separateElementFromPreviousElement() throws IOException {
297         if (!stack.isEmpty() && stack.peek().hasAtLeastOneChild()) {
298             writer.append(',');
299         }
300         newLine();
301     }
302
303     private void newLine() throws IOException {
304         if (indent != null) {
305             writer.append('\n');
306
307             for (int i = 0; i < currentDepth; i++) {
308                 writer.append(indent);
309             }
310         }
311     }
312
313     private void separateNextSiblingsWithComma() {
314         if (!stack.isEmpty()) {
315             stack.peek().setHasAtLeastOneChild(true);
316         }
317     }
318
319     /**
320      * Invisible nodes have to be also pushed to stack because of pairing of start*() and endNode() methods. Information
321      * about child existing (due to printing comma) has to be transfered to invisible node.
322      */
323     private void handleInvisibleNode(final URI uri) {
324         TypeInfo typeInfo = new TypeInfo(NodeType.OTHER, uri);
325         typeInfo.setHasAtLeastOneChild(stack.peek().hasAtLeastOneChild());
326         stack.push(typeInfo);
327     }
328
329     private void writeStartObject() throws IOException {
330         writer.append('{');
331     }
332
333     private void writeStartList() throws IOException {
334         writer.append('[');
335     }
336
337     private void writeModulName(final URI namespace) throws IOException {
338         if (this.currentNamespace == null || namespace != this.currentNamespace) {
339             Module module = schemaContext.findModuleByNamespaceAndRevision(namespace, null);
340             writer.append(module.getName());
341             writer.append(':');
342             currentNamespace = namespace;
343         }
344     }
345
346     private void writeValue(final String value) throws IOException {
347         writer.append('"');
348         writer.append(value);
349         writer.append('"');
350     }
351
352     private void writeJsonIdentifier(final NodeIdentifier name) throws IOException {
353         writer.append('"');
354         writeModulName(name.getNodeType().getNamespace());
355         writer.append(name.getNodeType().getLocalName());
356         writer.append("\":");
357     }
358
359     private void indentRight() {
360         currentDepth++;
361     }
362
363     private void indentLeft() {
364         currentDepth--;
365     }
366
367     @Override
368     public void flush() throws IOException {
369         writer.flush();
370     }
371
372     @Override
373     public void close() throws IOException {
374         writer.flush();
375         writer.close();
376     }
377
378 }