Added tests for yang.model.util
[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
14 import java.io.IOException;
15 import java.io.Writer;
16 import java.net.URI;
17 import java.util.ArrayDeque;
18 import java.util.Deque;
19
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
23 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
24 import org.opendaylight.yangtools.yang.model.api.Module;
25 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
26
27 /**
28  * This implementation will create JSON output as output stream.
29  *
30  * Values of leaf and leaf-list are NOT translated according to codecs.
31  *
32  * FIXME: rewrite this in terms of {@link JsonWriter}.
33  */
34 public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
35
36     private static enum NodeType {
37         OBJECT,
38         LIST,
39         OTHER,
40     }
41
42     private static class TypeInfo {
43         private boolean hasAtLeastOneChild = false;
44         private final NodeType type;
45         private final URI uri;
46
47         public TypeInfo(final NodeType type, final URI uri) {
48             this.type = type;
49             this.uri = uri;
50         }
51
52         public void setHasAtLeastOneChild(final boolean hasChildren) {
53             this.hasAtLeastOneChild = hasChildren;
54         }
55
56         public NodeType getType() {
57             return type;
58         }
59
60         public URI getNamespace() {
61             return uri;
62         }
63
64         public boolean hasAtLeastOneChild() {
65             return hasAtLeastOneChild;
66         }
67     }
68
69     private final Deque<TypeInfo> stack = new ArrayDeque<>();
70     private final SchemaContext schemaContext;
71     private final Writer writer;
72     private final String indent;
73
74     private URI currentNamespace = null;
75     private int currentDepth = 0;
76
77     private JSONNormalizedNodeStreamWriter(final SchemaContext schemaContext,
78             final Writer writer, final int indentSize) {
79         this.schemaContext = Preconditions.checkNotNull(schemaContext);
80         this.writer = Preconditions.checkNotNull(writer);
81
82         Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
83
84         if (indentSize != 0) {
85             indent = Strings.repeat(" ", indentSize);
86         } else {
87             indent = null;
88         }
89     }
90
91     /**
92      * Create a new stream writer, which writes to the specified {@link Writer}.
93      *
94      * @param schemaContext Schema context
95      * @param writer Output writer
96      * @return A stream writer instance
97      */
98     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
99         return new JSONNormalizedNodeStreamWriter(schemaContext, writer, 0);
100     }
101
102     /**
103      * Create a new stream writer, which writes to the specified output stream.
104      *
105      * @param schemaContext Schema context
106      * @param writer Output writer
107      * @param indentSize indentation size
108      * @return A stream writer instance
109      */
110     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
111         return new JSONNormalizedNodeStreamWriter(schemaContext, writer, indentSize);
112     }
113
114     @Override
115     public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
116         separateElementFromPreviousElement();
117         writeJsonIdentifier(name);
118         currentNamespace = stack.peek().getNamespace();
119         writeValue(value.toString());
120         separateNextSiblingsWithComma();
121     }
122
123     @Override
124     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
125         separateElementFromPreviousElement();
126         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
127         writeJsonIdentifier(name);
128         writeStartList();
129         indentRight();
130     }
131
132     @Override
133     public void leafSetEntryNode(final Object value) throws IOException {
134         separateElementFromPreviousElement();
135         writeValue(value.toString());
136         separateNextSiblingsWithComma();
137     }
138
139     @Override
140     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
141         separateElementFromPreviousElement();
142         stack.push(new TypeInfo(NodeType.OBJECT, name.getNodeType().getNamespace()));
143         writeJsonIdentifier(name);
144         writeStartObject();
145         indentRight();
146     }
147
148     @Override
149     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
150         separateElementFromPreviousElement();
151         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
152         writeJsonIdentifier(name);
153         writeStartList();
154         indentRight();
155     }
156
157     @Override
158     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
159         stack.push(new TypeInfo(NodeType.OBJECT, name.getNodeType().getNamespace()));
160         separateElementFromPreviousElement();
161         writeStartObject();
162         indentRight();
163     }
164
165     @Override
166     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
167         separateElementFromPreviousElement();
168         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
169         writeJsonIdentifier(name);
170         writeStartList();
171         indentRight();
172     }
173
174     @Override
175     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
176             throws IOException {
177         stack.push(new TypeInfo(NodeType.OBJECT, identifier.getNodeType().getNamespace()));
178         separateElementFromPreviousElement();
179         writeStartObject();
180         indentRight();
181     }
182
183     @Override
184     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
185         stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
186         separateElementFromPreviousElement();
187         writeJsonIdentifier(name);
188         writeStartList();
189         indentRight();
190     }
191
192     @Override
193     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
194         handleInvisibleNode(name.getNodeType().getNamespace());
195     }
196
197     @Override
198     public void startAugmentationNode(final AugmentationIdentifier identifier) throws IllegalArgumentException {
199         handleInvisibleNode(currentNamespace);
200     }
201
202     @Override
203     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
204         separateElementFromPreviousElement();
205         writeJsonIdentifier(name);
206         currentNamespace = stack.peek().getNamespace();
207         writeValue(value.toString());
208         separateNextSiblingsWithComma();
209     }
210
211     @Override
212     public void endNode() throws IOException {
213         switch (stack.peek().getType()) {
214         case LIST:
215             indentLeft();
216             newLine();
217             writer.append(']');
218             break;
219         case OBJECT:
220             indentLeft();
221             newLine();
222             writer.append('}');
223             break;
224         default:
225             break;
226         }
227         stack.pop();
228         currentNamespace = stack.isEmpty() ? null : stack.peek().getNamespace();
229         separateNextSiblingsWithComma();
230     }
231
232     private void separateElementFromPreviousElement() throws IOException {
233         if (!stack.isEmpty() && stack.peek().hasAtLeastOneChild()) {
234             writer.append(',');
235         }
236         newLine();
237     }
238
239     private void newLine() throws IOException {
240         if (indent != null) {
241             writer.append('\n');
242
243             for (int i = 0; i < currentDepth; i++) {
244                 writer.append(indent);
245             }
246         }
247     }
248
249     private void separateNextSiblingsWithComma() {
250         if (!stack.isEmpty()) {
251             stack.peek().setHasAtLeastOneChild(true);
252         }
253     }
254
255     /**
256      * Invisible nodes have to be also pushed to stack because of pairing of start*() and endNode() methods. Information
257      * about child existing (due to printing comma) has to be transfered to invisible node.
258      */
259     private void handleInvisibleNode(final URI uri) {
260         TypeInfo typeInfo = new TypeInfo(NodeType.OTHER, uri);
261         typeInfo.setHasAtLeastOneChild(stack.peek().hasAtLeastOneChild());
262         stack.push(typeInfo);
263     }
264
265     private void writeStartObject() throws IOException {
266         writer.append('{');
267     }
268
269     private void writeStartList() throws IOException {
270         writer.append('[');
271     }
272
273     private void writeModulName(final URI namespace) throws IOException {
274         if (this.currentNamespace == null || namespace != this.currentNamespace) {
275             Module module = schemaContext.findModuleByNamespaceAndRevision(namespace, null);
276             writer.append(module.getName());
277             writer.append(':');
278             currentNamespace = namespace;
279         }
280     }
281
282     private void writeValue(final String value) throws IOException {
283         writer.append('"');
284         writer.append(value);
285         writer.append('"');
286     }
287
288     private void writeJsonIdentifier(final NodeIdentifier name) throws IOException {
289         writer.append('"');
290         writeModulName(name.getNodeType().getNamespace());
291         writer.append(name.getNodeType().getLocalName());
292         writer.append("\":");
293     }
294
295     private void indentRight() {
296         currentDepth++;
297     }
298
299     private void indentLeft() {
300         currentDepth--;
301     }
302
303     @Override
304     public void flush() throws IOException {
305         writer.flush();
306     }
307
308     @Override
309     public void close() throws IOException {
310         writer.flush();
311         writer.close();
312     }
313
314 }