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