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 org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream.ANYXML_ARRAY_ELEMENT_ID;
11 import static org.w3c.dom.Node.ELEMENT_NODE;
12 import static org.w3c.dom.Node.TEXT_NODE;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Throwables;
16 import com.google.gson.stream.JsonWriter;
17 import java.io.IOException;
19 import java.util.regex.Pattern;
20 import javax.annotation.RegEx;
21 import javax.xml.transform.dom.DOMSource;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
26 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
27 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
28 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
33 import org.w3c.dom.Node;
34 import org.w3c.dom.NodeList;
37 * This implementation will create JSON output as output stream.
39 * Values of leaf and leaf-list are NOT translated according to codecs.
42 public final class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
44 * RFC6020 deviation: we are not required to emit empty containers unless they
45 * are marked as 'presence'.
47 private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
50 private static final String NUMBER_STRING = "-?\\d+(\\.\\d+)?";
51 private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_STRING);
54 private static final String NOT_DECIMAL_NUMBER_STRING = "-?\\d+";
55 private static final Pattern NOT_DECIMAL_NUMBER_PATTERN = Pattern.compile(NOT_DECIMAL_NUMBER_STRING);
57 private final SchemaTracker tracker;
58 private final JSONCodecFactory codecs;
59 private final JsonWriter writer;
60 private JSONStreamWriterContext context;
62 private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path, final JsonWriter JsonWriter, final JSONStreamWriterRootContext rootContext) {
63 this.writer = Preconditions.checkNotNull(JsonWriter);
64 this.codecs = Preconditions.checkNotNull(codecFactory);
65 this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
66 this.context = Preconditions.checkNotNull(rootContext);
70 * Create a new stream writer, which writes to the specified output stream.
72 * The codec factory can be reused between multiple writers.
74 * Returned writer is exclusive user of JsonWriter, which means it will start
75 * top-level JSON element and ends it.
77 * This instance of writer can be used only to emit one top level element,
78 * otherwise it will produce incorrect JSON.
80 * @param codecFactory JSON codec factory
81 * @param path Schema Path
82 * @param initialNs Initial namespace
83 * @param jsonWriter JsonWriter
84 * @return A stream writer instance
86 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory, final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
87 return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
91 * Create a new stream writer, which writes to the specified output stream.
93 * The codec factory can be reused between multiple writers.
95 * Returned writer can be used emit multiple top level element,
96 * but does not start / close parent JSON object, which must be done
97 * by user providing {@code jsonWriter} instance in order for
100 * @param codecFactory JSON codec factory
101 * @param path Schema Path
102 * @param initialNs Initial namespace
103 * @param jsonWriter JsonWriter
104 * @return A stream writer instance
106 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory, final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
107 return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
111 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
112 final LeafSchemaNode schema = tracker.leafNode(name);
113 final JSONCodec<?> codec = codecs.codecFor(schema);
114 context.emittingChild(codecs.getSchemaContext(), writer);
115 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
116 writeValue(value, codec);
120 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
121 tracker.startLeafSet(name);
122 context = new JSONStreamWriterListContext(context, name);
126 public void leafSetEntryNode(final QName name, final Object value) throws IOException {
127 final LeafListSchemaNode schema = tracker.leafSetEntryNode(name);
128 final JSONCodec<?> codec = codecs.codecFor(schema);
129 context.emittingChild(codecs.getSchemaContext(), writer);
130 writeValue(value, codec);
134 public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
135 tracker.startLeafSet(name);
136 context = new JSONStreamWriterListContext(context, name);
140 * Warning suppressed due to static final constant which triggers a warning
141 * for the call to schema.isPresenceContainer().
143 @SuppressWarnings("unused")
145 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
146 final SchemaNode schema = tracker.startContainerNode(name);
148 // FIXME this code ignores presence for containers
149 // but datastore does as well and it needs be fixed first (2399)
150 context = new JSONStreamWriterNamedObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
154 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
155 tracker.startList(name);
156 context = new JSONStreamWriterListContext(context, name);
160 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
161 tracker.startListItem(name);
162 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
166 public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
167 tracker.startList(name);
168 context = new JSONStreamWriterListContext(context, name);
172 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
174 tracker.startListItem(identifier);
175 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
179 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
180 tracker.startList(name);
181 context = new JSONStreamWriterListContext(context, name);
185 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
186 tracker.startChoiceNode(name);
187 context = new JSONStreamWriterInvisibleContext(context);
191 public void startAugmentationNode(final AugmentationIdentifier identifier) {
192 tracker.startAugmentationNode(identifier);
193 context = new JSONStreamWriterInvisibleContext(context);
197 public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
198 @SuppressWarnings("unused")
199 final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
200 // FIXME: should have a codec based on this :)
202 context.emittingChild(codecs.getSchemaContext(), writer);
203 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
205 writeAnyXmlValue((DOMSource) value);
209 public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
210 tracker.startYangModeledAnyXmlNode(name);
211 context = new JSONStreamWriterNamedObjectContext(context, name, true);
215 public void endNode() throws IOException {
217 context = context.endNode(codecs.getSchemaContext(), writer);
219 if (context instanceof JSONStreamWriterRootContext) {
220 context.emitEnd(writer);
224 @SuppressWarnings("unchecked")
225 private void writeValue(final Object value, final JSONCodec<?> codec)
228 ((JSONCodec<Object>) codec).writeValue(writer, value);
229 } catch (IOException e) {
231 } catch (Exception e) {
232 Throwables.propagateIfPossible(e);
233 throw new RuntimeException(e);
237 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
238 final Node documentNode = anyXmlValue.getNode();
239 final Node firstChild = documentNode.getFirstChild();
240 if (ELEMENT_NODE == firstChild.getNodeType() && !ANYXML_ARRAY_ELEMENT_ID.equals(firstChild.getNodeName())) {
241 writer.beginObject();
242 traverseAnyXmlValue(documentNode);
245 traverseAnyXmlValue(documentNode);
249 private void traverseAnyXmlValue(final Node node) throws IOException {
250 final NodeList children = node.getChildNodes();
251 boolean inArray = false;
253 for (int i = 0, length = children.getLength(); i < length; i++) {
254 final Node childNode = children.item(i);
255 boolean inObject = false;
257 if (ELEMENT_NODE == childNode.getNodeType()) {
258 final Node firstChild = childNode.getFirstChild();
259 // beginning of an array
260 if (ANYXML_ARRAY_ELEMENT_ID.equals(childNode.getNodeName()) && !inArray) {
263 // object at the beginning of the array
264 if (isJsonObjectInArray(childNode, firstChild)) {
265 writer.beginObject();
268 // object in the array
269 } else if (isJsonObjectInArray(childNode, firstChild)) {
270 writer.beginObject();
273 } else if (isJsonObject(firstChild)) {
274 writer.name(childNode.getNodeName());
275 writer.beginObject();
278 } else if (!inArray){
279 writer.name(childNode.getNodeName());
283 // text value, i.e. a number, string, boolean or null
284 if (TEXT_NODE == childNode.getNodeType()) {
285 final String childNodeText = childNode.getNodeValue();
286 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
287 writer.value(parseNumber(childNodeText));
288 } else if ("true".equals(childNodeText) || "false".equals(childNodeText)) {
289 writer.value(Boolean.parseBoolean(childNodeText));
290 } else if ("null".equals(childNodeText)) {
293 writer.value(childNodeText);
299 traverseAnyXmlValue(childNode);
311 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
312 private static Number parseNumber(final String numberText) {
313 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
314 return Long.valueOf(numberText);
317 return Double.valueOf(numberText);
320 private static boolean isJsonObject(final Node firstChild) {
321 return !ANYXML_ARRAY_ELEMENT_ID.equals(firstChild.getNodeName()) && TEXT_NODE != firstChild.getNodeType();
324 private static boolean isJsonObjectInArray(final Node node, final Node firstChild) {
325 return ANYXML_ARRAY_ELEMENT_ID.equals(node.getNodeName())
326 && !ANYXML_ARRAY_ELEMENT_ID.equals(firstChild.getNodeName())
327 && TEXT_NODE != firstChild.getNodeType();
331 public void flush() throws IOException {
336 public void close() throws IOException {