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.NormalizedNodeStreamWriterStack;
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 NormalizedNodeStreamWriterStack 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 NormalizedNodeStreamWriterStack tracker,
71 final JsonWriter writer, 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 NormalizedNodeStreamWriterStack tracker;
97 private final JSONCodecFactory codecs;
98 private final JsonWriter writer;
99 private JSONStreamWriterContext context;
101 JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final NormalizedNodeStreamWriterStack 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 NormalizedNodeStreamWriterStack.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, NormalizedNodeStreamWriterStack.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 NormalizedNodeStreamWriterStack.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,
214 NormalizedNodeStreamWriterStack.of(codecFactory.getEffectiveModelContext(), path), jsonWriter,
215 new JSONStreamWriterSharedRootContext(initialNs));
219 * Create a new stream writer, which writes to the specified output stream.
222 * The codec factory can be reused between multiple writers.
225 * Returned writer can be used emit multiple top level element,
226 * but does not start / close parent JSON object, which must be done
227 * by user providing {@code jsonWriter} instance in order for
228 * JSON to be valid. Closing this instance <strong>will not</strong>
229 * close the wrapped writer; the caller must take care of that.
231 * @param codecFactory JSON codec factory
232 * @param path Schema Path
233 * @param initialNs Initial namespace
234 * @param jsonWriter JsonWriter
235 * @return A stream writer instance
237 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
238 final Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
239 return new Nested(codecFactory,
240 NormalizedNodeStreamWriterStack.of(codecFactory.getEffectiveModelContext(), path), jsonWriter,
241 new JSONStreamWriterSharedRootContext(initialNs));
245 * Create a new stream writer, which writes to the specified output stream.
248 * The codec factory can be reused between multiple writers.
251 * Returned writer can be used emit multiple top level element,
252 * but does not start / close parent JSON object, which must be done
253 * by user providing {@code jsonWriter} instance in order for
254 * JSON to be valid. Closing this instance <strong>will not</strong>
255 * close the wrapped writer; the caller must take care of that.
257 * @param codecFactory JSON codec factory
258 * @param rootNode Root node inference
259 * @param initialNs Initial namespace
260 * @param jsonWriter JsonWriter
261 * @return A stream writer instance
263 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
264 final EffectiveStatementInference rootNode, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
265 return new Nested(codecFactory, NormalizedNodeStreamWriterStack.of(rootNode), jsonWriter,
266 new JSONStreamWriterSharedRootContext(initialNs));
270 public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
271 return ImmutableClassToInstanceMap.of(StreamWriterMountPointExtension.class, this);
275 public void startLeafNode(final NodeIdentifier name) throws IOException {
276 tracker.startLeafNode(name);
277 context.emittingChild(codecs.getEffectiveModelContext(), writer);
278 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
282 public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
283 tracker.startLeafSet(name);
284 context = new JSONStreamWriterListContext(context, name);
288 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
289 tracker.startLeafSetEntryNode(name);
290 context.emittingChild(codecs.getEffectiveModelContext(), writer);
294 public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
295 tracker.startLeafSet(name);
296 context = new JSONStreamWriterListContext(context, name);
300 * Warning suppressed due to static final constant which triggers a warning
301 * for the call to schema.isPresenceContainer().
304 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
305 final SchemaNode schema = tracker.startContainerNode(name);
306 final boolean isPresence = schema instanceof ContainerSchemaNode
307 ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
308 context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
312 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
313 tracker.startList(name);
314 context = new JSONStreamWriterListContext(context, name);
318 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
319 tracker.startListItem(name);
320 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
324 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
325 tracker.startList(name);
326 context = new JSONStreamWriterListContext(context, name);
330 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
332 tracker.startListItem(identifier);
333 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
337 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
338 tracker.startList(name);
339 context = new JSONStreamWriterListContext(context, name);
343 public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
344 tracker.startChoiceNode(name);
345 context = new JSONStreamWriterInvisibleContext(context);
349 public final void startAugmentationNode(final AugmentationIdentifier identifier) {
350 tracker.startAugmentationNode(identifier);
351 context = new JSONStreamWriterInvisibleContext(context);
355 public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
356 if (NormalizedAnydata.class.isAssignableFrom(objectModel)) {
357 tracker.startAnydataNode(name);
358 context.emittingChild(codecs.getEffectiveModelContext(), writer);
359 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
367 public final NormalizedNodeStreamWriter startMountPoint(final MountPointIdentifier mountId,
368 final MountPointContext mountCtx) throws IOException {
369 final EffectiveModelContext ctx = mountCtx.getEffectiveModelContext();
370 return new Nested(codecs.rebaseTo(ctx), NormalizedNodeStreamWriterStack.of(ctx), writer,
371 new JSONStreamWriterSharedRootContext(context.getNamespace()));
375 public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
376 if (DOMSource.class.isAssignableFrom(objectModel)) {
377 tracker.startAnyxmlNode(name);
378 context.emittingChild(codecs.getEffectiveModelContext(), writer);
379 context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
386 public final void endNode() throws IOException {
388 context = context.endNode(codecs.getEffectiveModelContext(), writer);
392 public final void flush() throws IOException {
396 final void closeWriter() throws IOException {
397 if (!(context instanceof JSONStreamWriterRootContext)) {
398 throw new IOException("Unexpected root context " + context);
401 context.endNode(codecs.getEffectiveModelContext(), writer);
406 public void scalarValue(final Object value) throws IOException {
407 final Object current = tracker.getParent();
408 if (current instanceof TypedDataSchemaNode) {
409 writeValue(value, codecs.codecFor((TypedDataSchemaNode) current, tracker));
410 } else if (current instanceof AnydataSchemaNode) {
411 writeAnydataValue(value);
413 throw new IllegalStateException(String.format("Cannot emit scalar %s for %s", value, current));
418 public void domSourceValue(final DOMSource value) throws IOException {
419 final Object current = tracker.getParent();
420 checkState(current instanceof AnyxmlSchemaNode, "Cannot emit DOMSource %s for %s", value, current);
421 // FIXME: should have a codec based on this :)
422 writeAnyXmlValue(value);
425 @SuppressWarnings("unchecked")
426 private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
427 ((JSONCodec<Object>) codec).writeValue(writer, value);
430 private void writeAnydataValue(final Object value) throws IOException {
431 if (value instanceof NormalizedAnydata) {
432 writeNormalizedAnydata((NormalizedAnydata) value);
434 throw new IllegalStateException("Unexpected anydata value " + value);
438 private void writeNormalizedAnydata(final NormalizedAnydata anydata) throws IOException {
439 // Adjust state to point to parent node and ensure it can handle data tree nodes
440 final SchemaInferenceStack.Inference inference;
442 final SchemaInferenceStack stack = SchemaInferenceStack.ofInference(anydata.getInference());
443 stack.exitToDataTree();
444 inference = stack.toInference();
445 } catch (IllegalArgumentException | IllegalStateException | NoSuchElementException e) {
446 throw new IOException("Cannot emit " + anydata, e);
449 anydata.writeTo(JSONNormalizedNodeStreamWriter.createNestedWriter(
450 codecs.rebaseTo(inference.getEffectiveModelContext()), inference, context.getNamespace(), writer));
453 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
454 writeXmlNode(anyXmlValue.getNode());
457 private void writeXmlNode(final Node node) throws IOException {
458 if (isArrayElement(node)) {
459 writeArrayContent(node);
462 final Element firstChildElement = getFirstChildElement(node);
463 if (firstChildElement == null) {
466 writeObjectContent(firstChildElement);
470 private void writeArrayContent(final Node node) throws IOException {
476 private void writeObjectContent(final Element firstChildElement) throws IOException {
477 writer.beginObject();
478 writeObject(firstChildElement);
482 private static boolean isArrayElement(final Node node) {
483 if (Node.ELEMENT_NODE == node.getNodeType()) {
484 final String nodeName = node.getNodeName();
485 for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
486 if (Node.ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
494 private void handleArray(final Node node) throws IOException {
495 final Element parentNode = (Element)node.getParentNode();
496 final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
497 for (int i = 0, length = elementsList.getLength(); i < length; i++) {
498 final Node arrayElement = elementsList.item(i);
499 final Element parent = (Element)arrayElement.getParentNode();
500 if (parentNode.isSameNode(parent)) {
501 final Element firstChildElement = getFirstChildElement(arrayElement);
502 if (firstChildElement != null) {
503 writeObjectContent(firstChildElement);
506 writeXmlValue(arrayElement);
512 private void writeObject(Node node) throws IOException {
513 String previousNodeName = "";
514 while (node != null) {
515 if (Node.ELEMENT_NODE == node.getNodeType()) {
516 if (!node.getNodeName().equals(previousNodeName)) {
517 previousNodeName = node.getNodeName();
518 writer.name(node.getNodeName());
522 node = node.getNextSibling();
526 private void writeXmlValue(final Node node) throws IOException {
527 Text firstChild = getFirstChildText(node);
528 String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
529 childNodeText = childNodeText != null ? childNodeText.trim() : "";
531 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
532 writer.value(parseNumber(childNodeText));
535 switch (childNodeText) {
546 writer.value(childNodeText);
550 private static Element getFirstChildElement(final Node node) {
551 final NodeList children = node.getChildNodes();
552 for (int i = 0, length = children.getLength(); i < length; i++) {
553 final Node childNode = children.item(i);
554 if (Node.ELEMENT_NODE == childNode.getNodeType()) {
555 return (Element) childNode;
561 private static Text getFirstChildText(final Node node) {
562 final NodeList children = node.getChildNodes();
563 for (int i = 0, length = children.getLength(); i < length; i++) {
564 final Node childNode = children.item(i);
565 if (Node.TEXT_NODE == childNode.getNodeType()) {
566 return (Text) childNode;
572 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
573 private static Number parseNumber(final String numberText) {
574 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
575 return Long.valueOf(numberText);
578 return Double.valueOf(numberText);