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.w3c.dom.Node.ELEMENT_NODE;
12 import static org.w3c.dom.Node.TEXT_NODE;
14 import com.google.gson.stream.JsonWriter;
15 import java.io.IOException;
17 import java.util.regex.Pattern;
18 import javax.annotation.RegEx;
19 import javax.xml.transform.dom.DOMSource;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
24 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
25 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
26 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
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 SchemaTracker tracker, final JsonWriter writer,
46 final JSONStreamWriterRootContext rootContext) {
47 super(codecFactory, tracker, writer, rootContext);
51 public void close() throws IOException {
57 private static final class Nested extends JSONNormalizedNodeStreamWriter {
58 Nested(final JSONCodecFactory codecFactory, final SchemaTracker tracker, final JsonWriter writer,
59 final JSONStreamWriterRootContext rootContext) {
60 super(codecFactory, tracker, 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 SchemaTracker tracker,
90 final JsonWriter writer, final JSONStreamWriterRootContext rootContext) {
91 this.writer = requireNonNull(writer);
92 this.codecs = requireNonNull(codecFactory);
93 this.tracker = requireNonNull(tracker);
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, SchemaTracker.create(codecFactory.getSchemaContext(), path), jsonWriter,
121 new JSONStreamWriterExclusiveRootContext(initialNs));
125 * Create a new stream writer, which writes to the specified output stream.
128 * The codec factory can be reused between multiple writers.
131 * Returned writer is exclusive user of JsonWriter, which means it will start
132 * top-level JSON element and ends it.
135 * This instance of writer can be used only to emit one top level element,
136 * otherwise it will produce incorrect JSON. Closing this instance will close
139 * @param codecFactory JSON codec factory
140 * @param rootNode Root node
141 * @param initialNs Initial namespace
142 * @param jsonWriter JsonWriter
143 * @return A stream writer instance
145 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
146 final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
147 return new Exclusive(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
148 new JSONStreamWriterExclusiveRootContext(initialNs));
152 * Create a new stream writer, which writes to the specified output stream.
155 * The codec factory can be reused between multiple writers.
158 * Returned writer can be used emit multiple top level element,
159 * but does not start / close parent JSON object, which must be done
160 * by user providing {@code jsonWriter} instance in order for
161 * JSON to be valid. Closing this instance <strong>will not</strong>
162 * close the wrapped writer; the caller must take care of that.
164 * @param codecFactory JSON codec factory
165 * @param path Schema Path
166 * @param initialNs Initial namespace
167 * @param jsonWriter JsonWriter
168 * @return A stream writer instance
170 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
171 final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
172 return new Nested(codecFactory, SchemaTracker.create(codecFactory.getSchemaContext(), path), jsonWriter,
173 new JSONStreamWriterSharedRootContext(initialNs));
177 * Create a new stream writer, which writes to the specified output stream.
180 * The codec factory can be reused between multiple writers.
183 * Returned writer can be used emit multiple top level element,
184 * but does not start / close parent JSON object, which must be done
185 * by user providing {@code jsonWriter} instance in order for
186 * JSON to be valid. Closing this instance <strong>will not</strong>
187 * close the wrapped writer; the caller must take care of that.
189 * @param codecFactory JSON codec factory
190 * @param rootNode Root node
191 * @param initialNs Initial namespace
192 * @param jsonWriter JsonWriter
193 * @return A stream writer instance
195 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
196 final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
197 return new Nested(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
198 new JSONStreamWriterSharedRootContext(initialNs));
202 public final void leafNode(final NodeIdentifier name, final Object value) throws IOException {
203 final LeafSchemaNode schema = tracker.leafNode(name);
204 final JSONCodec<?> codec = codecs.codecFor(schema);
205 context.emittingChild(codecs.getSchemaContext(), writer);
206 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
207 writeValue(value, codec);
211 public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
212 tracker.startLeafSet(name);
213 context = new JSONStreamWriterListContext(context, name);
217 public final void leafSetEntryNode(final QName name, final Object value) throws IOException {
218 final LeafListSchemaNode schema = tracker.leafSetEntryNode(name);
219 final JSONCodec<?> codec = codecs.codecFor(schema);
220 context.emittingChild(codecs.getSchemaContext(), writer);
221 writeValue(value, codec);
225 public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
226 tracker.startLeafSet(name);
227 context = new JSONStreamWriterListContext(context, name);
231 * Warning suppressed due to static final constant which triggers a warning
232 * for the call to schema.isPresenceContainer().
235 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
236 final SchemaNode schema = tracker.startContainerNode(name);
237 final boolean isPresence = schema instanceof ContainerSchemaNode
238 ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
239 context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
243 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
244 tracker.startList(name);
245 context = new JSONStreamWriterListContext(context, name);
249 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
250 tracker.startListItem(name);
251 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
255 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
256 tracker.startList(name);
257 context = new JSONStreamWriterListContext(context, name);
261 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
263 tracker.startListItem(identifier);
264 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
268 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
269 tracker.startList(name);
270 context = new JSONStreamWriterListContext(context, name);
274 public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
275 tracker.startChoiceNode(name);
276 context = new JSONStreamWriterInvisibleContext(context);
280 public final void startAugmentationNode(final AugmentationIdentifier identifier) {
281 tracker.startAugmentationNode(identifier);
282 context = new JSONStreamWriterInvisibleContext(context);
286 public final void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
287 // FIXME: should have a codec based on this :)
288 tracker.anyxmlNode(name);
290 context.emittingChild(codecs.getSchemaContext(), writer);
291 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
293 writeAnyXmlValue((DOMSource) value);
297 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
299 tracker.startYangModeledAnyXmlNode(name);
300 context = new JSONStreamWriterNamedObjectContext(context, name, true);
304 public final void endNode() throws IOException {
306 context = context.endNode(codecs.getSchemaContext(), writer);
308 if (context instanceof JSONStreamWriterRootContext) {
309 context.emitEnd(writer);
314 public final void flush() throws IOException {
318 final void closeWriter() throws IOException {
322 @SuppressWarnings("unchecked")
323 private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
324 ((JSONCodec<Object>) codec).writeValue(writer, value);
327 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
328 writeXmlNode(anyXmlValue.getNode());
331 private void writeXmlNode(final Node node) throws IOException {
332 if (isArrayElement(node)) {
333 writeArrayContent(node);
336 final Element firstChildElement = getFirstChildElement(node);
337 if (firstChildElement == null) {
340 writeObjectContent(firstChildElement);
344 private void writeArrayContent(final Node node) throws IOException {
350 private void writeObjectContent(final Element firstChildElement) throws IOException {
351 writer.beginObject();
352 writeObject(firstChildElement);
356 private static boolean isArrayElement(final Node node) {
357 if (ELEMENT_NODE == node.getNodeType()) {
358 final String nodeName = node.getNodeName();
359 for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
360 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
368 private void handleArray(final Node node) throws IOException {
369 final Element parentNode = (Element)node.getParentNode();
370 final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
371 for (int i = 0, length = elementsList.getLength(); i < length; i++) {
372 final Node arrayElement = elementsList.item(i);
373 final Element parent = (Element)arrayElement.getParentNode();
374 if (parentNode.isSameNode(parent)) {
375 final Element firstChildElement = getFirstChildElement(arrayElement);
376 if (firstChildElement != null) {
377 writeObjectContent(firstChildElement);
380 writeXmlValue(arrayElement);
386 private void writeObject(Node node) throws IOException {
387 String previousNodeName = "";
388 while (node != null) {
389 if (ELEMENT_NODE == node.getNodeType()) {
390 if (!node.getNodeName().equals(previousNodeName)) {
391 previousNodeName = node.getNodeName();
392 writer.name(node.getNodeName());
396 node = node.getNextSibling();
400 private void writeXmlValue(final Node node) throws IOException {
401 Text firstChild = getFirstChildText(node);
402 String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
403 childNodeText = childNodeText != null ? childNodeText.trim() : "";
405 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
406 writer.value(parseNumber(childNodeText));
409 switch (childNodeText) {
420 writer.value(childNodeText);
424 private static Element getFirstChildElement(final Node node) {
425 final NodeList children = node.getChildNodes();
426 for (int i = 0, length = children.getLength(); i < length; i++) {
427 final Node childNode = children.item(i);
428 if (ELEMENT_NODE == childNode.getNodeType()) {
429 return (Element) childNode;
435 private static Text getFirstChildText(final Node node) {
436 final NodeList children = node.getChildNodes();
437 for (int i = 0, length = children.getLength(); i < length; i++) {
438 final Node childNode = children.item(i);
439 if (TEXT_NODE == childNode.getNodeType()) {
440 return (Text) childNode;
446 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
447 private static Number parseNumber(final String numberText) {
448 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
449 return Long.valueOf(numberText);
452 return Double.valueOf(numberText);