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;
19 import java.util.regex.Pattern;
20 import javax.xml.transform.dom.DOMSource;
21 import org.checkerframework.checker.regex.qual.Regex;
22 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
23 import org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier;
24 import org.opendaylight.yangtools.rfc8528.data.api.StreamWriterMountPointExtension;
25 import org.opendaylight.yangtools.yang.common.XMLNamespace;
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.EffectiveModelContext;
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.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
44 import org.w3c.dom.Element;
45 import org.w3c.dom.Node;
46 import org.w3c.dom.NodeList;
47 import org.w3c.dom.Text;
50 * This implementation will create JSON output as output stream.
53 * Values of leaf and leaf-list are NOT translated according to codecs.
55 public abstract class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter,
56 StreamWriterMountPointExtension {
57 private static final class Exclusive extends JSONNormalizedNodeStreamWriter {
58 Exclusive(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 {
70 private static final class Nested extends JSONNormalizedNodeStreamWriter {
71 Nested(final JSONCodecFactory codecFactory, final SchemaTracker tracker, final JsonWriter writer,
72 final JSONStreamWriterRootContext rootContext) {
73 super(codecFactory, tracker, writer, rootContext);
77 public void close() throws IOException {
79 // The caller "owns" the writer, let them close it
84 * RFC6020 deviation: we are not required to emit empty containers unless they
85 * are marked as 'presence'.
87 private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
90 private static final String NUMBER_STRING = "-?\\d+(\\.\\d+)?";
91 private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_STRING);
94 private static final String NOT_DECIMAL_NUMBER_STRING = "-?\\d+";
95 private static final Pattern NOT_DECIMAL_NUMBER_PATTERN = Pattern.compile(NOT_DECIMAL_NUMBER_STRING);
97 private final SchemaTracker tracker;
98 private final JSONCodecFactory codecs;
99 private final JsonWriter writer;
100 private JSONStreamWriterContext context;
102 JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaTracker tracker,
103 final JsonWriter writer, final JSONStreamWriterRootContext rootContext) {
104 this.writer = requireNonNull(writer);
105 this.codecs = requireNonNull(codecFactory);
106 this.tracker = requireNonNull(tracker);
107 this.context = requireNonNull(rootContext);
111 * Create a new stream writer, which writes to the specified output stream.
114 * The codec factory can be reused between multiple writers.
117 * Returned writer is exclusive user of JsonWriter, which means it will start
118 * top-level JSON element and ends it.
121 * This instance of writer can be used only to emit one top level element,
122 * otherwise it will produce incorrect JSON. Closing this instance will close
125 * @param codecFactory JSON codec factory
126 * @param path Schema Path
127 * @param initialNs Initial namespace
128 * @param jsonWriter JsonWriter
129 * @return A stream writer instance
131 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
132 final SchemaPath path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
133 return new Exclusive(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path),
134 jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
138 * Create a new stream writer, which writes to the specified output stream.
141 * The codec factory can be reused between multiple writers.
144 * Returned writer is exclusive user of JsonWriter, which means it will start
145 * top-level JSON element and ends it.
148 * This instance of writer can be used only to emit one top level element,
149 * otherwise it will produce incorrect JSON. Closing this instance will close
152 * @param codecFactory JSON codec factory
153 * @param path Schema Path
154 * @param initialNs Initial namespace
155 * @param jsonWriter JsonWriter
156 * @return A stream writer instance
158 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
159 final Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
160 return new Exclusive(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path),
161 jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
165 * Create a new stream writer, which writes to the specified output stream.
168 * The codec factory can be reused between multiple writers.
171 * Returned writer is exclusive user of JsonWriter, which means it will start
172 * top-level JSON element and ends it.
175 * This instance of writer can be used only to emit one top level element,
176 * otherwise it will produce incorrect JSON. Closing this instance will close
179 * @param codecFactory JSON codec factory
180 * @param rootNode Root node
181 * @param initialNs Initial namespace
182 * @param jsonWriter JsonWriter
183 * @return A stream writer instance
185 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
186 final DataNodeContainer rootNode, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
187 return new Exclusive(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
188 new JSONStreamWriterExclusiveRootContext(initialNs));
192 * Create a new stream writer, which writes to the specified output stream.
195 * The codec factory can be reused between multiple writers.
198 * Returned writer can be used emit multiple top level element,
199 * but does not start / close parent JSON object, which must be done
200 * by user providing {@code jsonWriter} instance in order for
201 * JSON to be valid. Closing this instance <strong>will not</strong>
202 * close the wrapped writer; the caller must take care of that.
204 * @param codecFactory JSON codec factory
205 * @param path Schema Path
206 * @param initialNs Initial namespace
207 * @param jsonWriter JsonWriter
208 * @return A stream writer instance
210 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
211 final SchemaPath path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
212 return new Nested(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path), jsonWriter,
213 new JSONStreamWriterSharedRootContext(initialNs));
217 * Create a new stream writer, which writes to the specified output stream.
220 * The codec factory can be reused between multiple writers.
223 * Returned writer can be used emit multiple top level element,
224 * but does not start / close parent JSON object, which must be done
225 * by user providing {@code jsonWriter} instance in order for
226 * JSON to be valid. Closing this instance <strong>will not</strong>
227 * close the wrapped writer; the caller must take care of that.
229 * @param codecFactory JSON codec factory
230 * @param path Schema Path
231 * @param initialNs Initial namespace
232 * @param jsonWriter JsonWriter
233 * @return A stream writer instance
235 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
236 final Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
237 return new Nested(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path), jsonWriter,
238 new JSONStreamWriterSharedRootContext(initialNs));
242 * Create a new stream writer, which writes to the specified output stream.
245 * The codec factory can be reused between multiple writers.
248 * Returned writer can be used emit multiple top level element,
249 * but does not start / close parent JSON object, which must be done
250 * by user providing {@code jsonWriter} instance in order for
251 * JSON to be valid. Closing this instance <strong>will not</strong>
252 * close the wrapped writer; the caller must take care of that.
254 * @param codecFactory JSON codec factory
255 * @param rootNode Root node
256 * @param initialNs Initial namespace
257 * @param jsonWriter JsonWriter
258 * @return A stream writer instance
260 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
261 final DataNodeContainer rootNode, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
262 return new Nested(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
263 new JSONStreamWriterSharedRootContext(initialNs));
267 public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
268 return ImmutableClassToInstanceMap.of(StreamWriterMountPointExtension.class, this);
272 public void startLeafNode(final NodeIdentifier name) throws IOException {
273 tracker.startLeafNode(name);
274 context.emittingChild(codecs.getEffectiveModelContext(), writer);
275 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
279 public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
280 tracker.startLeafSet(name);
281 context = new JSONStreamWriterListContext(context, name);
285 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
286 tracker.startLeafSetEntryNode(name);
287 context.emittingChild(codecs.getEffectiveModelContext(), writer);
291 public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
292 tracker.startLeafSet(name);
293 context = new JSONStreamWriterListContext(context, name);
297 * Warning suppressed due to static final constant which triggers a warning
298 * for the call to schema.isPresenceContainer().
301 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
302 final SchemaNode schema = tracker.startContainerNode(name);
303 final boolean isPresence = schema instanceof ContainerSchemaNode
304 ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
305 context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
309 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
310 tracker.startList(name);
311 context = new JSONStreamWriterListContext(context, name);
315 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
316 tracker.startListItem(name);
317 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
321 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
322 tracker.startList(name);
323 context = new JSONStreamWriterListContext(context, name);
327 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
329 tracker.startListItem(identifier);
330 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
334 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
335 tracker.startList(name);
336 context = new JSONStreamWriterListContext(context, name);
340 public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
341 tracker.startChoiceNode(name);
342 context = new JSONStreamWriterInvisibleContext(context);
346 public final void startAugmentationNode(final AugmentationIdentifier identifier) {
347 tracker.startAugmentationNode(identifier);
348 context = new JSONStreamWriterInvisibleContext(context);
352 public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
353 if (NormalizedAnydata.class.isAssignableFrom(objectModel)) {
354 tracker.startAnydataNode(name);
355 context.emittingChild(codecs.getEffectiveModelContext(), writer);
356 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
364 public final NormalizedNodeStreamWriter startMountPoint(final MountPointIdentifier mountId,
365 final MountPointContext mountCtx) throws IOException {
366 final EffectiveModelContext ctx = mountCtx.getEffectiveModelContext();
367 return new Nested(codecs.rebaseTo(ctx), SchemaTracker.create(ctx), writer,
368 new JSONStreamWriterSharedRootContext(context.getNamespace()));
372 public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
373 if (DOMSource.class.isAssignableFrom(objectModel)) {
374 tracker.startAnyxmlNode(name);
375 context.emittingChild(codecs.getEffectiveModelContext(), writer);
376 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
383 public final void endNode() throws IOException {
385 context = context.endNode(codecs.getEffectiveModelContext(), writer);
389 public final void flush() throws IOException {
393 final void closeWriter() throws IOException {
394 if (!(context instanceof JSONStreamWriterRootContext)) {
395 throw new IOException("Unexpected root context " + context);
398 context.endNode(codecs.getEffectiveModelContext(), writer);
403 public void scalarValue(final Object value) throws IOException {
404 final Object current = tracker.getParent();
405 if (current instanceof TypedDataSchemaNode) {
406 writeValue(value, codecs.codecFor((TypedDataSchemaNode) current));
407 } else if (current instanceof AnydataSchemaNode) {
408 writeAnydataValue(value);
410 throw new IllegalStateException(String.format("Cannot emit scalar %s for %s", value, current));
415 public void domSourceValue(final DOMSource value) throws IOException {
416 final Object current = tracker.getParent();
417 checkState(current instanceof AnyxmlSchemaNode, "Cannot emit DOMSource %s for %s", value, current);
418 // FIXME: should have a codec based on this :)
419 writeAnyXmlValue(value);
422 @SuppressWarnings("unchecked")
423 private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
424 ((JSONCodec<Object>) codec).writeValue(writer, value);
427 private void writeAnydataValue(final Object value) throws IOException {
428 if (value instanceof NormalizedAnydata) {
429 writeNormalizedAnydata((NormalizedAnydata) value);
431 throw new IllegalStateException("Unexpected anydata value " + value);
435 private void writeNormalizedAnydata(final NormalizedAnydata anydata) throws IOException {
436 anydata.writeTo(JSONNormalizedNodeStreamWriter.createNestedWriter(
437 codecs.rebaseTo(anydata.getEffectiveModelContext()),
438 new SingleChildDataNodeContainer(anydata.getContextNode()), context.getNamespace(), writer));
441 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
442 writeXmlNode(anyXmlValue.getNode());
445 private void writeXmlNode(final Node node) throws IOException {
446 if (isArrayElement(node)) {
447 writeArrayContent(node);
450 final Element firstChildElement = getFirstChildElement(node);
451 if (firstChildElement == null) {
454 writeObjectContent(firstChildElement);
458 private void writeArrayContent(final Node node) throws IOException {
464 private void writeObjectContent(final Element firstChildElement) throws IOException {
465 writer.beginObject();
466 writeObject(firstChildElement);
470 private static boolean isArrayElement(final Node node) {
471 if (ELEMENT_NODE == node.getNodeType()) {
472 final String nodeName = node.getNodeName();
473 for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
474 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
482 private void handleArray(final Node node) throws IOException {
483 final Element parentNode = (Element)node.getParentNode();
484 final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
485 for (int i = 0, length = elementsList.getLength(); i < length; i++) {
486 final Node arrayElement = elementsList.item(i);
487 final Element parent = (Element)arrayElement.getParentNode();
488 if (parentNode.isSameNode(parent)) {
489 final Element firstChildElement = getFirstChildElement(arrayElement);
490 if (firstChildElement != null) {
491 writeObjectContent(firstChildElement);
494 writeXmlValue(arrayElement);
500 private void writeObject(Node node) throws IOException {
501 String previousNodeName = "";
502 while (node != null) {
503 if (ELEMENT_NODE == node.getNodeType()) {
504 if (!node.getNodeName().equals(previousNodeName)) {
505 previousNodeName = node.getNodeName();
506 writer.name(node.getNodeName());
510 node = node.getNextSibling();
514 private void writeXmlValue(final Node node) throws IOException {
515 Text firstChild = getFirstChildText(node);
516 String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
517 childNodeText = childNodeText != null ? childNodeText.trim() : "";
519 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
520 writer.value(parseNumber(childNodeText));
523 switch (childNodeText) {
534 writer.value(childNodeText);
538 private static Element getFirstChildElement(final Node node) {
539 final NodeList children = node.getChildNodes();
540 for (int i = 0, length = children.getLength(); i < length; i++) {
541 final Node childNode = children.item(i);
542 if (ELEMENT_NODE == childNode.getNodeType()) {
543 return (Element) childNode;
549 private static Text getFirstChildText(final Node node) {
550 final NodeList children = node.getChildNodes();
551 for (int i = 0, length = children.getLength(); i < length; i++) {
552 final Node childNode = children.item(i);
553 if (TEXT_NODE == childNode.getNodeType()) {
554 return (Text) childNode;
560 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
561 private static Number parseNumber(final String numberText) {
562 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
563 return Long.valueOf(numberText);
566 return Double.valueOf(numberText);