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.ContainerSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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 QUOTES_OR_BACKSLASH = CharMatcher.anyOf("\\\"");
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 codecFactor 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 ContainerSchemaNode schema = tracker.startContainerNode(name);
164 context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS || schema.isPresenceContainer());
168 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
169 tracker.startList(name);
170 context = new JSONStreamWriterListContext(context, name);
174 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
175 tracker.startListItem(name);
176 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
180 public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
181 tracker.startList(name);
182 context = new JSONStreamWriterListContext(context, name);
186 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
188 tracker.startListItem(identifier);
189 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
193 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
194 tracker.startList(name);
195 context = new JSONStreamWriterListContext(context, name);
199 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
200 tracker.startChoiceNode(name);
201 context = new JSONStreamWriterInvisibleContext(context);
205 public void startAugmentationNode(final AugmentationIdentifier identifier) {
206 tracker.startAugmentationNode(identifier);
207 context = new JSONStreamWriterInvisibleContext(context);
211 public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
212 @SuppressWarnings("unused")
213 final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
214 // FIXME: should have a codec based on this :)
216 context.emittingChild(codecs.getSchemaContext(), writer, indent);
217 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
218 writeValue(String.valueOf(value), true);
222 public void endNode() throws IOException {
224 context = context.endNode(codecs.getSchemaContext(), writer, indent);
227 private void writeValue(final String str, final boolean needQuotes) throws IOException {
231 final int needEscape = QUOTES_OR_BACKSLASH.countIn(str);
232 if (needEscape != 0) {
233 final char[] escaped = new char[str.length() + needEscape];
236 for (int i = 0; i < str.length(); i++) {
237 final char c = str.charAt(i);
238 if (QUOTES_OR_BACKSLASH.matches(c)) {
239 escaped[offset++] = '\\';
241 escaped[offset++] = c;
243 writer.write(escaped);
255 public void flush() throws IOException {
260 public void close() throws IOException {