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 static java.util.Objects.requireNonNull;
11 import static org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream.ANYXML_ARRAY_ELEMENT_ID;
12 import static org.w3c.dom.Node.ELEMENT_NODE;
13 import static org.w3c.dom.Node.TEXT_NODE;
15 import com.google.gson.stream.JsonWriter;
16 import java.io.IOException;
18 import java.util.regex.Pattern;
19 import javax.annotation.RegEx;
20 import javax.xml.transform.dom.DOMSource;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
25 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
26 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
27 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
32 import org.w3c.dom.Element;
33 import org.w3c.dom.Node;
34 import org.w3c.dom.NodeList;
35 import org.w3c.dom.Text;
38 * This implementation will create JSON output as output stream.
41 * Values of leaf and leaf-list are NOT translated according to codecs.
43 public abstract class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
44 private static final class Exclusive extends JSONNormalizedNodeStreamWriter {
45 Exclusive(final JSONCodecFactory codecFactory, final SchemaPath path, final JsonWriter writer,
46 final JSONStreamWriterRootContext rootContext) {
47 super(codecFactory, path, writer, rootContext);
51 public void close() throws IOException {
57 private static final class Nested extends JSONNormalizedNodeStreamWriter {
58 Nested(final JSONCodecFactory codecFactory, final SchemaPath path, final JsonWriter writer,
59 final JSONStreamWriterRootContext rootContext) {
60 super(codecFactory, path, writer, rootContext);
64 public void close() throws IOException {
66 // The caller "owns" the writer, let them close it
71 * RFC6020 deviation: we are not required to emit empty containers unless they
72 * are marked as 'presence'.
74 private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
77 private static final String NUMBER_STRING = "-?\\d+(\\.\\d+)?";
78 private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_STRING);
81 private static final String NOT_DECIMAL_NUMBER_STRING = "-?\\d+";
82 private static final Pattern NOT_DECIMAL_NUMBER_PATTERN = Pattern.compile(NOT_DECIMAL_NUMBER_STRING);
84 private final SchemaTracker tracker;
85 private final JSONCodecFactory codecs;
86 private final JsonWriter writer;
87 private JSONStreamWriterContext context;
89 JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path, final JsonWriter writer,
90 final JSONStreamWriterRootContext rootContext) {
91 this.writer = requireNonNull(writer);
92 this.codecs = requireNonNull(codecFactory);
93 this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
94 this.context = requireNonNull(rootContext);
98 * Create a new stream writer, which writes to the specified output stream.
101 * The codec factory can be reused between multiple writers.
104 * Returned writer is exclusive user of JsonWriter, which means it will start
105 * top-level JSON element and ends it.
108 * This instance of writer can be used only to emit one top level element,
109 * otherwise it will produce incorrect JSON. Closing this instance will close
112 * @param codecFactory JSON codec factory
113 * @param path Schema Path
114 * @param initialNs Initial namespace
115 * @param jsonWriter JsonWriter
116 * @return A stream writer instance
118 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
119 final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
120 return new Exclusive(codecFactory, path, jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
124 * Create a new stream writer, which writes to the specified output stream.
127 * The codec factory can be reused between multiple writers.
130 * Returned writer can be used emit multiple top level element,
131 * but does not start / close parent JSON object, which must be done
132 * by user providing {@code jsonWriter} instance in order for
133 * JSON to be valid. Closing this instance <strong>will not</strong>
134 * close the wrapped writer; the caller must take care of that.
136 * @param codecFactory JSON codec factory
137 * @param path Schema Path
138 * @param initialNs Initial namespace
139 * @param jsonWriter JsonWriter
140 * @return A stream writer instance
142 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
143 final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
144 return new Nested(codecFactory, path, jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
148 public final void leafNode(final NodeIdentifier name, final Object value) throws IOException {
149 final LeafSchemaNode schema = tracker.leafNode(name);
150 final JSONCodec<?> codec = codecs.codecFor(schema);
151 context.emittingChild(codecs.getSchemaContext(), writer);
152 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
153 writeValue(value, codec);
157 public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
158 tracker.startLeafSet(name);
159 context = new JSONStreamWriterListContext(context, name);
163 public final void leafSetEntryNode(final QName name, final Object value) throws IOException {
164 final LeafListSchemaNode schema = tracker.leafSetEntryNode(name);
165 final JSONCodec<?> codec = codecs.codecFor(schema);
166 context.emittingChild(codecs.getSchemaContext(), writer);
167 writeValue(value, codec);
171 public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
172 tracker.startLeafSet(name);
173 context = new JSONStreamWriterListContext(context, name);
177 * Warning suppressed due to static final constant which triggers a warning
178 * for the call to schema.isPresenceContainer().
180 @SuppressWarnings("unused")
182 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
183 final SchemaNode schema = tracker.startContainerNode(name);
185 // FIXME this code ignores presence for containers
186 // but datastore does as well and it needs be fixed first (2399)
187 context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
191 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
192 tracker.startList(name);
193 context = new JSONStreamWriterListContext(context, name);
197 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
198 tracker.startListItem(name);
199 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
203 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
204 tracker.startList(name);
205 context = new JSONStreamWriterListContext(context, name);
209 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
211 tracker.startListItem(identifier);
212 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
216 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
217 tracker.startList(name);
218 context = new JSONStreamWriterListContext(context, name);
222 public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
223 tracker.startChoiceNode(name);
224 context = new JSONStreamWriterInvisibleContext(context);
228 public final void startAugmentationNode(final AugmentationIdentifier identifier) {
229 tracker.startAugmentationNode(identifier);
230 context = new JSONStreamWriterInvisibleContext(context);
234 public final void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
235 @SuppressWarnings("unused")
236 final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
237 // FIXME: should have a codec based on this :)
239 context.emittingChild(codecs.getSchemaContext(), writer);
240 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
242 writeAnyXmlValue((DOMSource) value);
246 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
248 tracker.startYangModeledAnyXmlNode(name);
249 context = new JSONStreamWriterNamedObjectContext(context, name, true);
253 public final void endNode() throws IOException {
255 context = context.endNode(codecs.getSchemaContext(), writer);
257 if (context instanceof JSONStreamWriterRootContext) {
258 context.emitEnd(writer);
263 public final void flush() throws IOException {
267 final void closeWriter() throws IOException {
271 @SuppressWarnings("unchecked")
272 private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
273 ((JSONCodec<Object>) codec).writeValue(writer, value);
276 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
277 writeXmlNode(anyXmlValue.getNode());
280 private void writeXmlNode(final Node node) throws IOException {
281 final Element firstChildElement = getFirstChildElement(node);
282 if (firstChildElement == null) {
284 } else if (ANYXML_ARRAY_ELEMENT_ID.equals(firstChildElement.getNodeName())) {
286 writeArray(firstChildElement);
289 writer.beginObject();
290 writeObject(firstChildElement);
295 private void writeArray(Node node) throws IOException {
296 while (node != null) {
297 if (ELEMENT_NODE == node.getNodeType()) {
300 node = node.getNextSibling();
304 private void writeObject(Node node) throws IOException {
305 while (node != null) {
306 if (ELEMENT_NODE == node.getNodeType()) {
307 writer.name(node.getNodeName());
310 node = node.getNextSibling();
314 private void writeXmlValue(final Node node) throws IOException {
315 final String childNodeText = getFirstChildText(node).getWholeText().trim();
316 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
317 writer.value(parseNumber(childNodeText));
320 switch (childNodeText) {
331 writer.value(childNodeText);
335 private static Element getFirstChildElement(final Node node) {
336 final NodeList children = node.getChildNodes();
337 for (int i = 0, length = children.getLength(); i < length; i++) {
338 final Node childNode = children.item(i);
339 if (ELEMENT_NODE == childNode.getNodeType()) {
340 return (Element) childNode;
346 private static Text getFirstChildText(final Node node) {
347 final NodeList children = node.getChildNodes();
348 for (int i = 0, length = children.getLength(); i < length; i++) {
349 final Node childNode = children.item(i);
350 if (TEXT_NODE == childNode.getNodeType()) {
351 return (Text) childNode;
357 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
358 private static Number parseNumber(final String numberText) {
359 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
360 return Long.valueOf(numberText);
363 return Double.valueOf(numberText);