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.rfc8528.data.api.MountPointContext;
24 import org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier;
25 import org.opendaylight.yangtools.rfc8528.data.api.StreamWriterMountPointExtension;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedAnydata;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriterExtension;
33 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
34 import org.opendaylight.yangtools.yang.data.util.SingleChildDataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
43 import org.w3c.dom.Element;
44 import org.w3c.dom.Node;
45 import org.w3c.dom.NodeList;
46 import org.w3c.dom.Text;
49 * This implementation will create JSON output as output stream.
52 * Values of leaf and leaf-list are NOT translated according to codecs.
54 public abstract class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter,
55 StreamWriterMountPointExtension {
56 private static final class Exclusive extends JSONNormalizedNodeStreamWriter {
57 Exclusive(final JSONCodecFactory codecFactory, final SchemaTracker tracker, final JsonWriter writer,
58 final JSONStreamWriterRootContext rootContext) {
59 super(codecFactory, tracker, writer, rootContext);
63 public void close() throws IOException {
69 private static final class Nested extends JSONNormalizedNodeStreamWriter {
70 Nested(final JSONCodecFactory codecFactory, final SchemaTracker tracker, final JsonWriter writer,
71 final JSONStreamWriterRootContext rootContext) {
72 super(codecFactory, tracker, writer, rootContext);
76 public void close() throws IOException {
78 // The caller "owns" the writer, let them close it
83 * RFC6020 deviation: we are not required to emit empty containers unless they
84 * are marked as 'presence'.
86 private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
89 private static final String NUMBER_STRING = "-?\\d+(\\.\\d+)?";
90 private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_STRING);
93 private static final String NOT_DECIMAL_NUMBER_STRING = "-?\\d+";
94 private static final Pattern NOT_DECIMAL_NUMBER_PATTERN = Pattern.compile(NOT_DECIMAL_NUMBER_STRING);
96 private final SchemaTracker tracker;
97 private final JSONCodecFactory codecs;
98 private final JsonWriter writer;
99 private JSONStreamWriterContext context;
101 JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaTracker tracker,
102 final JsonWriter writer, final JSONStreamWriterRootContext rootContext) {
103 this.writer = requireNonNull(writer);
104 this.codecs = requireNonNull(codecFactory);
105 this.tracker = requireNonNull(tracker);
106 this.context = requireNonNull(rootContext);
110 * Create a new stream writer, which writes to the specified output stream.
113 * The codec factory can be reused between multiple writers.
116 * Returned writer is exclusive user of JsonWriter, which means it will start
117 * top-level JSON element and ends it.
120 * This instance of writer can be used only to emit one top level element,
121 * otherwise it will produce incorrect JSON. Closing this instance will close
124 * @param codecFactory JSON codec factory
125 * @param path Schema Path
126 * @param initialNs Initial namespace
127 * @param jsonWriter JsonWriter
128 * @return A stream writer instance
130 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
131 final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
132 return new Exclusive(codecFactory, SchemaTracker.create(codecFactory.getSchemaContext(), path), jsonWriter,
133 new JSONStreamWriterExclusiveRootContext(initialNs));
137 * Create a new stream writer, which writes to the specified output stream.
140 * The codec factory can be reused between multiple writers.
143 * Returned writer is exclusive user of JsonWriter, which means it will start
144 * top-level JSON element and ends it.
147 * This instance of writer can be used only to emit one top level element,
148 * otherwise it will produce incorrect JSON. Closing this instance will close
151 * @param codecFactory JSON codec factory
152 * @param rootNode Root node
153 * @param initialNs Initial namespace
154 * @param jsonWriter JsonWriter
155 * @return A stream writer instance
157 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
158 final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
159 return new Exclusive(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
160 new JSONStreamWriterExclusiveRootContext(initialNs));
164 * Create a new stream writer, which writes to the specified output stream.
167 * The codec factory can be reused between multiple writers.
170 * Returned writer can be used emit multiple top level element,
171 * but does not start / close parent JSON object, which must be done
172 * by user providing {@code jsonWriter} instance in order for
173 * JSON to be valid. Closing this instance <strong>will not</strong>
174 * close the wrapped writer; the caller must take care of that.
176 * @param codecFactory JSON codec factory
177 * @param path Schema Path
178 * @param initialNs Initial namespace
179 * @param jsonWriter JsonWriter
180 * @return A stream writer instance
182 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
183 final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
184 return new Nested(codecFactory, SchemaTracker.create(codecFactory.getSchemaContext(), path), jsonWriter,
185 new JSONStreamWriterSharedRootContext(initialNs));
189 * Create a new stream writer, which writes to the specified output stream.
192 * The codec factory can be reused between multiple writers.
195 * Returned writer can be used emit multiple top level element,
196 * but does not start / close parent JSON object, which must be done
197 * by user providing {@code jsonWriter} instance in order for
198 * JSON to be valid. Closing this instance <strong>will not</strong>
199 * close the wrapped writer; the caller must take care of that.
201 * @param codecFactory JSON codec factory
202 * @param rootNode Root node
203 * @param initialNs Initial namespace
204 * @param jsonWriter JsonWriter
205 * @return A stream writer instance
207 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
208 final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
209 return new Nested(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
210 new JSONStreamWriterSharedRootContext(initialNs));
214 public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
215 return ImmutableClassToInstanceMap.of(StreamWriterMountPointExtension.class, this);
219 public void startLeafNode(final NodeIdentifier name) throws IOException {
220 tracker.startLeafNode(name);
221 context.emittingChild(codecs.getSchemaContext(), writer);
222 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
226 public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
227 tracker.startLeafSet(name);
228 context = new JSONStreamWriterListContext(context, name);
232 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
233 tracker.startLeafSetEntryNode(name);
234 context.emittingChild(codecs.getSchemaContext(), writer);
238 public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
239 tracker.startLeafSet(name);
240 context = new JSONStreamWriterListContext(context, name);
244 * Warning suppressed due to static final constant which triggers a warning
245 * for the call to schema.isPresenceContainer().
248 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
249 final SchemaNode schema = tracker.startContainerNode(name);
250 final boolean isPresence = schema instanceof ContainerSchemaNode
251 ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
252 context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
256 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
257 tracker.startList(name);
258 context = new JSONStreamWriterListContext(context, name);
262 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
263 tracker.startListItem(name);
264 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
268 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
269 tracker.startList(name);
270 context = new JSONStreamWriterListContext(context, name);
274 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
276 tracker.startListItem(identifier);
277 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
281 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
282 tracker.startList(name);
283 context = new JSONStreamWriterListContext(context, name);
287 public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
288 tracker.startChoiceNode(name);
289 context = new JSONStreamWriterInvisibleContext(context);
293 public final void startAugmentationNode(final AugmentationIdentifier identifier) {
294 tracker.startAugmentationNode(identifier);
295 context = new JSONStreamWriterInvisibleContext(context);
299 public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
300 if (NormalizedAnydata.class.isAssignableFrom(objectModel)) {
301 tracker.startAnydataNode(name);
302 context.emittingChild(codecs.getSchemaContext(), writer);
303 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
311 public final NormalizedNodeStreamWriter startMountPoint(final MountPointIdentifier mountId,
312 final MountPointContext mountCtx) throws IOException {
313 final SchemaContext ctx = mountCtx.getSchemaContext();
314 return new Nested(codecs.rebaseTo(ctx), SchemaTracker.create(ctx), writer,
315 new JSONStreamWriterSharedRootContext(context.getNamespace()));
319 public final void startAnyxmlNode(final NodeIdentifier name) throws IOException {
320 tracker.startAnyxmlNode(name);
321 context.emittingChild(codecs.getSchemaContext(), writer);
322 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
326 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
328 tracker.startYangModeledAnyXmlNode(name);
329 context = new JSONStreamWriterNamedObjectContext(context, name, true);
333 public final void endNode() throws IOException {
335 context = context.endNode(codecs.getSchemaContext(), writer);
337 if (context instanceof JSONStreamWriterRootContext) {
338 context.endNode(codecs.getSchemaContext(), writer);
343 public final void flush() throws IOException {
347 final void closeWriter() throws IOException {
352 public void scalarValue(final Object value) throws IOException {
353 final Object current = tracker.getParent();
354 if (current instanceof TypedDataSchemaNode) {
355 writeValue(value, codecs.codecFor((TypedDataSchemaNode) current));
356 } else if (current instanceof AnydataSchemaNode) {
357 writeAnydataValue(value);
359 throw new IllegalStateException(String.format("Cannot emit scalar %s for %s", value, current));
364 public void domSourceValue(final DOMSource value) throws IOException {
365 final Object current = tracker.getParent();
366 checkState(current instanceof AnyxmlSchemaNode, "Cannot emit DOMSource %s for %s", value, current);
367 // FIXME: should have a codec based on this :)
368 writeAnyXmlValue(value);
371 @SuppressWarnings("unchecked")
372 private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
373 ((JSONCodec<Object>) codec).writeValue(writer, value);
376 private void writeAnydataValue(final Object value) throws IOException {
377 if (value instanceof NormalizedAnydata) {
378 writeNormalizedAnydata((NormalizedAnydata) value);
380 throw new IllegalStateException("Unexpected anydata value " + value);
384 private void writeNormalizedAnydata(final NormalizedAnydata anydata) throws IOException {
385 anydata.writeTo(JSONNormalizedNodeStreamWriter.createNestedWriter(codecs.rebaseTo(anydata.getSchemaContext()),
386 new SingleChildDataNodeContainer(anydata.getContextNode()), context.getNamespace(), writer));
389 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
390 writeXmlNode(anyXmlValue.getNode());
393 private void writeXmlNode(final Node node) throws IOException {
394 if (isArrayElement(node)) {
395 writeArrayContent(node);
398 final Element firstChildElement = getFirstChildElement(node);
399 if (firstChildElement == null) {
402 writeObjectContent(firstChildElement);
406 private void writeArrayContent(final Node node) throws IOException {
412 private void writeObjectContent(final Element firstChildElement) throws IOException {
413 writer.beginObject();
414 writeObject(firstChildElement);
418 private static boolean isArrayElement(final Node node) {
419 if (ELEMENT_NODE == node.getNodeType()) {
420 final String nodeName = node.getNodeName();
421 for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
422 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
430 private void handleArray(final Node node) throws IOException {
431 final Element parentNode = (Element)node.getParentNode();
432 final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
433 for (int i = 0, length = elementsList.getLength(); i < length; i++) {
434 final Node arrayElement = elementsList.item(i);
435 final Element parent = (Element)arrayElement.getParentNode();
436 if (parentNode.isSameNode(parent)) {
437 final Element firstChildElement = getFirstChildElement(arrayElement);
438 if (firstChildElement != null) {
439 writeObjectContent(firstChildElement);
442 writeXmlValue(arrayElement);
448 private void writeObject(Node node) throws IOException {
449 String previousNodeName = "";
450 while (node != null) {
451 if (ELEMENT_NODE == node.getNodeType()) {
452 if (!node.getNodeName().equals(previousNodeName)) {
453 previousNodeName = node.getNodeName();
454 writer.name(node.getNodeName());
458 node = node.getNextSibling();
462 private void writeXmlValue(final Node node) throws IOException {
463 Text firstChild = getFirstChildText(node);
464 String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
465 childNodeText = childNodeText != null ? childNodeText.trim() : "";
467 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
468 writer.value(parseNumber(childNodeText));
471 switch (childNodeText) {
482 writer.value(childNodeText);
486 private static Element getFirstChildElement(final Node node) {
487 final NodeList children = node.getChildNodes();
488 for (int i = 0, length = children.getLength(); i < length; i++) {
489 final Node childNode = children.item(i);
490 if (ELEMENT_NODE == childNode.getNodeType()) {
491 return (Element) childNode;
497 private static Text getFirstChildText(final Node node) {
498 final NodeList children = node.getChildNodes();
499 for (int i = 0, length = children.getLength(); i < length; i++) {
500 final Node childNode = children.item(i);
501 if (TEXT_NODE == childNode.getNodeType()) {
502 return (Text) childNode;
508 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
509 private static Number parseNumber(final String numberText) {
510 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
511 return Long.valueOf(numberText);
514 return Double.valueOf(numberText);