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.gson.stream.JsonWriter;
17 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.concepts.ObjectExtensions;
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.MountPointStreamWriter;
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.AnydataExtension;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
33 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriterExtension;
34 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
35 import org.opendaylight.yangtools.yang.data.util.SingleChildDataNodeContainer;
36 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
43 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
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, AnydataExtension,
56 MountPointStreamWriter {
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;
89 static final ObjectExtensions.Factory<JSONNormalizedNodeStreamWriter, NormalizedNodeStreamWriter,
90 NormalizedNodeStreamWriterExtension> EXTENSIONS_BUILDER = ObjectExtensions.factory(
91 JSONNormalizedNodeStreamWriter.class, AnydataExtension.class, MountPointStreamWriter.class);
94 private static final String NUMBER_STRING = "-?\\d+(\\.\\d+)?";
95 private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_STRING);
98 private static final String NOT_DECIMAL_NUMBER_STRING = "-?\\d+";
99 private static final Pattern NOT_DECIMAL_NUMBER_PATTERN = Pattern.compile(NOT_DECIMAL_NUMBER_STRING);
101 private final SchemaTracker tracker;
102 private final JSONCodecFactory codecs;
103 private final JsonWriter writer;
104 private JSONStreamWriterContext context;
106 JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaTracker tracker,
107 final JsonWriter writer, final JSONStreamWriterRootContext rootContext) {
108 this.writer = requireNonNull(writer);
109 this.codecs = requireNonNull(codecFactory);
110 this.tracker = requireNonNull(tracker);
111 this.context = requireNonNull(rootContext);
115 * Create a new stream writer, which writes to the specified output stream.
118 * The codec factory can be reused between multiple writers.
121 * Returned writer is exclusive user of JsonWriter, which means it will start
122 * top-level JSON element and ends it.
125 * This instance of writer can be used only to emit one top level element,
126 * otherwise it will produce incorrect JSON. Closing this instance will close
129 * @param codecFactory JSON codec factory
130 * @param path Schema Path
131 * @param initialNs Initial namespace
132 * @param jsonWriter JsonWriter
133 * @return A stream writer instance
135 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
136 final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
137 return new Exclusive(codecFactory, SchemaTracker.create(codecFactory.getSchemaContext(), path), jsonWriter,
138 new JSONStreamWriterExclusiveRootContext(initialNs));
142 * Create a new stream writer, which writes to the specified output stream.
145 * The codec factory can be reused between multiple writers.
148 * Returned writer is exclusive user of JsonWriter, which means it will start
149 * top-level JSON element and ends it.
152 * This instance of writer can be used only to emit one top level element,
153 * otherwise it will produce incorrect JSON. Closing this instance will close
156 * @param codecFactory JSON codec factory
157 * @param rootNode Root node
158 * @param initialNs Initial namespace
159 * @param jsonWriter JsonWriter
160 * @return A stream writer instance
162 public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
163 final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
164 return new Exclusive(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
165 new JSONStreamWriterExclusiveRootContext(initialNs));
169 * Create a new stream writer, which writes to the specified output stream.
172 * The codec factory can be reused between multiple writers.
175 * Returned writer can be used emit multiple top level element,
176 * but does not start / close parent JSON object, which must be done
177 * by user providing {@code jsonWriter} instance in order for
178 * JSON to be valid. Closing this instance <strong>will not</strong>
179 * close the wrapped writer; the caller must take care of that.
181 * @param codecFactory JSON codec factory
182 * @param path Schema Path
183 * @param initialNs Initial namespace
184 * @param jsonWriter JsonWriter
185 * @return A stream writer instance
187 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
188 final SchemaPath path, final URI initialNs, final JsonWriter jsonWriter) {
189 return new Nested(codecFactory, SchemaTracker.create(codecFactory.getSchemaContext(), path), jsonWriter,
190 new JSONStreamWriterSharedRootContext(initialNs));
194 * Create a new stream writer, which writes to the specified output stream.
197 * The codec factory can be reused between multiple writers.
200 * Returned writer can be used emit multiple top level element,
201 * but does not start / close parent JSON object, which must be done
202 * by user providing {@code jsonWriter} instance in order for
203 * JSON to be valid. Closing this instance <strong>will not</strong>
204 * close the wrapped writer; the caller must take care of that.
206 * @param codecFactory JSON codec factory
207 * @param rootNode Root node
208 * @param initialNs Initial namespace
209 * @param jsonWriter JsonWriter
210 * @return A stream writer instance
212 public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
213 final DataNodeContainer rootNode, final URI initialNs, final JsonWriter jsonWriter) {
214 return new Nested(codecFactory, SchemaTracker.create(rootNode), jsonWriter,
215 new JSONStreamWriterSharedRootContext(initialNs));
219 public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
220 return EXTENSIONS_BUILDER.newInstance(this);
224 public void startLeafNode(final NodeIdentifier name) throws IOException {
225 tracker.startLeafNode(name);
226 context.emittingChild(codecs.getSchemaContext(), writer);
227 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
231 public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
232 tracker.startLeafSet(name);
233 context = new JSONStreamWriterListContext(context, name);
237 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
238 tracker.startLeafSetEntryNode(name);
239 context.emittingChild(codecs.getSchemaContext(), writer);
243 public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
244 tracker.startLeafSet(name);
245 context = new JSONStreamWriterListContext(context, name);
249 * Warning suppressed due to static final constant which triggers a warning
250 * for the call to schema.isPresenceContainer().
253 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
254 final SchemaNode schema = tracker.startContainerNode(name);
255 final boolean isPresence = schema instanceof ContainerSchemaNode
256 ? ((ContainerSchemaNode) schema).isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
257 context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
261 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
262 tracker.startList(name);
263 context = new JSONStreamWriterListContext(context, name);
267 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
268 tracker.startListItem(name);
269 context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
273 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
274 tracker.startList(name);
275 context = new JSONStreamWriterListContext(context, name);
279 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
281 tracker.startListItem(identifier);
282 context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
286 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
287 tracker.startList(name);
288 context = new JSONStreamWriterListContext(context, name);
292 public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
293 tracker.startChoiceNode(name);
294 context = new JSONStreamWriterInvisibleContext(context);
298 public final void startAugmentationNode(final AugmentationIdentifier identifier) {
299 tracker.startAugmentationNode(identifier);
300 context = new JSONStreamWriterInvisibleContext(context);
304 public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
305 if (NormalizedAnydata.class.isAssignableFrom(objectModel)) {
306 tracker.startAnydataNode(name);
307 context.emittingChild(codecs.getSchemaContext(), writer);
308 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
316 public final NormalizedNodeStreamWriter startMountPoint(final MountPointIdentifier mountId,
317 final MountPointContext mountCtx) throws IOException {
318 final SchemaContext ctx = mountCtx.getSchemaContext();
319 return new Nested(codecs.rebaseTo(ctx), SchemaTracker.create(ctx), writer,
320 new JSONStreamWriterSharedRootContext(context.getNamespace()));
324 public final void startAnyxmlNode(final NodeIdentifier name) throws IOException {
325 tracker.startAnyxmlNode(name);
326 context.emittingChild(codecs.getSchemaContext(), writer);
327 context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
331 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
333 tracker.startYangModeledAnyXmlNode(name);
334 context = new JSONStreamWriterNamedObjectContext(context, name, true);
338 public final void endNode() throws IOException {
340 context = context.endNode(codecs.getSchemaContext(), writer);
342 if (context instanceof JSONStreamWriterRootContext) {
343 context.endNode(codecs.getSchemaContext(), writer);
348 public final void flush() throws IOException {
352 final void closeWriter() throws IOException {
357 public void scalarValue(final Object value) throws IOException {
358 final Object current = tracker.getParent();
359 if (current instanceof TypedDataSchemaNode) {
360 writeValue(value, codecs.codecFor((TypedDataSchemaNode) current));
361 } else if (current instanceof AnydataSchemaNode) {
362 writeAnydataValue(value);
364 throw new IllegalStateException(String.format("Cannot emit scalar %s for %s", value, current));
369 public void domSourceValue(final DOMSource value) throws IOException {
370 final Object current = tracker.getParent();
371 checkState(current instanceof AnyxmlSchemaNode, "Cannot emit DOMSource %s for %s", value, current);
372 // FIXME: should have a codec based on this :)
373 writeAnyXmlValue(value);
376 @SuppressWarnings("unchecked")
377 private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
378 ((JSONCodec<Object>) codec).writeValue(writer, value);
381 private void writeAnydataValue(final Object value) throws IOException {
382 if (value instanceof NormalizedAnydata) {
383 writeNormalizedAnydata((NormalizedAnydata) value);
385 throw new IllegalStateException("Unexpected anydata value " + value);
389 private void writeNormalizedAnydata(final NormalizedAnydata anydata) throws IOException {
390 anydata.writeTo(JSONNormalizedNodeStreamWriter.createNestedWriter(codecs.rebaseTo(anydata.getSchemaContext()),
391 new SingleChildDataNodeContainer(anydata.getContextNode()), context.getNamespace(), writer));
394 private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
395 writeXmlNode(anyXmlValue.getNode());
398 private void writeXmlNode(final Node node) throws IOException {
399 if (isArrayElement(node)) {
400 writeArrayContent(node);
403 final Element firstChildElement = getFirstChildElement(node);
404 if (firstChildElement == null) {
407 writeObjectContent(firstChildElement);
411 private void writeArrayContent(final Node node) throws IOException {
417 private void writeObjectContent(final Element firstChildElement) throws IOException {
418 writer.beginObject();
419 writeObject(firstChildElement);
423 private static boolean isArrayElement(final Node node) {
424 if (ELEMENT_NODE == node.getNodeType()) {
425 final String nodeName = node.getNodeName();
426 for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
427 if (ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
435 private void handleArray(final Node node) throws IOException {
436 final Element parentNode = (Element)node.getParentNode();
437 final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
438 for (int i = 0, length = elementsList.getLength(); i < length; i++) {
439 final Node arrayElement = elementsList.item(i);
440 final Element parent = (Element)arrayElement.getParentNode();
441 if (parentNode.isSameNode(parent)) {
442 final Element firstChildElement = getFirstChildElement(arrayElement);
443 if (firstChildElement != null) {
444 writeObjectContent(firstChildElement);
447 writeXmlValue(arrayElement);
453 private void writeObject(Node node) throws IOException {
454 String previousNodeName = "";
455 while (node != null) {
456 if (ELEMENT_NODE == node.getNodeType()) {
457 if (!node.getNodeName().equals(previousNodeName)) {
458 previousNodeName = node.getNodeName();
459 writer.name(node.getNodeName());
463 node = node.getNextSibling();
467 private void writeXmlValue(final Node node) throws IOException {
468 Text firstChild = getFirstChildText(node);
469 String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
470 childNodeText = childNodeText != null ? childNodeText.trim() : "";
472 if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
473 writer.value(parseNumber(childNodeText));
476 switch (childNodeText) {
487 writer.value(childNodeText);
491 private static Element getFirstChildElement(final Node node) {
492 final NodeList children = node.getChildNodes();
493 for (int i = 0, length = children.getLength(); i < length; i++) {
494 final Node childNode = children.item(i);
495 if (ELEMENT_NODE == childNode.getNodeType()) {
496 return (Element) childNode;
502 private static Text getFirstChildText(final Node node) {
503 final NodeList children = node.getChildNodes();
504 for (int i = 0, length = children.getLength(); i < length; i++) {
505 final Node childNode = children.item(i);
506 if (TEXT_NODE == childNode.getNodeType()) {
507 return (Text) childNode;
513 // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
514 private static Number parseNumber(final String numberText) {
515 if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
516 return Long.valueOf(numberText);
519 return Double.valueOf(numberText);