2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.codec.gson;
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;
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;
32 * This implementation will create JSON output as output stream.
34 * Values of leaf and leaf-list are NOT translated according to codecs.
36 * FIXME: rewrite this in terms of {@link JsonWriter}.
38 public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
40 private static enum NodeType {
46 private static class TypeInfo {
47 private boolean hasAtLeastOneChild = false;
48 private final NodeType type;
49 private final URI uri;
51 public TypeInfo(final NodeType type, final URI uri) {
56 public void setHasAtLeastOneChild(final boolean hasChildren) {
57 this.hasAtLeastOneChild = hasChildren;
60 public NodeType getType() {
64 public URI getNamespace() {
68 public boolean hasAtLeastOneChild() {
69 return hasAtLeastOneChild;
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;
80 private URI currentNamespace = null;
81 private int currentDepth = 0;
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);
88 Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
89 if (indentSize != 0) {
90 indent = Strings.repeat(" ", indentSize);
95 this.codecs = CodecFactory.create(schemaContext);
96 this.tracker = SchemaTracker.create(schemaContext);
99 private JSONNormalizedNodeStreamWriter(final SchemaContext schemaContext, final SchemaPath path,
100 final Writer writer, final URI initialNs,final int indentSize) {
101 this.schemaContext = Preconditions.checkNotNull(schemaContext);
102 this.writer = Preconditions.checkNotNull(writer);
104 Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
105 if (indentSize != 0) {
106 indent = Strings.repeat(" ", indentSize);
110 this.currentNamespace = initialNs;
111 this.codecs = CodecFactory.create(schemaContext);
112 this.tracker = SchemaTracker.create(schemaContext,path);
116 * Create a new stream writer, which writes to the specified {@link Writer}.
118 * @param schemaContext Schema context
119 * @param writer Output writer
120 * @return A stream writer instance
122 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
123 return new JSONNormalizedNodeStreamWriter(schemaContext, writer, 0);
127 * Create a new stream writer, which writes to the specified {@link Writer}.
129 * @param schemaContext Schema context
130 * @param writer Output writer
131 * @return A stream writer instance
133 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, SchemaPath path,final Writer writer) {
134 return new JSONNormalizedNodeStreamWriter(schemaContext, path, writer, null, 0);
138 * Create a new stream writer, which writes to the specified {@link Writer}.
140 * @param schemaContext Schema context
141 * @param writer Output writer
142 * @param initialNs Initial namespace
143 * @return A stream writer instance
145 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, SchemaPath path,URI initialNs, final Writer writer) {
146 return new JSONNormalizedNodeStreamWriter(schemaContext, path, writer, initialNs, 0);
150 * Create a new stream writer, which writes to the specified output stream.
152 * @param schemaContext Schema context
153 * @param writer Output writer
154 * @param indentSize indentation size
155 * @return A stream writer instance
157 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
158 return new JSONNormalizedNodeStreamWriter(schemaContext, writer, indentSize);
162 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
163 final LeafSchemaNode schema = tracker.leafNode(name);
164 final Codec<Object, Object> codec = codecs.codecFor(schema.getType());
166 separateElementFromPreviousElement();
167 writeJsonIdentifier(name);
168 currentNamespace = stack.peek().getNamespace();
169 writeValue(String.valueOf(codec.serialize(value)));
170 separateNextSiblingsWithComma();
174 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
175 tracker.startLeafSet(name);
177 separateElementFromPreviousElement();
178 stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
179 writeJsonIdentifier(name);
185 public void leafSetEntryNode(final Object value) throws IOException {
186 final LeafListSchemaNode schema = tracker.leafSetEntryNode();
187 final Codec<Object, Object> codec = codecs.codecFor(schema.getType());
189 separateElementFromPreviousElement();
190 writeValue(String.valueOf(codec.serialize(value)));
191 separateNextSiblingsWithComma();
195 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
196 tracker.startContainerNode(name);
198 separateElementFromPreviousElement();
199 stack.push(new TypeInfo(NodeType.OBJECT, name.getNodeType().getNamespace()));
200 writeJsonIdentifier(name);
206 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
207 tracker.startList(name);
209 separateElementFromPreviousElement();
210 stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
211 writeJsonIdentifier(name);
217 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
218 tracker.startListItem(name);
220 separateElementFromPreviousElement();
221 stack.push(new TypeInfo(NodeType.OBJECT, name.getNodeType().getNamespace()));
227 public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
228 tracker.startList(name);
230 separateElementFromPreviousElement();
231 stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
232 writeJsonIdentifier(name);
238 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
240 tracker.startListItem(identifier);
241 separateElementFromPreviousElement();
242 stack.push(new TypeInfo(NodeType.OBJECT, identifier.getNodeType().getNamespace()));
250 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
251 tracker.startListItem(name);
253 stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
254 separateElementFromPreviousElement();
255 writeJsonIdentifier(name);
261 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
262 tracker.startChoiceNode(name);
263 handleInvisibleNode(name.getNodeType().getNamespace());
267 public void startAugmentationNode(final AugmentationIdentifier identifier) throws IllegalArgumentException {
268 tracker.startAugmentationNode(identifier);
269 handleInvisibleNode(currentNamespace);
273 public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
274 final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
275 // FIXME: should have a codec based on this :)
277 separateElementFromPreviousElement();
278 writeJsonIdentifier(name);
279 currentNamespace = stack.peek().getNamespace();
280 writeValue(value.toString());
281 separateNextSiblingsWithComma();
285 public void endNode() throws IOException {
288 final TypeInfo t = stack.pop();
289 switch (t.getType()) {
304 currentNamespace = stack.isEmpty() ? null : stack.peek().getNamespace();
305 separateNextSiblingsWithComma();
308 private void separateElementFromPreviousElement() throws IOException {
309 if (!stack.isEmpty() && stack.peek().hasAtLeastOneChild()) {
315 private void newLine() throws IOException {
316 if (indent != null) {
319 for (int i = 0; i < currentDepth; i++) {
320 writer.append(indent);
325 private void separateNextSiblingsWithComma() {
326 if (!stack.isEmpty()) {
327 stack.peek().setHasAtLeastOneChild(true);
332 * Invisible nodes have to be also pushed to stack because of pairing of start*() and endNode() methods. Information
333 * about child existing (due to printing comma) has to be transfered to invisible node.
335 private void handleInvisibleNode(final URI uri) {
336 TypeInfo typeInfo = new TypeInfo(NodeType.OTHER, uri);
337 typeInfo.setHasAtLeastOneChild(stack.peek().hasAtLeastOneChild());
338 stack.push(typeInfo);
341 private void writeStartObject() throws IOException {
345 private void writeStartList() throws IOException {
349 private void writeModulName(final URI namespace) throws IOException {
350 if (this.currentNamespace == null || namespace != this.currentNamespace) {
351 Module module = schemaContext.findModuleByNamespaceAndRevision(namespace, null);
352 writer.append(module.getName());
354 currentNamespace = namespace;
358 private void writeValue(final String value) throws IOException {
360 writer.append(value);
364 private void writeJsonIdentifier(final NodeIdentifier name) throws IOException {
366 writeModulName(name.getNodeType().getNamespace());
367 writer.append(name.getNodeType().getLocalName());
368 writer.append("\":");
371 private void indentRight() {
375 private void indentLeft() {
380 public void flush() throws IOException {
385 public void close() throws IOException {