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.CharMatcher;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Strings;
13 import com.google.gson.stream.JsonWriter;
15 import java.io.IOException;
16 import java.io.Writer;
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.ContainerSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
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 * RFC6020 deviation: we are not required to emit empty containers unless they
41 * are marked as 'presence'.
43 private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
46 * Matcher used to check if a string needs to be escaped.
48 private static final CharMatcher QUOTES_OR_BACKSLASH = CharMatcher.anyOf("\\\"");
50 private final SchemaTracker tracker;
51 private final JSONCodecFactory codecs;
52 private final Writer writer;
53 private final String indent;
54 private JSONStreamWriterContext context;
56 private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path,
57 final Writer writer, final URI initialNs, final int indentSize) {
58 this.writer = Preconditions.checkNotNull(writer);
60 Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
61 if (indentSize != 0) {
62 indent = Strings.repeat(" ", indentSize);
66 this.codecs = Preconditions.checkNotNull(codecFactory);
67 this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
68 this.context = new JSONStreamWriterRootContext(initialNs);
72 * Create a new stream writer, which writes to the specified {@link Writer}.
74 * @param schemaContext Schema context
75 * @param writer Output writer
76 * @return A stream writer instance
78 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
79 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, 0);
83 * Create a new stream writer, which writes to the specified {@link Writer}.
85 * @param schemaContext Schema context
86 * @param path Root schemapath
87 * @param writer Output writer
88 * @return A stream writer instance
90 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path, final Writer writer) {
91 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, null, 0);
95 * Create a new stream writer, which writes to the specified {@link Writer}.
97 * @param schemaContext Schema context
98 * @param path Root schemapath
99 * @param writer Output writer
100 * @param initialNs Initial namespace
101 * @return A stream writer instance
103 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path,
104 final URI initialNs, final Writer writer) {
105 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, initialNs, 0);
109 * Create a new stream writer, which writes to the specified output stream.
111 * @param schemaContext Schema context
112 * @param writer Output writer
113 * @param indentSize indentation size
114 * @return A stream writer instance
116 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
117 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, indentSize);
121 * Create a new stream writer, which writes to the specified output stream. The codec factory
122 * can be reused between multiple writers.
124 * @param codecFactor JSON codec factory
125 * @param writer Output writer
126 * @param indentSize indentation size
127 * @return A stream writer instance
129 public static NormalizedNodeStreamWriter create(final JSONCodecFactory codecFactory, final Writer writer, final int indentSize) {
130 return new JSONNormalizedNodeStreamWriter(codecFactory, SchemaPath.ROOT, writer, null, indentSize);
134 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
135 final LeafSchemaNode schema = tracker.leafNode(name);
136 final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
138 context.emittingChild(codecs.getSchemaContext(), writer, indent);
139 context.writeJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
140 writeValue(codec.serialize(value), codec.needQuotes());
144 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
145 tracker.startLeafSet(name);
146 context = new JSONStreamWriterListContext(context, name);
150 public void leafSetEntryNode(final Object value) throws IOException {
151 final LeafListSchemaNode schema = tracker.leafSetEntryNode();
152 final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
154 context.emittingChild(codecs.getSchemaContext(), writer, indent);
155 writeValue(codec.serialize(value), codec.needQuotes());
159 * Warning suppressed due to static final constant which triggers a warning
160 * for the call to schema.isPresenceContainer().
162 @SuppressWarnings("unused")
164 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
165 final ContainerSchemaNode schema = tracker.startContainerNode(name);
166 context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS || schema.isPresenceContainer());
170 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
171 tracker.startList(name);
172 context = new JSONStreamWriterListContext(context, name);
176 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
177 tracker.startListItem(name);
178 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
182 public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
183 tracker.startList(name);
184 context = new JSONStreamWriterListContext(context, name);
188 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
190 tracker.startListItem(identifier);
191 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
195 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
196 tracker.startList(name);
197 context = new JSONStreamWriterListContext(context, name);
201 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
202 tracker.startChoiceNode(name);
203 context = new JSONStreamWriterInvisibleContext(context);
207 public void startAugmentationNode(final AugmentationIdentifier identifier) {
208 tracker.startAugmentationNode(identifier);
209 context = new JSONStreamWriterInvisibleContext(context);
213 public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
214 final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
215 // FIXME: should have a codec based on this :)
217 context.emittingChild(codecs.getSchemaContext(), writer, indent);
218 context.writeJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
219 writeValue(String.valueOf(value), true);
223 public void endNode() throws IOException {
225 context = context.endNode(codecs.getSchemaContext(), writer, indent);
228 private void writeValue(final String str, final boolean needQuotes) throws IOException {
232 final int needEscape = QUOTES_OR_BACKSLASH.countIn(str);
233 if (needEscape != 0) {
234 final char[] escaped = new char[str.length() + needEscape];
237 for (int i = 0; i < str.length(); i++) {
238 final char c = str.charAt(i);
239 if (QUOTES_OR_BACKSLASH.matches(c)) {
240 escaped[offset++] = '\\';
242 escaped[offset++] = c;
244 writer.write(escaped);
256 public void flush() throws IOException {
261 public void close() throws IOException {