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.impl.codec.SchemaTracker;
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 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 XMLNamespace initialNs, final JsonWriter jsonWriter) {
132 return new Exclusive(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path),
133 jsonWriter, 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 inference
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 EffectiveStatementInference rootNode, final XMLNamespace 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 is exclusive user of JsonWriter, which means it will start
171 * top-level JSON element and ends it.
174 * This instance of writer can be used only to emit one top level element,
175 * otherwise it will produce incorrect JSON. Closing this instance will close
178 * @param codecFactory JSON codec factory
179 * @param path Schema Path
180 * @param initialNs Initial namespace
181 * @param jsonWriter JsonWriter
182 * @return A stream writer instance
184 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
185 final Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
186 return new Exclusive(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path),
187 jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
191 * Create a new stream writer, which writes to the specified output stream.
194 * The codec factory can be reused between multiple writers.
197 * Returned writer can be used emit multiple top level element,
198 * but does not start / close parent JSON object, which must be done
199 * by user providing {@code jsonWriter} instance in order for
200 * JSON to be valid. Closing this instance <strong>will not</strong>
201 * close the wrapped writer; the caller must take care of that.
203 * @param codecFactory JSON codec factory
204 * @param path Schema Path
205 * @param initialNs Initial namespace
206 * @param jsonWriter JsonWriter
207 * @return A stream writer instance
209 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
210 final SchemaPath path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
211 return new Nested(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path), jsonWriter,
212 new JSONStreamWriterSharedRootContext(initialNs));
216 * Create a new stream writer, which writes to the specified output stream.
219 * The codec factory can be reused between multiple writers.
222 * Returned writer can be used emit multiple top level element,
223 * but does not start / close parent JSON object, which must be done
224 * by user providing {@code jsonWriter} instance in order for
225 * JSON to be valid. Closing this instance <strong>will not</strong>
226 * close the wrapped writer; the caller must take care of that.
228 * @param codecFactory JSON codec factory
229 * @param path Schema Path
230 * @param initialNs Initial namespace
231 * @param jsonWriter JsonWriter
232 * @return A stream writer instance
234 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
235 final Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
236 return new Nested(codecFactory, SchemaTracker.create(codecFactory.getEffectiveModelContext(), path), jsonWriter,
237 new JSONStreamWriterSharedRootContext(initialNs));
241 * Create a new stream writer, which writes to the specified output stream.
244 * The codec factory can be reused between multiple writers.
247 * Returned writer can be used emit multiple top level element,
248 * but does not start / close parent JSON object, which must be done
249 * by user providing {@code jsonWriter} instance in order for
250 * JSON to be valid. Closing this instance <strong>will not</strong>
251 * close the wrapped writer; the caller must take care of that.
253 * @param codecFactory JSON codec factory
254 * @param rootNode Root node inference
255 * @param initialNs Initial namespace
256 * @param jsonWriter JsonWriter
257 * @return A stream writer instance
259 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
260 final EffectiveStatementInference rootNode, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
261 return new Nested(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
262 new JSONStreamWriterSharedRootContext(initialNs));
266 public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
267 return ImmutableClassToInstanceMap.of(StreamWriterMountPointExtension.class, this);
271 public void startLeafNode(final NodeIdentifier name) throws IOException {
272 tracker.startLeafNode(name);
273 context.emittingChild(codecs.getEffectiveModelContext(), writer);
274 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
278 public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
279 tracker.startLeafSet(name);
280 context = new JSONStreamWriterListContext(context, name);
284 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
285 tracker.startLeafSetEntryNode(name);
286 context.emittingChild(codecs.getEffectiveModelContext(), writer);
290 public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
291 tracker.startLeafSet(name);
292 context = new JSONStreamWriterListContext(context, name);
296 * Warning suppressed due to static final constant which triggers a warning
297 * for the call to schema.isPresenceContainer().
300 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
301 final SchemaNode schema = tracker.startContainerNode(name);
302 final boolean isPresence = schema instanceof ContainerSchemaNode
303 ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
304 context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
308 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
309 tracker.startList(name);
310 context = new JSONStreamWriterListContext(context, name);
314 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
315 tracker.startListItem(name);
316 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
320 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
321 tracker.startList(name);
322 context = new JSONStreamWriterListContext(context, name);
326 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
328 tracker.startListItem(identifier);
329 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
333 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
334 tracker.startList(name);
335 context = new JSONStreamWriterListContext(context, name);
339 public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
340 tracker.startChoiceNode(name);
341 context = new JSONStreamWriterInvisibleContext(context);
345 public final void startAugmentationNode(final AugmentationIdentifier identifier) {
346 tracker.startAugmentationNode(identifier);
347 context = new JSONStreamWriterInvisibleContext(context);
351 public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
352 if (NormalizedAnydata.class.isAssignableFrom(objectModel)) {
353 tracker.startAnydataNode(name);
354 context.emittingChild(codecs.getEffectiveModelContext(), writer);
355 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
363 public final NormalizedNodeStreamWriter startMountPoint(final MountPointIdentifier mountId,
364 final MountPointContext mountCtx) throws IOException {
365 final EffectiveModelContext ctx = mountCtx.getEffectiveModelContext();
366 return new Nested(codecs.rebaseTo(ctx), SchemaTracker.create(ctx), writer,
367 new JSONStreamWriterSharedRootContext(context.getNamespace()));
371 public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
372 if (DOMSource.class.isAssignableFrom(objectModel)) {
373 tracker.startAnyxmlNode(name);
374 context.emittingChild(codecs.getEffectiveModelContext(), writer);
375 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
382 public final void endNode() throws IOException {
384 context = context.endNode(codecs.getEffectiveModelContext(), writer);
388 public final void flush() throws IOException {
392 final void closeWriter() throws IOException {
393 if (!(context instanceof JSONStreamWriterRootContext)) {
394 throw new IOException("Unexpected root context " + context);
397 context.endNode(codecs.getEffectiveModelContext(), writer);
402 public void scalarValue(final Object value) throws IOException {
403 final Object current = tracker.getParent();
404 if (current instanceof TypedDataSchemaNode) {
405 writeValue(value, codecs.codecFor((TypedDataSchemaNode) current));
406 } else if (current instanceof AnydataSchemaNode) {
407 writeAnydataValue(value);
409 throw new IllegalStateException(String.format("Cannot emit scalar %s for %s", value, current));
414 public void domSourceValue(final DOMSource value) throws IOException {
415 final Object current = tracker.getParent();
416 checkState(current instanceof AnyxmlSchemaNode, "Cannot emit DOMSource %s for %s", value, current);
417 // FIXME: should have a codec based on this :)
418 writeAnyXmlValue(value);
421 @SuppressWarnings("unchecked")
422 private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
423 ((JSONCodec<Object>) codec).writeValue(writer, value);
426 private void writeAnydataValue(final Object value) throws IOException {
427 if (value instanceof NormalizedAnydata) {
428 writeNormalizedAnydata((NormalizedAnydata) value);
430 throw new IllegalStateException("Unexpected anydata value " + value);
434 private void writeNormalizedAnydata(final NormalizedAnydata anydata) throws IOException {
435 // Adjust state to point to parent node and ensure it can handle data tree nodes
436 final SchemaInferenceStack.Inference inference;
438 final SchemaInferenceStack stack = SchemaInferenceStack.ofInference(anydata.getInference());
439 stack.exitToDataTree();
440 inference = stack.toInference();
441 } catch (IllegalArgumentException | IllegalStateException | NoSuchElementException e) {
442 throw new IOException("Cannot emit " + anydata, e);
445 anydata.writeTo(JSONNormalizedNodeStreamWriter.createNestedWriter(
446 codecs.rebaseTo(inference.getEffectiveModelContext()), inference, context.getNamespace(), writer));
449 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
450 writeXmlNode(anyXmlValue.getNode());
453 private void writeXmlNode(final Node node) throws IOException {
454 if (isArrayElement(node)) {
455 writeArrayContent(node);
458 final Element firstChildElement = getFirstChildElement(node);
459 if (firstChildElement == null) {
462 writeObjectContent(firstChildElement);
466 private void writeArrayContent(final Node node) throws IOException {
472 private void writeObjectContent(final Element firstChildElement) throws IOException {
473 writer.beginObject();
474 writeObject(firstChildElement);
478 private static boolean isArrayElement(final Node node) {
479 if (Node.ELEMENT_NODE == node.getNodeType()) {
480 final String nodeName = node.getNodeName();
481 for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
482 if (Node.ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
490 private void handleArray(final Node node) throws IOException {
491 final Element parentNode = (Element)node.getParentNode();
492 final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
493 for (int i = 0, length = elementsList.getLength(); i < length; i++) {
494 final Node arrayElement = elementsList.item(i);
495 final Element parent = (Element)arrayElement.getParentNode();
496 if (parentNode.isSameNode(parent)) {
497 final Element firstChildElement = getFirstChildElement(arrayElement);
498 if (firstChildElement != null) {
499 writeObjectContent(firstChildElement);
502 writeXmlValue(arrayElement);
508 private void writeObject(Node node) throws IOException {
509 String previousNodeName = "";
510 while (node != null) {
511 if (Node.ELEMENT_NODE == node.getNodeType()) {
512 if (!node.getNodeName().equals(previousNodeName)) {
513 previousNodeName = node.getNodeName();
514 writer.name(node.getNodeName());
518 node = node.getNextSibling();
522 private void writeXmlValue(final Node node) throws IOException {
523 Text firstChild = getFirstChildText(node);
524 String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
525 childNodeText = childNodeText != null ? childNodeText.trim() : "";
527 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
528 writer.value(parseNumber(childNodeText));
531 switch (childNodeText) {
542 writer.value(childNodeText);
546 private static Element getFirstChildElement(final Node node) {
547 final NodeList children = node.getChildNodes();
548 for (int i = 0, length = children.getLength(); i < length; i++) {
549 final Node childNode = children.item(i);
550 if (Node.ELEMENT_NODE == childNode.getNodeType()) {
551 return (Element) childNode;
557 private static Text getFirstChildText(final Node node) {
558 final NodeList children = node.getChildNodes();
559 for (int i = 0, length = children.getLength(); i < length; i++) {
560 final Node childNode = children.item(i);
561 if (Node.TEXT_NODE == childNode.getNodeType()) {
562 return (Text) childNode;
568 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
569 private static Number parseNumber(final String numberText) {
570 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
571 return Long.valueOf(numberText);
574 return Double.valueOf(numberText);