Bug 4969: NPE in JSONCodecFactory by attempt to find codec for a leafref
[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.gson.stream.JsonWriter;
12 import java.io.IOException;
13 import java.net.URI;
14 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
17 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
18 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
19 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
20 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
21 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
22 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
24
25 /**
26  * This implementation will create JSON output as output stream.
27  *
28  * Values of leaf and leaf-list are NOT translated according to codecs.
29  *
30  */
31 public final class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
32     /**
33      * RFC6020 deviation: we are not required to emit empty containers unless they
34      * are marked as 'presence'.
35      */
36     private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
37
38     private final SchemaTracker tracker;
39     private final JSONCodecFactory codecs;
40     private final JsonWriter writer;
41     private JSONStreamWriterContext context;
42
43     private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path, final JsonWriter JsonWriter, final JSONStreamWriterRootContext rootContext) {
44         this.writer = Preconditions.checkNotNull(JsonWriter);
45         this.codecs = Preconditions.checkNotNull(codecFactory);
46         this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
47         this.context = Preconditions.checkNotNull(rootContext);
48     }
49
50     /**
51      * Create a new stream writer, which writes to the specified output stream.
52      *
53      * The codec factory can be reused between multiple writers.
54      *
55      * Returned writer is exclusive user of JsonWriter, which means it will start
56      * top-level JSON element and ends it.
57      *
58      * This instance of writer can be used only to emit one top level element,
59      * otherwise it will produce incorrect JSON.
60      *
61      * @param codecFactory JSON codec factory
62      * @param path Schema Path
63      * @param initialNs Initial namespace
64      * @param jsonWriter JsonWriter
65      * @return A stream writer instance
66      */
67     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory, final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
68         return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
69     }
70
71     /**
72      * Create a new stream writer, which writes to the specified output stream.
73      *
74      * The codec factory can be reused between multiple writers.
75      *
76      * Returned writer can be used emit multiple top level element,
77      * but does not start / close parent JSON object, which must be done
78      * by user providing {@code jsonWriter} instance in order for
79      * JSON to be valid.
80      *
81      * @param codecFactory JSON codec factory
82      * @param path Schema Path
83      * @param initialNs Initial namespace
84      * @param jsonWriter JsonWriter
85      * @return A stream writer instance
86      */
87     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory, final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
88         return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
89     }
90
91     @Override
92     public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
93         final LeafSchemaNode schema = tracker.leafNode(name);
94         final JSONCodec<Object> codec = codecs.codecFor(schema);
95         context.emittingChild(codecs.getSchemaContext(), writer);
96         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
97         writeValue(value, codec);
98     }
99
100     @Override
101     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
102         tracker.startLeafSet(name);
103         context = new JSONStreamWriterListContext(context, name);
104     }
105
106     @Override
107     public void leafSetEntryNode(final Object value) throws IOException {
108         final LeafListSchemaNode schema = tracker.leafSetEntryNode();
109         final JSONCodec<Object> codec = codecs.codecFor(schema);
110         context.emittingChild(codecs.getSchemaContext(), writer);
111         writeValue(value, codec);
112     }
113
114     @Override
115     public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
116         tracker.startLeafSet(name);
117         context = new JSONStreamWriterListContext(context, name);
118     }
119
120     /*
121      * Warning suppressed due to static final constant which triggers a warning
122      * for the call to schema.isPresenceContainer().
123      */
124     @SuppressWarnings("unused")
125     @Override
126     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
127         final SchemaNode schema = tracker.startContainerNode(name);
128
129         // FIXME this code ignores presence for containers
130         // but datastore does as well and it needs be fixed first (2399)
131         context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
132     }
133
134     @Override
135     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
136         tracker.startList(name);
137         context = new JSONStreamWriterListContext(context, name);
138     }
139
140     @Override
141     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
142         tracker.startListItem(name);
143         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
144     }
145
146     @Override
147     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
148         tracker.startList(name);
149         context = new JSONStreamWriterListContext(context, name);
150     }
151
152     @Override
153     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
154             throws IOException {
155         tracker.startListItem(identifier);
156         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
157     }
158
159     @Override
160     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
161         tracker.startList(name);
162         context = new JSONStreamWriterListContext(context, name);
163     }
164
165     @Override
166     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
167         tracker.startChoiceNode(name);
168         context = new JSONStreamWriterInvisibleContext(context);
169     }
170
171     @Override
172     public void startAugmentationNode(final AugmentationIdentifier identifier) {
173         tracker.startAugmentationNode(identifier);
174         context = new JSONStreamWriterInvisibleContext(context);
175     }
176
177     @Override
178     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
179         @SuppressWarnings("unused")
180         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
181         // FIXME: should have a codec based on this :)
182
183         context.emittingChild(codecs.getSchemaContext(), writer);
184         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
185         // FIXME this kind of serialization is incorrect since the value for AnyXml is now a DOMSource
186         writer.value(String.valueOf(value));
187     }
188
189     @Override
190     public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
191         tracker.startYangModeledAnyXmlNode(name);
192         context = new JSONStreamWriterNamedObjectContext(context, name, true);
193     }
194
195     @Override
196     public void endNode() throws IOException {
197         tracker.endNode();
198         context = context.endNode(codecs.getSchemaContext(), writer);
199
200         if(context instanceof JSONStreamWriterRootContext) {
201             context.emitEnd(writer);
202         }
203     }
204
205     private void writeValue(final Object value, final JSONCodec<Object> codec)
206             throws IOException {
207         codec.serializeToWriter(writer,value);
208     }
209
210     @Override
211     public void flush() throws IOException {
212         writer.flush();
213     }
214
215     @Override
216     public void close() throws IOException {
217         flush();
218         writer.close();
219     }
220 }