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;
14 import java.io.IOException;
15 import java.io.Writer;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
20 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
21 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
22 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
26 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
30 * This implementation will create JSON output as output stream.
32 * Values of leaf and leaf-list are NOT translated according to codecs.
34 * FIXME: rewrite this in terms of {@link JsonWriter}.
36 public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
38 * RFC6020 deviation: we are not required to emit empty containers unless they
39 * are marked as 'presence'.
41 private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
44 * Matcher used to check if a string needs to be escaped.
46 private static final CharMatcher JSON_ILLEGAL_STRING_CHARACTERS = CharMatcher.anyOf("\\\"\n\r");
48 private final SchemaTracker tracker;
49 private final JSONCodecFactory codecs;
50 private final Writer writer;
51 private final String indent;
52 private JSONStreamWriterContext context;
54 private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path,
55 final Writer writer, final URI initialNs, final int indentSize) {
56 this.writer = Preconditions.checkNotNull(writer);
58 Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
59 if (indentSize != 0) {
60 indent = Strings.repeat(" ", indentSize);
64 this.codecs = Preconditions.checkNotNull(codecFactory);
65 this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
66 this.context = new JSONStreamWriterRootContext(initialNs);
70 * Create a new stream writer, which writes to the specified {@link Writer}.
72 * @param schemaContext Schema context
73 * @param writer Output writer
74 * @return A stream writer instance
76 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
77 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, 0);
81 * Create a new stream writer, which writes to the specified {@link Writer}.
83 * @param schemaContext Schema context
84 * @param path Root schemapath
85 * @param writer Output writer
86 * @return A stream writer instance
88 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path, final Writer writer) {
89 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, null, 0);
93 * Create a new stream writer, which writes to the specified {@link Writer}.
95 * @param schemaContext Schema context
96 * @param path Root schemapath
97 * @param writer Output writer
98 * @param initialNs Initial namespace
99 * @return A stream writer instance
101 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path,
102 final URI initialNs, final Writer writer) {
103 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, initialNs, 0);
107 * Create a new stream writer, which writes to the specified output stream.
109 * @param schemaContext Schema context
110 * @param writer Output writer
111 * @param indentSize indentation size
112 * @return A stream writer instance
114 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
115 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, indentSize);
119 * Create a new stream writer, which writes to the specified output stream. The codec factory
120 * can be reused between multiple writers.
122 * @param codecFactory JSON codec factory
123 * @param writer Output writer
124 * @param indentSize indentation size
125 * @return A stream writer instance
127 public static NormalizedNodeStreamWriter create(final JSONCodecFactory codecFactory, final Writer writer, final int indentSize) {
128 return new JSONNormalizedNodeStreamWriter(codecFactory, SchemaPath.ROOT, writer, null, indentSize);
132 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
133 final LeafSchemaNode schema = tracker.leafNode(name);
134 final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
136 context.emittingChild(codecs.getSchemaContext(), writer, indent);
137 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
138 writeValue(codec.serialize(value), codec.needQuotes());
142 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
143 tracker.startLeafSet(name);
144 context = new JSONStreamWriterListContext(context, name);
148 public void leafSetEntryNode(final Object value) throws IOException {
149 final LeafListSchemaNode schema = tracker.leafSetEntryNode();
150 final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
152 context.emittingChild(codecs.getSchemaContext(), writer, indent);
153 writeValue(codec.serialize(value), codec.needQuotes());
157 * Warning suppressed due to static final constant which triggers a warning
158 * for the call to schema.isPresenceContainer().
160 @SuppressWarnings("unused")
162 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
163 final SchemaNode schema = tracker.startContainerNode(name);
165 // FIXME this code ignores presence for containers
166 // but datastore does as well and it needs be fixed first (2399)
167 context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
171 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
172 tracker.startList(name);
173 context = new JSONStreamWriterListContext(context, name);
177 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
178 tracker.startListItem(name);
179 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
183 public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
184 tracker.startList(name);
185 context = new JSONStreamWriterListContext(context, name);
189 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
191 tracker.startListItem(identifier);
192 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
196 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
197 tracker.startList(name);
198 context = new JSONStreamWriterListContext(context, name);
202 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
203 tracker.startChoiceNode(name);
204 context = new JSONStreamWriterInvisibleContext(context);
208 public void startAugmentationNode(final AugmentationIdentifier identifier) {
209 tracker.startAugmentationNode(identifier);
210 context = new JSONStreamWriterInvisibleContext(context);
214 public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
215 @SuppressWarnings("unused")
216 final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
217 // FIXME: should have a codec based on this :)
219 context.emittingChild(codecs.getSchemaContext(), writer, indent);
220 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
221 writeValue(String.valueOf(value), true);
225 public void endNode() throws IOException {
227 context = context.endNode(codecs.getSchemaContext(), writer, indent);
230 private void writeValue(final String str, final boolean needQuotes) throws IOException {
234 final int needEscape = JSON_ILLEGAL_STRING_CHARACTERS.countIn(str);
235 if (needEscape != 0) {
236 final char[] escaped = new char[str.length() + needEscape];
239 for (int i = 0; i < str.length(); i++) {
240 final char c = str.charAt(i);
241 if (JSON_ILLEGAL_STRING_CHARACTERS.matches(c)) {
242 escaped[offset++] = '\\';
244 escaped[offset++] = c;
246 writer.write(escaped);
258 public void flush() throws IOException {
263 public void close() throws IOException {