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;
13 import com.google.common.collect.ClassToInstanceMap;
14 import com.google.common.collect.ImmutableClassToInstanceMap;
15 import com.google.gson.stream.JsonWriter;
16 import java.io.IOException;
17 import java.util.NoSuchElementException;
18 import java.util.regex.Pattern;
19 import javax.xml.transform.dom.DOMSource;
20 import org.checkerframework.checker.regex.qual.Regex;
21 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
22 import org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier;
23 import org.opendaylight.yangtools.rfc8528.data.api.StreamWriterMountPointExtension;
24 import org.opendaylight.yangtools.yang.common.XMLNamespace;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedAnydata;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriterExtension;
32 import org.opendaylight.yangtools.yang.data.util.NormalizedNodeInferenceStack;
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.EffectiveModelContext;
37 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
38 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
40 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
42 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
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 NormalizedNodeInferenceStack tracker,
58 final JsonWriter writer, 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 NormalizedNodeInferenceStack 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 NormalizedNodeInferenceStack tracker;
97 private final JSONCodecFactory codecs;
98 private final JsonWriter writer;
99 private JSONStreamWriterContext context;
101 JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final NormalizedNodeInferenceStack 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 XMLNamespace initialNs, final JsonWriter jsonWriter) {
132 return new Exclusive(codecFactory,
133 NormalizedNodeInferenceStack.of(codecFactory.getEffectiveModelContext(), path), jsonWriter,
134 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 rootNode Root node inference
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 EffectiveStatementInference rootNode, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
160 return new Exclusive(codecFactory, NormalizedNodeInferenceStack.of(rootNode), jsonWriter,
161 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 path Schema Path
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 Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
187 return new Exclusive(codecFactory,
188 NormalizedNodeInferenceStack.of(codecFactory.getEffectiveModelContext(), path), jsonWriter,
189 new JSONStreamWriterExclusiveRootContext(initialNs));
193 * Create a new stream writer, which writes to the specified output stream.
196 * The codec factory can be reused between multiple writers.
199 * Returned writer can be used emit multiple top level element,
200 * but does not start / close parent JSON object, which must be done
201 * by user providing {@code jsonWriter} instance in order for
202 * JSON to be valid. Closing this instance <strong>will not</strong>
203 * close the wrapped writer; the caller must take care of that.
205 * @param codecFactory JSON codec factory
206 * @param path Schema Path
207 * @param initialNs Initial namespace
208 * @param jsonWriter JsonWriter
209 * @return A stream writer instance
211 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
212 final SchemaPath path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
213 return new Nested(codecFactory, NormalizedNodeInferenceStack.of(codecFactory.getEffectiveModelContext(), path),
214 jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
218 * Create a new stream writer, which writes to the specified output stream.
221 * The codec factory can be reused between multiple writers.
224 * Returned writer can be used emit multiple top level element,
225 * but does not start / close parent JSON object, which must be done
226 * by user providing {@code jsonWriter} instance in order for
227 * JSON to be valid. Closing this instance <strong>will not</strong>
228 * close the wrapped writer; the caller must take care of that.
230 * @param codecFactory JSON codec factory
231 * @param path Schema Path
232 * @param initialNs Initial namespace
233 * @param jsonWriter JsonWriter
234 * @return A stream writer instance
236 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
237 final Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
238 return new Nested(codecFactory, NormalizedNodeInferenceStack.of(codecFactory.getEffectiveModelContext(), path),
239 jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
243 * Create a new stream writer, which writes to the specified output stream.
246 * The codec factory can be reused between multiple writers.
249 * Returned writer can be used emit multiple top level element,
250 * but does not start / close parent JSON object, which must be done
251 * by user providing {@code jsonWriter} instance in order for
252 * JSON to be valid. Closing this instance <strong>will not</strong>
253 * close the wrapped writer; the caller must take care of that.
255 * @param codecFactory JSON codec factory
256 * @param rootNode Root node inference
257 * @param initialNs Initial namespace
258 * @param jsonWriter JsonWriter
259 * @return A stream writer instance
261 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
262 final EffectiveStatementInference rootNode, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
263 return new Nested(codecFactory, NormalizedNodeInferenceStack.of(rootNode), jsonWriter,
264 new JSONStreamWriterSharedRootContext(initialNs));
268 public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
269 return ImmutableClassToInstanceMap.of(StreamWriterMountPointExtension.class, this);
273 public void startLeafNode(final NodeIdentifier name) throws IOException {
274 tracker.startLeafNode(name);
275 context.emittingChild(codecs.getEffectiveModelContext(), writer);
276 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
280 public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
281 tracker.startLeafSet(name);
282 context = new JSONStreamWriterListContext(context, name);
286 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
287 tracker.startLeafSetEntryNode(name);
288 context.emittingChild(codecs.getEffectiveModelContext(), writer);
292 public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
293 tracker.startLeafSet(name);
294 context = new JSONStreamWriterListContext(context, name);
298 * Warning suppressed due to static final constant which triggers a warning
299 * for the call to schema.isPresenceContainer().
302 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
303 final SchemaNode schema = tracker.startContainerNode(name);
304 final boolean isPresence = schema instanceof ContainerSchemaNode
305 ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
306 context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
310 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
311 tracker.startList(name);
312 context = new JSONStreamWriterListContext(context, name);
316 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
317 tracker.startListItem(name);
318 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
322 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
323 tracker.startList(name);
324 context = new JSONStreamWriterListContext(context, name);
328 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
330 tracker.startListItem(identifier);
331 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
335 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
336 tracker.startList(name);
337 context = new JSONStreamWriterListContext(context, name);
341 public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
342 tracker.startChoiceNode(name);
343 context = new JSONStreamWriterInvisibleContext(context);
347 public final void startAugmentationNode(final AugmentationIdentifier identifier) {
348 tracker.startAugmentationNode(identifier);
349 context = new JSONStreamWriterInvisibleContext(context);
353 public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
354 if (NormalizedAnydata.class.isAssignableFrom(objectModel)) {
355 tracker.startAnydataNode(name);
356 context.emittingChild(codecs.getEffectiveModelContext(), writer);
357 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
365 public final NormalizedNodeStreamWriter startMountPoint(final MountPointIdentifier mountId,
366 final MountPointContext mountCtx) throws IOException {
367 final EffectiveModelContext ctx = mountCtx.getEffectiveModelContext();
368 return new Nested(codecs.rebaseTo(ctx), NormalizedNodeInferenceStack.of(ctx), writer,
369 new JSONStreamWriterSharedRootContext(context.getNamespace()));
373 public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
374 if (DOMSource.class.isAssignableFrom(objectModel)) {
375 tracker.startAnyxmlNode(name);
376 context.emittingChild(codecs.getEffectiveModelContext(), writer);
377 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
384 public final void endNode() throws IOException {
386 context = context.endNode(codecs.getEffectiveModelContext(), writer);
390 public final void flush() throws IOException {
394 final void closeWriter() throws IOException {
395 if (!(context instanceof JSONStreamWriterRootContext)) {
396 throw new IOException("Unexpected root context " + context);
399 context.endNode(codecs.getEffectiveModelContext(), writer);
404 public void scalarValue(final Object value) throws IOException {
405 final Object current = tracker.getParent();
406 if (current instanceof TypedDataSchemaNode) {
407 writeValue(value, codecs.codecFor((TypedDataSchemaNode) current));
408 } else if (current instanceof AnydataSchemaNode) {
409 writeAnydataValue(value);
411 throw new IllegalStateException(String.format("Cannot emit scalar %s for %s", value, current));
416 public void domSourceValue(final DOMSource value) throws IOException {
417 final Object current = tracker.getParent();
418 checkState(current instanceof AnyxmlSchemaNode, "Cannot emit DOMSource %s for %s", value, current);
419 // FIXME: should have a codec based on this :)
420 writeAnyXmlValue(value);
423 @SuppressWarnings("unchecked")
424 private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
425 ((JSONCodec<Object>) codec).writeValue(writer, value);
428 private void writeAnydataValue(final Object value) throws IOException {
429 if (value instanceof NormalizedAnydata) {
430 writeNormalizedAnydata((NormalizedAnydata) value);
432 throw new IllegalStateException("Unexpected anydata value " + value);
436 private void writeNormalizedAnydata(final NormalizedAnydata anydata) throws IOException {
437 // Adjust state to point to parent node and ensure it can handle data tree nodes
438 final SchemaInferenceStack.Inference inference;
440 final SchemaInferenceStack stack = SchemaInferenceStack.ofInference(anydata.getInference());
441 stack.exitToDataTree();
442 inference = stack.toInference();
443 } catch (IllegalArgumentException | IllegalStateException | NoSuchElementException e) {
444 throw new IOException("Cannot emit " + anydata, e);
447 anydata.writeTo(JSONNormalizedNodeStreamWriter.createNestedWriter(
448 codecs.rebaseTo(inference.getEffectiveModelContext()), inference, context.getNamespace(), writer));
451 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
452 writeXmlNode(anyXmlValue.getNode());
455 private void writeXmlNode(final Node node) throws IOException {
456 if (isArrayElement(node)) {
457 writeArrayContent(node);
460 final Element firstChildElement = getFirstChildElement(node);
461 if (firstChildElement == null) {
464 writeObjectContent(firstChildElement);
468 private void writeArrayContent(final Node node) throws IOException {
474 private void writeObjectContent(final Element firstChildElement) throws IOException {
475 writer.beginObject();
476 writeObject(firstChildElement);
480 private static boolean isArrayElement(final Node node) {
481 if (Node.ELEMENT_NODE == node.getNodeType()) {
482 final String nodeName = node.getNodeName();
483 for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
484 if (Node.ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
492 private void handleArray(final Node node) throws IOException {
493 final Element parentNode = (Element)node.getParentNode();
494 final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
495 for (int i = 0, length = elementsList.getLength(); i < length; i++) {
496 final Node arrayElement = elementsList.item(i);
497 final Element parent = (Element)arrayElement.getParentNode();
498 if (parentNode.isSameNode(parent)) {
499 final Element firstChildElement = getFirstChildElement(arrayElement);
500 if (firstChildElement != null) {
501 writeObjectContent(firstChildElement);
504 writeXmlValue(arrayElement);
510 private void writeObject(Node node) throws IOException {
511 String previousNodeName = "";
512 while (node != null) {
513 if (Node.ELEMENT_NODE == node.getNodeType()) {
514 if (!node.getNodeName().equals(previousNodeName)) {
515 previousNodeName = node.getNodeName();
516 writer.name(node.getNodeName());
520 node = node.getNextSibling();
524 private void writeXmlValue(final Node node) throws IOException {
525 Text firstChild = getFirstChildText(node);
526 String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
527 childNodeText = childNodeText != null ? childNodeText.trim() : "";
529 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
530 writer.value(parseNumber(childNodeText));
533 switch (childNodeText) {
544 writer.value(childNodeText);
548 private static Element getFirstChildElement(final Node node) {
549 final NodeList children = node.getChildNodes();
550 for (int i = 0, length = children.getLength(); i < length; i++) {
551 final Node childNode = children.item(i);
552 if (Node.ELEMENT_NODE == childNode.getNodeType()) {
553 return (Element) childNode;
559 private static Text getFirstChildText(final Node node) {
560 final NodeList children = node.getChildNodes();
561 for (int i = 0, length = children.getLength(); i < length; i++) {
562 final Node childNode = children.item(i);
563 if (Node.TEXT_NODE == childNode.getNodeType()) {
564 return (Text) childNode;
570 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
571 private static Number parseNumber(final String numberText) {
572 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
573 return Long.valueOf(numberText);
576 return Double.valueOf(numberText);