a0488ee6ae8f75e3d0441e714e9d1d5dfb533d9f
[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
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
21 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
22 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
23 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
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.SchemaContext;
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     private final SchemaContext schemaContext;
45     private final SchemaTracker tracker;
46     private final CodecFactory codecs;
47     private final Writer writer;
48     private final String indent;
49     private JSONStreamWriterContext context;
50
51     private JSONNormalizedNodeStreamWriter(final SchemaContext schemaContext,
52             final Writer writer, final int indentSize) {
53         this(schemaContext, SchemaPath.ROOT, writer, null, indentSize);
54     }
55
56     private JSONNormalizedNodeStreamWriter(final SchemaContext schemaContext, final SchemaPath path,
57             final Writer writer, final URI initialNs, final int indentSize) {
58         this.schemaContext = Preconditions.checkNotNull(schemaContext);
59         this.writer = Preconditions.checkNotNull(writer);
60
61         Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
62         if (indentSize != 0) {
63             indent = Strings.repeat(" ", indentSize);
64         } else {
65             indent = null;
66         }
67         this.codecs = CodecFactory.create(schemaContext);
68         this.tracker = SchemaTracker.create(schemaContext, path);
69         this.context = new JSONStreamWriterRootContext(initialNs);
70     }
71
72     /**
73      * Create a new stream writer, which writes to the specified {@link Writer}.
74      *
75      * @param schemaContext Schema context
76      * @param writer Output writer
77      * @return A stream writer instance
78      */
79     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
80         return new JSONNormalizedNodeStreamWriter(schemaContext, writer, 0);
81     }
82
83     /**
84      * Create a new stream writer, which writes to the specified {@link Writer}.
85      *
86      * @param schemaContext Schema context
87      * @param path Root schemapath
88      * @param writer Output writer
89      * @return A stream writer instance
90      */
91     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path, final Writer writer) {
92         return new JSONNormalizedNodeStreamWriter(schemaContext, path, writer, null, 0);
93     }
94
95     /**
96      * Create a new stream writer, which writes to the specified {@link Writer}.
97      *
98      * @param schemaContext Schema context
99      * @param path Root schemapath
100      * @param writer Output writer
101      * @param initialNs Initial namespace
102      * @return A stream writer instance
103      */
104     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path,
105             final URI initialNs, final Writer writer) {
106         return new JSONNormalizedNodeStreamWriter(schemaContext, path, writer, initialNs, 0);
107     }
108
109     /**
110      * Create a new stream writer, which writes to the specified output stream.
111      *
112      * @param schemaContext Schema context
113      * @param writer Output writer
114      * @param indentSize indentation size
115      * @return A stream writer instance
116      */
117     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
118         return new JSONNormalizedNodeStreamWriter(schemaContext, writer, indentSize);
119     }
120
121     @Override
122     public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
123         final LeafSchemaNode schema = tracker.leafNode(name);
124         final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
125
126         context.emittingChild(schemaContext, writer, indent);
127         context.writeJsonIdentifier(schemaContext, writer, name.getNodeType());
128         writeValue(codec.serialize(value), codec.needQuotes());
129     }
130
131     @Override
132     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
133         tracker.startLeafSet(name);
134         context = new JSONStreamWriterListContext(context, name);
135     }
136
137     @Override
138     public void leafSetEntryNode(final Object value) throws IOException {
139         final LeafListSchemaNode schema = tracker.leafSetEntryNode();
140         final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
141
142         context.emittingChild(schemaContext, writer, indent);
143         writeValue(codec.serialize(value), codec.needQuotes());
144     }
145
146     /*
147      * Warning suppressed due to static final constant which triggers a warning
148      * for the call to schema.isPresenceContainer().
149      */
150     @SuppressWarnings("unused")
151     @Override
152     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
153         final ContainerSchemaNode schema = tracker.startContainerNode(name);
154         context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS || schema.isPresenceContainer());
155     }
156
157     @Override
158     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
159         tracker.startList(name);
160         context = new JSONStreamWriterListContext(context, name);
161     }
162
163     @Override
164     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
165         tracker.startListItem(name);
166         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
167     }
168
169     @Override
170     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
171         tracker.startList(name);
172         context = new JSONStreamWriterListContext(context, name);
173     }
174
175     @Override
176     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
177             throws IOException {
178         tracker.startListItem(identifier);
179         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
180     }
181
182     @Override
183     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
184         tracker.startList(name);
185         context = new JSONStreamWriterListContext(context, name);
186     }
187
188     @Override
189     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
190         tracker.startChoiceNode(name);
191         context = new JSONStreamWriterInvisibleContext(context);
192     }
193
194     @Override
195     public void startAugmentationNode(final AugmentationIdentifier identifier) {
196         tracker.startAugmentationNode(identifier);
197         context = new JSONStreamWriterInvisibleContext(context);
198     }
199
200     @Override
201     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
202         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
203         // FIXME: should have a codec based on this :)
204
205         context.emittingChild(schemaContext, writer, indent);
206         context.writeJsonIdentifier(schemaContext, writer, name.getNodeType());
207         writeValue(String.valueOf(value), true);
208     }
209
210     @Override
211     public void endNode() throws IOException {
212         tracker.endNode();
213         context = context.endNode(schemaContext, writer, indent);
214     }
215
216     private void writeValue(final String str, final boolean needQuotes) throws IOException {
217         if (needQuotes) {
218             writer.append('"');
219             writer.append(str);
220             writer.append('"');
221         } else {
222             writer.append(str);
223         }
224     }
225
226     @Override
227     public void flush() throws IOException {
228         writer.flush();
229     }
230
231     @Override
232     public void close() throws IOException {
233         writer.flush();
234         writer.close();
235     }
236
237 }