Fixed compilation breakage in JSONNormalizedNodeStreamWriter caused by merge job.
[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.codecs = CodecFactory.create(schemaContext);
112         this.tracker = SchemaTracker.create(schemaContext,path);
113     }
114
115     /**
116      * Create a new stream writer, which writes to the specified {@link Writer}.
117      *
118      * @param schemaContext Schema context
119      * @param writer Output writer
120      * @return A stream writer instance
121      */
122     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
123         return new JSONNormalizedNodeStreamWriter(schemaContext, writer, 0);
124     }
125
126     /**
127      * Create a new stream writer, which writes to the specified {@link Writer}.
128      *
129      * @param schemaContext Schema context
130      * @param writer Output writer
131      * @return A stream writer instance
132      */
133     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, SchemaPath path,final Writer writer) {
134         return new JSONNormalizedNodeStreamWriter(schemaContext, path, writer, 0);
135     }
136
137     /**
138      * Create a new stream writer, which writes to the specified output stream.
139      *
140      * @param schemaContext Schema context
141      * @param writer Output writer
142      * @param indentSize indentation size
143      * @return A stream writer instance
144      */
145     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
146         return new JSONNormalizedNodeStreamWriter(schemaContext, writer, indentSize);
147     }
148
149     @Override
150     public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
151         final LeafSchemaNode schema = tracker.leafNode(name);
152         final Codec<Object, Object> codec = codecs.codecFor(schema.getType());
153
154         separateElementFromPreviousElement();
155         writeJsonIdentifier(name);
156         currentNamespace = stack.peek().getNamespace();
157         writeValue(String.valueOf(codec.serialize(value)));
158         separateNextSiblingsWithComma();
159     }
160
161     @Override
162     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
163         tracker.startLeafSet(name);
164
165         separateElementFromPreviousElement();
166         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
167         writeJsonIdentifier(name);
168         writeStartList();
169         indentRight();
170     }
171
172     @Override
173     public void leafSetEntryNode(final Object value) throws IOException {
174         final LeafListSchemaNode schema = tracker.leafSetEntryNode();
175         final Codec<Object, Object> codec = codecs.codecFor(schema.getType());
176
177         separateElementFromPreviousElement();
178         writeValue(String.valueOf(codec.serialize(value)));
179         separateNextSiblingsWithComma();
180     }
181
182     @Override
183     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
184         tracker.startContainerNode(name);
185
186         separateElementFromPreviousElement();
187         stack.push(new TypeInfo(NodeType.OBJECT, name.getNodeType().getNamespace()));
188         writeJsonIdentifier(name);
189         writeStartObject();
190         indentRight();
191     }
192
193     @Override
194     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
195         tracker.startList(name);
196
197         separateElementFromPreviousElement();
198         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
199         writeJsonIdentifier(name);
200         writeStartList();
201         indentRight();
202     }
203
204     @Override
205     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
206         tracker.startListItem(name);
207
208         stack.push(new TypeInfo(NodeType.OBJECT, name.getNodeType().getNamespace()));
209         separateElementFromPreviousElement();
210         writeStartObject();
211         indentRight();
212     }
213
214     @Override
215     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
216         tracker.startList(name);
217
218         separateElementFromPreviousElement();
219         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
220         writeJsonIdentifier(name);
221         writeStartList();
222         indentRight();
223     }
224
225     @Override
226     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
227             throws IOException {
228         tracker.startListItem(identifier);
229
230         stack.push(new TypeInfo(NodeType.OBJECT, identifier.getNodeType().getNamespace()));
231         separateElementFromPreviousElement();
232         writeStartObject();
233         indentRight();
234     }
235
236     @Override
237     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
238         tracker.startListItem(name);
239
240         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
241         separateElementFromPreviousElement();
242         writeJsonIdentifier(name);
243         writeStartList();
244         indentRight();
245     }
246
247     @Override
248     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
249         tracker.startChoiceNode(name);
250         handleInvisibleNode(name.getNodeType().getNamespace());
251     }
252
253     @Override
254     public void startAugmentationNode(final AugmentationIdentifier identifier) throws IllegalArgumentException {
255         tracker.startAugmentationNode(identifier);
256         handleInvisibleNode(currentNamespace);
257     }
258
259     @Override
260     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
261         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
262         // FIXME: should have a codec based on this :)
263
264         separateElementFromPreviousElement();
265         writeJsonIdentifier(name);
266         currentNamespace = stack.peek().getNamespace();
267         writeValue(value.toString());
268         separateNextSiblingsWithComma();
269     }
270
271     @Override
272     public void endNode() throws IOException {
273         tracker.endNode();
274
275         final TypeInfo t = stack.pop();
276         switch (t.getType()) {
277         case LIST:
278             indentLeft();
279             newLine();
280             writer.append(']');
281             break;
282         case OBJECT:
283             indentLeft();
284             newLine();
285             writer.append('}');
286             break;
287         default:
288             break;
289         }
290
291         currentNamespace = stack.isEmpty() ? null : stack.peek().getNamespace();
292         separateNextSiblingsWithComma();
293     }
294
295     private void separateElementFromPreviousElement() throws IOException {
296         if (!stack.isEmpty() && stack.peek().hasAtLeastOneChild()) {
297             writer.append(',');
298         }
299         newLine();
300     }
301
302     private void newLine() throws IOException {
303         if (indent != null) {
304             writer.append('\n');
305
306             for (int i = 0; i < currentDepth; i++) {
307                 writer.append(indent);
308             }
309         }
310     }
311
312     private void separateNextSiblingsWithComma() {
313         if (!stack.isEmpty()) {
314             stack.peek().setHasAtLeastOneChild(true);
315         }
316     }
317
318     /**
319      * Invisible nodes have to be also pushed to stack because of pairing of start*() and endNode() methods. Information
320      * about child existing (due to printing comma) has to be transfered to invisible node.
321      */
322     private void handleInvisibleNode(final URI uri) {
323         TypeInfo typeInfo = new TypeInfo(NodeType.OTHER, uri);
324         typeInfo.setHasAtLeastOneChild(stack.peek().hasAtLeastOneChild());
325         stack.push(typeInfo);
326     }
327
328     private void writeStartObject() throws IOException {
329         writer.append('{');
330     }
331
332     private void writeStartList() throws IOException {
333         writer.append('[');
334     }
335
336     private void writeModulName(final URI namespace) throws IOException {
337         if (this.currentNamespace == null || namespace != this.currentNamespace) {
338             Module module = schemaContext.findModuleByNamespaceAndRevision(namespace, null);
339             writer.append(module.getName());
340             writer.append(':');
341             currentNamespace = namespace;
342         }
343     }
344
345     private void writeValue(final String value) throws IOException {
346         writer.append('"');
347         writer.append(value);
348         writer.append('"');
349     }
350
351     private void writeJsonIdentifier(final NodeIdentifier name) throws IOException {
352         writer.append('"');
353         writeModulName(name.getNodeType().getNamespace());
354         writer.append(name.getNodeType().getLocalName());
355         writer.append("\":");
356     }
357
358     private void indentRight() {
359         currentDepth++;
360     }
361
362     private void indentLeft() {
363         currentDepth--;
364     }
365
366     @Override
367     public void flush() throws IOException {
368         writer.flush();
369     }
370
371     @Override
372     public void close() throws IOException {
373         writer.flush();
374         writer.close();
375     }
376
377 }