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.xml.transform.dom.DOMSource;
19 import org.checkerframework.checker.regex.qual.Regex;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
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.AnyXmlSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
31 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
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 void startLeafNode(final NodeIdentifier name) throws IOException {
203 tracker.startLeafNode(name);
204 context.emittingChild(codecs.getSchemaContext(), writer);
205 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
209 public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
210 tracker.startLeafSet(name);
211 context = new JSONStreamWriterListContext(context, name);
215 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
216 tracker.startLeafSetEntryNode(name);
217 context.emittingChild(codecs.getSchemaContext(), writer);
221 public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
222 tracker.startLeafSet(name);
223 context = new JSONStreamWriterListContext(context, name);
227 * Warning suppressed due to static final constant which triggers a warning
228 * for the call to schema.isPresenceContainer().
231 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
232 final SchemaNode schema = tracker.startContainerNode(name);
233 final boolean isPresence = schema instanceof ContainerSchemaNode
234 ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
235 context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
239 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
240 tracker.startList(name);
241 context = new JSONStreamWriterListContext(context, name);
245 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
246 tracker.startListItem(name);
247 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
251 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
252 tracker.startList(name);
253 context = new JSONStreamWriterListContext(context, name);
257 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
259 tracker.startListItem(identifier);
260 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
264 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
265 tracker.startList(name);
266 context = new JSONStreamWriterListContext(context, name);
270 public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
271 tracker.startChoiceNode(name);
272 context = new JSONStreamWriterInvisibleContext(context);
276 public final void startAugmentationNode(final AugmentationIdentifier identifier) {
277 tracker.startAugmentationNode(identifier);
278 context = new JSONStreamWriterInvisibleContext(context);
282 public final void startAnyxmlNode(final NodeIdentifier name) throws IOException {
283 tracker.startAnyxmlNode(name);
284 context.emittingChild(codecs.getSchemaContext(), writer);
285 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
289 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
291 tracker.startYangModeledAnyXmlNode(name);
292 context = new JSONStreamWriterNamedObjectContext(context, name, true);
296 public final void endNode() throws IOException {
298 context = context.endNode(codecs.getSchemaContext(), writer);
300 if (context instanceof JSONStreamWriterRootContext) {
301 context.emitEnd(writer);
306 public final void flush() throws IOException {
310 final void closeWriter() throws IOException {
315 public void nodeValue(final Object value) throws IOException {
316 final Object current = tracker.getParent();
317 if (current instanceof TypedDataSchemaNode) {
318 final JSONCodec<?> codec = codecs.codecFor((TypedDataSchemaNode) current);
319 writeValue(value, codec);
320 } else if (current instanceof AnyXmlSchemaNode) {
321 // FIXME: should have a codec based on this :)
322 writeAnyXmlValue((DOMSource) value);
324 throw new IllegalStateException("Cannot emit scalar for " + current);
328 @SuppressWarnings("unchecked")
329 private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
330 ((JSONCodec<Object>) codec).writeValue(writer, value);
333 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
334 writeXmlNode(anyXmlValue.getNode());
337 private void writeXmlNode(final Node node) throws IOException {
338 if (isArrayElement(node)) {
339 writeArrayContent(node);
342 final Element firstChildElement = getFirstChildElement(node);
343 if (firstChildElement == null) {
346 writeObjectContent(firstChildElement);
350 private void writeArrayContent(final Node node) throws IOException {
356 private void writeObjectContent(final Element firstChildElement) throws IOException {
357 writer.beginObject();
358 writeObject(firstChildElement);
362 private static boolean isArrayElement(final Node node) {
363 if (ELEMENT_NODE == node.getNodeType()) {
364 final String nodeName = node.getNodeName();
365 for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
366 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
374 private void handleArray(final Node node) throws IOException {
375 final Element parentNode = (Element)node.getParentNode();
376 final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
377 for (int i = 0, length = elementsList.getLength(); i < length; i++) {
378 final Node arrayElement = elementsList.item(i);
379 final Element parent = (Element)arrayElement.getParentNode();
380 if (parentNode.isSameNode(parent)) {
381 final Element firstChildElement = getFirstChildElement(arrayElement);
382 if (firstChildElement != null) {
383 writeObjectContent(firstChildElement);
386 writeXmlValue(arrayElement);
392 private void writeObject(Node node) throws IOException {
393 String previousNodeName = "";
394 while (node != null) {
395 if (ELEMENT_NODE == node.getNodeType()) {
396 if (!node.getNodeName().equals(previousNodeName)) {
397 previousNodeName = node.getNodeName();
398 writer.name(node.getNodeName());
402 node = node.getNextSibling();
406 private void writeXmlValue(final Node node) throws IOException {
407 Text firstChild = getFirstChildText(node);
408 String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
409 childNodeText = childNodeText != null ? childNodeText.trim() : "";
411 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
412 writer.value(parseNumber(childNodeText));
415 switch (childNodeText) {
426 writer.value(childNodeText);
430 private static Element getFirstChildElement(final Node node) {
431 final NodeList children = node.getChildNodes();
432 for (int i = 0, length = children.getLength(); i < length; i++) {
433 final Node childNode = children.item(i);
434 if (ELEMENT_NODE == childNode.getNodeType()) {
435 return (Element) childNode;
441 private static Text getFirstChildText(final Node node) {
442 final NodeList children = node.getChildNodes();
443 for (int i = 0, length = children.getLength(); i < length; i++) {
444 final Node childNode = children.item(i);
445 if (TEXT_NODE == childNode.getNodeType()) {
446 return (Text) childNode;
452 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
453 private static Number parseNumber(final String numberText) {
454 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
455 return Long.valueOf(numberText);
458 return Double.valueOf(numberText);