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 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.ContainerSchemaNode;
21 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
22 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
24 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
26 import java.io.IOException;
27 import java.io.Writer;
31 * This implementation will create JSON output as output stream.
33 * Values of leaf and leaf-list are NOT translated according to codecs.
35 * FIXME: rewrite this in terms of {@link JsonWriter}.
37 public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
39 * RFC6020 deviation: we are not required to emit empty containers unless they
40 * are marked as 'presence'.
42 private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
45 * Matcher used to check if a string needs to be escaped.
47 private static final CharMatcher JSON_ILLEGAL_STRING_CHARACTERS = CharMatcher.anyOf("\\\"\n\r");
49 private final SchemaTracker tracker;
50 private final JSONCodecFactory codecs;
51 private final Writer writer;
52 private final String indent;
53 private JSONStreamWriterContext context;
55 private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path,
56 final Writer writer, final URI initialNs, final int indentSize) {
57 this.writer = Preconditions.checkNotNull(writer);
59 Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
60 if (indentSize != 0) {
61 indent = Strings.repeat(" ", indentSize);
65 this.codecs = Preconditions.checkNotNull(codecFactory);
66 this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
67 this.context = new JSONStreamWriterRootContext(initialNs);
71 * Create a new stream writer, which writes to the specified {@link Writer}.
73 * @param schemaContext Schema context
74 * @param writer Output writer
75 * @return A stream writer instance
77 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
78 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, 0);
82 * Create a new stream writer, which writes to the specified {@link Writer}.
84 * @param schemaContext Schema context
85 * @param path Root schemapath
86 * @param writer Output writer
87 * @return A stream writer instance
89 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path, final Writer writer) {
90 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, null, 0);
94 * Create a new stream writer, which writes to the specified {@link Writer}.
96 * @param schemaContext Schema context
97 * @param path Root schemapath
98 * @param writer Output writer
99 * @param initialNs Initial namespace
100 * @return A stream writer instance
102 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path,
103 final URI initialNs, final Writer writer) {
104 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, initialNs, 0);
108 * Create a new stream writer, which writes to the specified output stream.
110 * @param schemaContext Schema context
111 * @param writer Output writer
112 * @param indentSize indentation size
113 * @return A stream writer instance
115 public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
116 return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, indentSize);
120 * Create a new stream writer, which writes to the specified output stream. The codec factory
121 * can be reused between multiple writers.
123 * @param codecFactor JSON codec factory
124 * @param writer Output writer
125 * @param indentSize indentation size
126 * @return A stream writer instance
128 public static NormalizedNodeStreamWriter create(final JSONCodecFactory codecFactory, final Writer writer, final int indentSize) {
129 return new JSONNormalizedNodeStreamWriter(codecFactory, SchemaPath.ROOT, writer, null, indentSize);
133 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
134 final LeafSchemaNode schema = tracker.leafNode(name);
135 final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
137 context.emittingChild(codecs.getSchemaContext(), writer, indent);
138 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
139 writeValue(codec.serialize(value), codec.needQuotes());
143 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
144 tracker.startLeafSet(name);
145 context = new JSONStreamWriterListContext(context, name);
149 public void leafSetEntryNode(final Object value) throws IOException {
150 final LeafListSchemaNode schema = tracker.leafSetEntryNode();
151 final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
153 context.emittingChild(codecs.getSchemaContext(), writer, indent);
154 writeValue(codec.serialize(value), codec.needQuotes());
158 * Warning suppressed due to static final constant which triggers a warning
159 * for the call to schema.isPresenceContainer().
161 @SuppressWarnings("unused")
163 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
164 final ContainerSchemaNode schema = tracker.startContainerNode(name);
165 context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS || schema.isPresenceContainer());
169 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
170 tracker.startList(name);
171 context = new JSONStreamWriterListContext(context, name);
175 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
176 tracker.startListItem(name);
177 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
181 public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
182 tracker.startList(name);
183 context = new JSONStreamWriterListContext(context, name);
187 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
189 tracker.startListItem(identifier);
190 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
194 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
195 tracker.startList(name);
196 context = new JSONStreamWriterListContext(context, name);
200 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
201 tracker.startChoiceNode(name);
202 context = new JSONStreamWriterInvisibleContext(context);
206 public void startAugmentationNode(final AugmentationIdentifier identifier) {
207 tracker.startAugmentationNode(identifier);
208 context = new JSONStreamWriterInvisibleContext(context);
212 public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
213 @SuppressWarnings("unused")
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.writeChildJsonIdentifier(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 = JSON_ILLEGAL_STRING_CHARACTERS.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 (JSON_ILLEGAL_STRING_CHARACTERS.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 {