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 com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12 import static org.w3c.dom.Node.ELEMENT_NODE;
13 import static org.w3c.dom.Node.TEXT_NODE;
15 import com.google.common.collect.ClassToInstanceMap;
16 import com.google.common.collect.ImmutableClassToInstanceMap;
17 import com.google.gson.stream.JsonWriter;
18 import java.io.IOException;
20 import java.util.regex.Pattern;
21 import javax.xml.transform.dom.DOMSource;
22 import org.checkerframework.checker.regex.qual.Regex;
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.YangInstanceIdentifier.NodeWithValue;
27 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedAnydata;
28 import org.opendaylight.yangtools.yang.data.api.schema.stream.AnydataExtension;
29 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriterExtension;
31 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
32 import org.opendaylight.yangtools.yang.data.util.SingleChildDataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.AnyDataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
37 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
39 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
40 import org.w3c.dom.Element;
41 import org.w3c.dom.Node;
42 import org.w3c.dom.NodeList;
43 import org.w3c.dom.Text;
46 * This implementation will create JSON output as output stream.
49 * Values of leaf and leaf-list are NOT translated according to codecs.
51 public abstract class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter, AnydataExtension {
52 private static final class Exclusive extends JSONNormalizedNodeStreamWriter {
53 Exclusive(final JSONCodecFactory codecFactory, final SchemaTracker tracker, final JsonWriter writer,
54 final JSONStreamWriterRootContext rootContext) {
55 super(codecFactory, tracker, writer, rootContext);
59 public void close() throws IOException {
65 private static final class Nested extends JSONNormalizedNodeStreamWriter {
66 Nested(final JSONCodecFactory codecFactory, final SchemaTracker tracker, final JsonWriter writer,
67 final JSONStreamWriterRootContext rootContext) {
68 super(codecFactory, tracker, writer, rootContext);
72 public void close() throws IOException {
74 // The caller "owns" the writer, let them close it
79 * RFC6020 deviation: we are not required to emit empty containers unless they
80 * are marked as 'presence'.
82 private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
85 private static final String NUMBER_STRING = "-?\\d+(\\.\\d+)?";
86 private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_STRING);
89 private static final String NOT_DECIMAL_NUMBER_STRING = "-?\\d+";
90 private static final Pattern NOT_DECIMAL_NUMBER_PATTERN = Pattern.compile(NOT_DECIMAL_NUMBER_STRING);
92 private final SchemaTracker tracker;
93 private final JSONCodecFactory codecs;
94 private final JsonWriter writer;
95 private JSONStreamWriterContext context;
97 JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaTracker tracker,
98 final JsonWriter writer, final JSONStreamWriterRootContext rootContext) {
99 this.writer = requireNonNull(writer);
100 this.codecs = requireNonNull(codecFactory);
101 this.tracker = requireNonNull(tracker);
102 this.context = requireNonNull(rootContext);
106 * Create a new stream writer, which writes to the specified output stream.
109 * The codec factory can be reused between multiple writers.
112 * Returned writer is exclusive user of JsonWriter, which means it will start
113 * top-level JSON element and ends it.
116 * This instance of writer can be used only to emit one top level element,
117 * otherwise it will produce incorrect JSON. Closing this instance will close
120 * @param codecFactory JSON codec factory
121 * @param path Schema Path
122 * @param initialNs Initial namespace
123 * @param jsonWriter JsonWriter
124 * @return A stream writer instance
126 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
127 final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
128 return new Exclusive(codecFactory, SchemaTracker.create(codecFactory.getSchemaContext(), path), jsonWriter,
129 new JSONStreamWriterExclusiveRootContext(initialNs));
133 * Create a new stream writer, which writes to the specified output stream.
136 * The codec factory can be reused between multiple writers.
139 * Returned writer is exclusive user of JsonWriter, which means it will start
140 * top-level JSON element and ends it.
143 * This instance of writer can be used only to emit one top level element,
144 * otherwise it will produce incorrect JSON. Closing this instance will close
147 * @param codecFactory JSON codec factory
148 * @param rootNode Root node
149 * @param initialNs Initial namespace
150 * @param jsonWriter JsonWriter
151 * @return A stream writer instance
153 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
154 final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
155 return new Exclusive(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
156 new JSONStreamWriterExclusiveRootContext(initialNs));
160 * Create a new stream writer, which writes to the specified output stream.
163 * The codec factory can be reused between multiple writers.
166 * Returned writer can be used emit multiple top level element,
167 * but does not start / close parent JSON object, which must be done
168 * by user providing {@code jsonWriter} instance in order for
169 * JSON to be valid. Closing this instance <strong>will not</strong>
170 * close the wrapped writer; the caller must take care of that.
172 * @param codecFactory JSON codec factory
173 * @param path Schema Path
174 * @param initialNs Initial namespace
175 * @param jsonWriter JsonWriter
176 * @return A stream writer instance
178 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
179 final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
180 return new Nested(codecFactory, SchemaTracker.create(codecFactory.getSchemaContext(), path), jsonWriter,
181 new JSONStreamWriterSharedRootContext(initialNs));
185 * Create a new stream writer, which writes to the specified output stream.
188 * The codec factory can be reused between multiple writers.
191 * Returned writer can be used emit multiple top level element,
192 * but does not start / close parent JSON object, which must be done
193 * by user providing {@code jsonWriter} instance in order for
194 * JSON to be valid. Closing this instance <strong>will not</strong>
195 * close the wrapped writer; the caller must take care of that.
197 * @param codecFactory JSON codec factory
198 * @param rootNode Root node
199 * @param initialNs Initial namespace
200 * @param jsonWriter JsonWriter
201 * @return A stream writer instance
203 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
204 final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
205 return new Nested(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
206 new JSONStreamWriterSharedRootContext(initialNs));
210 public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
211 return ImmutableClassToInstanceMap.of(AnydataExtension.class, this);
215 public void startLeafNode(final NodeIdentifier name) throws IOException {
216 tracker.startLeafNode(name);
217 context.emittingChild(codecs.getSchemaContext(), writer);
218 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
222 public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
223 tracker.startLeafSet(name);
224 context = new JSONStreamWriterListContext(context, name);
228 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
229 tracker.startLeafSetEntryNode(name);
230 context.emittingChild(codecs.getSchemaContext(), writer);
234 public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
235 tracker.startLeafSet(name);
236 context = new JSONStreamWriterListContext(context, name);
240 * Warning suppressed due to static final constant which triggers a warning
241 * for the call to schema.isPresenceContainer().
244 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
245 final SchemaNode schema = tracker.startContainerNode(name);
246 final boolean isPresence = schema instanceof ContainerSchemaNode
247 ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
248 context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
252 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
253 tracker.startList(name);
254 context = new JSONStreamWriterListContext(context, name);
258 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
259 tracker.startListItem(name);
260 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
264 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
265 tracker.startList(name);
266 context = new JSONStreamWriterListContext(context, name);
270 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
272 tracker.startListItem(identifier);
273 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
277 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
278 tracker.startList(name);
279 context = new JSONStreamWriterListContext(context, name);
283 public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
284 tracker.startChoiceNode(name);
285 context = new JSONStreamWriterInvisibleContext(context);
289 public final void startAugmentationNode(final AugmentationIdentifier identifier) {
290 tracker.startAugmentationNode(identifier);
291 context = new JSONStreamWriterInvisibleContext(context);
295 public boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
296 if (NormalizedAnydata.class.isAssignableFrom(objectModel)) {
297 tracker.startAnydataNode(name);
298 context.emittingChild(codecs.getSchemaContext(), writer);
299 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
307 public final void startAnyxmlNode(final NodeIdentifier name) throws IOException {
308 tracker.startAnyxmlNode(name);
309 context.emittingChild(codecs.getSchemaContext(), writer);
310 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
314 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
316 tracker.startYangModeledAnyXmlNode(name);
317 context = new JSONStreamWriterNamedObjectContext(context, name, true);
321 public final void endNode() throws IOException {
323 context = context.endNode(codecs.getSchemaContext(), writer);
325 if (context instanceof JSONStreamWriterRootContext) {
326 context.emitEnd(writer);
331 public final void flush() throws IOException {
335 final void closeWriter() throws IOException {
340 public void scalarValue(final Object value) throws IOException {
341 final Object current = tracker.getParent();
342 if (current instanceof TypedDataSchemaNode) {
343 writeValue(value, codecs.codecFor((TypedDataSchemaNode) current));
344 } else if (current instanceof AnyDataSchemaNode) {
345 writeAnydataValue(value);
347 throw new IllegalStateException(String.format("Cannot emit scalar %s for %s", value, current));
352 public void domSourceValue(final DOMSource value) throws IOException {
353 final Object current = tracker.getParent();
354 checkState(current instanceof AnyXmlSchemaNode, "Cannot emit DOMSource %s for %s", value, current);
355 // FIXME: should have a codec based on this :)
356 writeAnyXmlValue(value);
359 @SuppressWarnings("unchecked")
360 private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
361 ((JSONCodec<Object>) codec).writeValue(writer, value);
364 private void writeAnydataValue(final Object value) throws IOException {
365 if (value instanceof NormalizedAnydata) {
366 writeNormalizedAnydata((NormalizedAnydata) value);
368 throw new IllegalStateException("Unexpected anydata value " + value);
372 private void writeNormalizedAnydata(final NormalizedAnydata anydata) throws IOException {
373 anydata.writeTo(JSONNormalizedNodeStreamWriter.createNestedWriter(codecs.rebaseTo(anydata.getSchemaContext()),
374 new SingleChildDataNodeContainer(anydata.getContextNode()), context.getNamespace(), writer));
377 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
378 writeXmlNode(anyXmlValue.getNode());
381 private void writeXmlNode(final Node node) throws IOException {
382 if (isArrayElement(node)) {
383 writeArrayContent(node);
386 final Element firstChildElement = getFirstChildElement(node);
387 if (firstChildElement == null) {
390 writeObjectContent(firstChildElement);
394 private void writeArrayContent(final Node node) throws IOException {
400 private void writeObjectContent(final Element firstChildElement) throws IOException {
401 writer.beginObject();
402 writeObject(firstChildElement);
406 private static boolean isArrayElement(final Node node) {
407 if (ELEMENT_NODE == node.getNodeType()) {
408 final String nodeName = node.getNodeName();
409 for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
410 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
418 private void handleArray(final Node node) throws IOException {
419 final Element parentNode = (Element)node.getParentNode();
420 final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
421 for (int i = 0, length = elementsList.getLength(); i < length; i++) {
422 final Node arrayElement = elementsList.item(i);
423 final Element parent = (Element)arrayElement.getParentNode();
424 if (parentNode.isSameNode(parent)) {
425 final Element firstChildElement = getFirstChildElement(arrayElement);
426 if (firstChildElement != null) {
427 writeObjectContent(firstChildElement);
430 writeXmlValue(arrayElement);
436 private void writeObject(Node node) throws IOException {
437 String previousNodeName = "";
438 while (node != null) {
439 if (ELEMENT_NODE == node.getNodeType()) {
440 if (!node.getNodeName().equals(previousNodeName)) {
441 previousNodeName = node.getNodeName();
442 writer.name(node.getNodeName());
446 node = node.getNextSibling();
450 private void writeXmlValue(final Node node) throws IOException {
451 Text firstChild = getFirstChildText(node);
452 String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
453 childNodeText = childNodeText != null ? childNodeText.trim() : "";
455 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
456 writer.value(parseNumber(childNodeText));
459 switch (childNodeText) {
470 writer.value(childNodeText);
474 private static Element getFirstChildElement(final Node node) {
475 final NodeList children = node.getChildNodes();
476 for (int i = 0, length = children.getLength(); i < length; i++) {
477 final Node childNode = children.item(i);
478 if (ELEMENT_NODE == childNode.getNodeType()) {
479 return (Element) childNode;
485 private static Text getFirstChildText(final Node node) {
486 final NodeList children = node.getChildNodes();
487 for (int i = 0, length = children.getLength(); i < length; i++) {
488 final Node childNode = children.item(i);
489 if (TEXT_NODE == childNode.getNodeType()) {
490 return (Text) childNode;
496 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
497 private static Number parseNumber(final String numberText) {
498 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
499 return Long.valueOf(numberText);
502 return Double.valueOf(numberText);