Move MountPoint{Child,Context,ContextFactory}
[yangtools.git] / codec / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / JSONNormalizedNodeStreamWriter.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.codec.gson;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
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.HashSet;
18 import java.util.NoSuchElementException;
19 import java.util.regex.Pattern;
20 import javax.xml.transform.dom.DOMSource;
21 import org.checkerframework.checker.regex.qual.Regex;
22 import org.eclipse.jdt.annotation.Nullable;
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.MountPointContext;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedAnydata;
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.util.NormalizedNodeStreamWriterStack;
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.EffectiveModelContext;
39 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
43 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
44 import org.w3c.dom.Element;
45 import org.w3c.dom.Node;
46 import org.w3c.dom.NodeList;
47 import org.w3c.dom.Text;
48
49 /**
50  * This implementation will create JSON output as output stream.
51  *
52  * <p>
53  * Values of leaf and leaf-list are NOT translated according to codecs.
54  */
55 public abstract class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter,
56         StreamWriterMountPointExtension {
57     private static final class Exclusive extends JSONNormalizedNodeStreamWriter {
58         Exclusive(final JSONCodecFactory codecFactory, final NormalizedNodeStreamWriterStack tracker,
59                 final JsonWriter writer, final JSONStreamWriterRootContext rootContext) {
60             super(codecFactory, tracker, writer, rootContext);
61         }
62
63         @Override
64         public void close() throws IOException {
65             flush();
66             closeWriter();
67         }
68     }
69
70     private static final class Nested extends JSONNormalizedNodeStreamWriter {
71         Nested(final JSONCodecFactory codecFactory, final NormalizedNodeStreamWriterStack tracker,
72                 final JsonWriter writer, final JSONStreamWriterRootContext rootContext) {
73             super(codecFactory, tracker, writer, rootContext);
74         }
75
76         @Override
77         public void close() throws IOException {
78             flush();
79             // The caller "owns" the writer, let them close it
80         }
81     }
82
83     /**
84      * RFC6020 deviation: we are not required to emit empty containers unless they
85      * are marked as 'presence'.
86      */
87     private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
88
89     @Regex
90     private static final String NUMBER_STRING = "-?\\d+(\\.\\d+)?";
91     private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_STRING);
92
93     @Regex
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);
96
97     private final NormalizedNodeStreamWriterStack tracker;
98     private final JSONCodecFactory codecs;
99     private final JsonWriter writer;
100     private JSONStreamWriterContext context;
101
102     JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final NormalizedNodeStreamWriterStack tracker,
103             final JsonWriter writer, final JSONStreamWriterRootContext rootContext) {
104         this.writer = requireNonNull(writer);
105         codecs = requireNonNull(codecFactory);
106         this.tracker = requireNonNull(tracker);
107         context = requireNonNull(rootContext);
108     }
109
110     /**
111      * Create a new stream writer, which writes to the specified output stream.
112      *
113      * <p>
114      * The codec factory can be reused between multiple writers.
115      *
116      * <p>
117      * Returned writer is exclusive user of JsonWriter, which means it will start
118      * top-level JSON element and ends it.
119      *
120      * <p>
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
123      * the writer too.
124      *
125      * @param codecFactory JSON codec factory
126      * @param jsonWriter JsonWriter
127      * @return A stream writer instance
128      */
129     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
130             final JsonWriter jsonWriter) {
131         return createExclusiveWriter(codecFactory, jsonWriter, null);
132     }
133
134     /**
135      * Create a new stream writer, which writes to the specified output stream.
136      *
137      * <p>
138      * The codec factory can be reused between multiple writers.
139      *
140      * <p>
141      * Returned writer is exclusive user of JsonWriter, which means it will start
142      * top-level JSON element and ends it.
143      *
144      * <p>
145      * This instance of writer can be used only to emit one top level element,
146      * otherwise it will produce incorrect JSON. Closing this instance will close
147      * the writer too.
148      *
149      * @param codecFactory JSON codec factory
150      * @param jsonWriter JsonWriter
151      * @param initialNs Initial namespace, can be null
152      * @return A stream writer instance
153      */
154     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
155             final JsonWriter jsonWriter, final @Nullable XMLNamespace initialNs) {
156         return new Exclusive(codecFactory, NormalizedNodeStreamWriterStack.of(codecFactory.getEffectiveModelContext()),
157             jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
158     }
159
160     /**
161      * Create a new stream writer, which writes to the specified output stream.
162      *
163      * <p>
164      * The codec factory can be reused between multiple writers.
165      *
166      * <p>
167      * Returned writer is exclusive user of JsonWriter, which means it will start
168      * top-level JSON element and ends it.
169      *
170      * <p>
171      * This instance of writer can be used only to emit one top level element,
172      * otherwise it will produce incorrect JSON. Closing this instance will close
173      * the writer too.
174      *
175      * @param codecFactory JSON codec factory
176      * @param rootNode Root node inference
177      * @param initialNs Initial namespace
178      * @param jsonWriter JsonWriter
179      * @return A stream writer instance
180      */
181     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
182             final EffectiveStatementInference rootNode, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
183         return new Exclusive(codecFactory, NormalizedNodeStreamWriterStack.of(rootNode), jsonWriter,
184             new JSONStreamWriterExclusiveRootContext(initialNs));
185     }
186
187     /**
188      * Create a new stream writer, which writes to the specified output stream.
189      *
190      * <p>
191      * The codec factory can be reused between multiple writers.
192      *
193      * <p>
194      * Returned writer is exclusive user of JsonWriter, which means it will start
195      * top-level JSON element and ends it.
196      *
197      * <p>
198      * This instance of writer can be used only to emit one top level element,
199      * otherwise it will produce incorrect JSON. Closing this instance will close
200      * the writer too.
201      *
202      * @param codecFactory JSON codec factory
203      * @param path Schema Path
204      * @param initialNs Initial namespace
205      * @param jsonWriter JsonWriter
206      * @return A stream writer instance
207      */
208     public static NormalizedNodeStreamWriter createExclusiveWriter(final JSONCodecFactory codecFactory,
209             final Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
210         return new Exclusive(codecFactory,
211             NormalizedNodeStreamWriterStack.of(codecFactory.getEffectiveModelContext(), path), jsonWriter,
212             new JSONStreamWriterExclusiveRootContext(initialNs));
213     }
214
215     /**
216      * Create a new stream writer, which writes to the specified output stream.
217      *
218      * <p>
219      * The codec factory can be reused between multiple writers.
220      *
221      * <p>
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.
227      *
228      * @param codecFactory JSON codec factory
229      * @param jsonWriter JsonWriter
230      * @return A stream writer instance
231      */
232     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
233             final JsonWriter jsonWriter) {
234         return createNestedWriter(codecFactory, jsonWriter, null);
235     }
236
237     /**
238      * Create a new stream writer, which writes to the specified output stream.
239      *
240      * <p>
241      * The codec factory can be reused between multiple writers.
242      *
243      * <p>
244      * Returned writer can be used emit multiple top level element,
245      * but does not start / close parent JSON object, which must be done
246      * by user providing {@code jsonWriter} instance in order for
247      * JSON to be valid. Closing this instance <strong>will not</strong>
248      * close the wrapped writer; the caller must take care of that.
249      *
250      * @param codecFactory JSON codec factory
251      * @param initialNs Initial namespace
252      * @param jsonWriter JsonWriter
253      * @return A stream writer instance
254      */
255     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
256             final JsonWriter jsonWriter, final @Nullable XMLNamespace initialNs) {
257         return new Nested(codecFactory, NormalizedNodeStreamWriterStack.of(codecFactory.getEffectiveModelContext()),
258             jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
259     }
260
261     /**
262      * Create a new stream writer, which writes to the specified output stream.
263      *
264      * <p>
265      * The codec factory can be reused between multiple writers.
266      *
267      * <p>
268      * Returned writer can be used emit multiple top level element,
269      * but does not start / close parent JSON object, which must be done
270      * by user providing {@code jsonWriter} instance in order for
271      * JSON to be valid. Closing this instance <strong>will not</strong>
272      * close the wrapped writer; the caller must take care of that.
273      *
274      * @param codecFactory JSON codec factory
275      * @param path Schema Path
276      * @param initialNs Initial namespace
277      * @param jsonWriter JsonWriter
278      * @return A stream writer instance
279      */
280     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
281             final Absolute path, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
282         return new Nested(codecFactory,
283             NormalizedNodeStreamWriterStack.of(codecFactory.getEffectiveModelContext(), path), jsonWriter,
284             new JSONStreamWriterSharedRootContext(initialNs));
285     }
286
287     /**
288      * Create a new stream writer, which writes to the specified output stream.
289      *
290      * <p>
291      * The codec factory can be reused between multiple writers.
292      *
293      * <p>
294      * Returned writer can be used emit multiple top level element,
295      * but does not start / close parent JSON object, which must be done
296      * by user providing {@code jsonWriter} instance in order for
297      * JSON to be valid. Closing this instance <strong>will not</strong>
298      * close the wrapped writer; the caller must take care of that.
299      *
300      * @param codecFactory JSON codec factory
301      * @param rootNode Root node inference
302      * @param initialNs Initial namespace
303      * @param jsonWriter JsonWriter
304      * @return A stream writer instance
305      */
306     public static NormalizedNodeStreamWriter createNestedWriter(final JSONCodecFactory codecFactory,
307             final EffectiveStatementInference rootNode, final XMLNamespace initialNs, final JsonWriter jsonWriter) {
308         return new Nested(codecFactory, NormalizedNodeStreamWriterStack.of(rootNode), jsonWriter,
309             new JSONStreamWriterSharedRootContext(initialNs));
310     }
311
312     @Override
313     public ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
314         return ImmutableClassToInstanceMap.of(StreamWriterMountPointExtension.class, this);
315     }
316
317     @Override
318     public void startLeafNode(final NodeIdentifier name) throws IOException {
319         tracker.startLeafNode(name);
320         context.emittingChild(codecs.getEffectiveModelContext(), writer);
321         context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
322     }
323
324     @Override
325     public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
326         tracker.startLeafSet(name);
327         context = new JSONStreamWriterListContext(context, name);
328     }
329
330     @Override
331     public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
332         tracker.startLeafSetEntryNode(name);
333         context.emittingChild(codecs.getEffectiveModelContext(), writer);
334     }
335
336     @Override
337     public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
338         tracker.startLeafSet(name);
339         context = new JSONStreamWriterListContext(context, name);
340     }
341
342     /*
343      * Warning suppressed due to static final constant which triggers a warning
344      * for the call to schema.isPresenceContainer().
345      */
346     @Override
347     public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
348         final SchemaNode schema = tracker.startContainerNode(name);
349         final boolean isPresence = schema instanceof ContainerSchemaNode container
350             ? container.isPresenceContainer() : DEFAULT_EMIT_EMPTY_CONTAINERS;
351         context = new JSONStreamWriterNamedObjectContext(context, name, isPresence);
352     }
353
354     @Override
355     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
356         tracker.startList(name);
357         context = new JSONStreamWriterListContext(context, name);
358     }
359
360     @Override
361     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
362         tracker.startListItem(name);
363         context = new JSONStreamWriterObjectContext(context, name, DEFAULT_EMIT_EMPTY_CONTAINERS);
364     }
365
366     @Override
367     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
368         tracker.startList(name);
369         context = new JSONStreamWriterListContext(context, name);
370     }
371
372     @Override
373     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
374             throws IOException {
375         tracker.startListItem(identifier);
376         context = new JSONStreamWriterObjectContext(context, identifier, DEFAULT_EMIT_EMPTY_CONTAINERS);
377     }
378
379     @Override
380     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
381         tracker.startList(name);
382         context = new JSONStreamWriterListContext(context, name);
383     }
384
385     @Override
386     public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
387         tracker.startChoiceNode(name);
388         context = new JSONStreamWriterInvisibleContext(context);
389     }
390
391     @Override
392     public final void startAugmentationNode(final AugmentationIdentifier identifier) {
393         tracker.startAugmentationNode(identifier);
394         context = new JSONStreamWriterInvisibleContext(context);
395     }
396
397     @Override
398     public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
399         if (NormalizedAnydata.class.isAssignableFrom(objectModel)) {
400             tracker.startAnydataNode(name);
401             context.emittingChild(codecs.getEffectiveModelContext(), writer);
402             context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
403             return true;
404         }
405
406         return false;
407     }
408
409     @Override
410     public final NormalizedNodeStreamWriter startMountPoint(final MountPointIdentifier mountId,
411             final MountPointContext mountCtx) throws IOException {
412         final EffectiveModelContext ctx = mountCtx.getEffectiveModelContext();
413         return new Nested(codecs.rebaseTo(ctx), NormalizedNodeStreamWriterStack.of(ctx), writer,
414             new JSONStreamWriterSharedRootContext(context.getNamespace()));
415     }
416
417     @Override
418     public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
419         if (DOMSource.class.isAssignableFrom(objectModel)) {
420             tracker.startAnyxmlNode(name);
421             context.emittingChild(codecs.getEffectiveModelContext(), writer);
422             context.writeChildJsonIdentifier(codecs.getEffectiveModelContext(), writer, name.getNodeType());
423             return true;
424         }
425         return false;
426     }
427
428     @Override
429     public final void endNode() throws IOException {
430         tracker.endNode();
431         context = context.endNode(codecs.getEffectiveModelContext(), writer);
432     }
433
434     @Override
435     public final void flush() throws IOException {
436         writer.flush();
437     }
438
439     final void closeWriter() throws IOException {
440         if (!(context instanceof JSONStreamWriterRootContext)) {
441             throw new IOException("Unexpected root context " + context);
442         }
443
444         context.endNode(codecs.getEffectiveModelContext(), writer);
445         writer.close();
446     }
447
448     @Override
449     public void scalarValue(final Object value) throws IOException {
450         final Object current = tracker.getParent();
451         if (current instanceof TypedDataSchemaNode typed) {
452             writeValue(value, codecs.codecFor(typed, tracker));
453         } else if (current instanceof AnydataSchemaNode) {
454             writeAnydataValue(value);
455         } else {
456             throw new IllegalStateException(String.format("Cannot emit scalar %s for %s", value, current));
457         }
458     }
459
460     @Override
461     public void domSourceValue(final DOMSource value) throws IOException {
462         final Object current = tracker.getParent();
463         checkState(current instanceof AnyxmlSchemaNode, "Cannot emit DOMSource %s for %s", value, current);
464         // FIXME: should have a codec based on this :)
465         writeAnyXmlValue(value);
466     }
467
468     @SuppressWarnings("unchecked")
469     private void writeValue(final Object value, final JSONCodec<?> codec) throws IOException {
470         ((JSONCodec<Object>) codec).writeValue(writer, value);
471     }
472
473     private void writeAnydataValue(final Object value) throws IOException {
474         if (value instanceof NormalizedAnydata normalized) {
475             writeNormalizedAnydata(normalized);
476         } else {
477             throw new IllegalStateException("Unexpected anydata value " + value);
478         }
479     }
480
481     private void writeNormalizedAnydata(final NormalizedAnydata anydata) throws IOException {
482         // Adjust state to point to parent node and ensure it can handle data tree nodes
483         final SchemaInferenceStack.Inference inference;
484         try {
485             final SchemaInferenceStack stack = SchemaInferenceStack.ofInference(anydata.getInference());
486             stack.exitToDataTree();
487             inference = stack.toInference();
488         } catch (IllegalArgumentException | IllegalStateException | NoSuchElementException e) {
489             throw new IOException("Cannot emit " + anydata, e);
490         }
491
492         anydata.writeTo(JSONNormalizedNodeStreamWriter.createNestedWriter(
493             codecs.rebaseTo(inference.getEffectiveModelContext()), inference, context.getNamespace(), writer));
494     }
495
496     private void writeAnyXmlValue(final DOMSource anyXmlValue) throws IOException {
497         writeXmlNode(anyXmlValue.getNode());
498     }
499
500     private void writeXmlNode(final Node node) throws IOException {
501         if (isArrayElement(node)) {
502             writeArrayContent(node);
503             return;
504         }
505         final Element firstChildElement = getFirstChildElement(node);
506         if (firstChildElement == null) {
507             writeXmlValue(node);
508         } else {
509             writeObjectContent(firstChildElement);
510         }
511     }
512
513     private void writeArrayContent(final Node node) throws IOException {
514         writer.beginArray();
515         handleArray(node);
516         writer.endArray();
517     }
518
519     private void writeObjectContent(final Element firstChildElement) throws IOException {
520         writer.beginObject();
521         writeObject(firstChildElement);
522         writer.endObject();
523     }
524
525     private static boolean isArrayElement(final Node node) {
526         if (Node.ELEMENT_NODE == node.getNodeType()) {
527             final String nodeName = node.getNodeName();
528             for (Node nextNode = node.getNextSibling(); nextNode != null; nextNode = nextNode.getNextSibling()) {
529                 if (Node.ELEMENT_NODE == nextNode.getNodeType() && nodeName.equals(nextNode.getNodeName())) {
530                     return true;
531                 }
532             }
533         }
534         return false;
535     }
536
537     private void handleArray(final Node node) throws IOException {
538         final Element parentNode = (Element)node.getParentNode();
539         final NodeList elementsList = parentNode.getElementsByTagName(node.getNodeName());
540         for (int i = 0, length = elementsList.getLength(); i < length; i++) {
541             final Node arrayElement = elementsList.item(i);
542             final Element parent = (Element)arrayElement.getParentNode();
543             if (parentNode.isSameNode(parent)) {
544                 final Element firstChildElement = getFirstChildElement(arrayElement);
545                 if (firstChildElement != null) {
546                     writeObjectContent(firstChildElement);
547                 } else {
548                     // It may be scalar
549                     writeXmlValue(arrayElement);
550                 }
551             }
552         }
553     }
554
555     private void writeObject(Node node) throws IOException {
556         final var previousNodeNames = new HashSet<String>();
557         while (node != null) {
558             if (Node.ELEMENT_NODE == node.getNodeType()) {
559                 final var nodeName = node.getNodeName();
560                 if (previousNodeNames.add(nodeName)) {
561                     writer.name(nodeName);
562                     writeXmlNode(node);
563                 }
564             }
565             node = node.getNextSibling();
566         }
567     }
568
569     private void writeXmlValue(final Node node) throws IOException {
570         Text firstChild = getFirstChildText(node);
571         String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
572         childNodeText = childNodeText != null ? childNodeText.trim() : "";
573
574         if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
575             writer.value(parseNumber(childNodeText));
576             return;
577         }
578         switch (childNodeText) {
579             case "null" -> writer.nullValue();
580             case "false" -> writer.value(false);
581             case "true" -> writer.value(true);
582             default -> writer.value(childNodeText);
583         }
584     }
585
586     private static Element getFirstChildElement(final Node node) {
587         final NodeList children = node.getChildNodes();
588         for (int i = 0, length = children.getLength(); i < length; i++) {
589             final Node childNode = children.item(i);
590             if (Node.ELEMENT_NODE == childNode.getNodeType()) {
591                 return (Element) childNode;
592             }
593         }
594         return null;
595     }
596
597     private static Text getFirstChildText(final Node node) {
598         final NodeList children = node.getChildNodes();
599         for (int i = 0, length = children.getLength(); i < length; i++) {
600             final Node childNode = children.item(i);
601             if (Node.TEXT_NODE == childNode.getNodeType()) {
602                 return (Text) childNode;
603             }
604         }
605         return null;
606     }
607
608     // json numbers are 64 bit wide floating point numbers - in java terms it is either long or double
609     private static Number parseNumber(final String numberText) {
610         if (NOT_DECIMAL_NUMBER_PATTERN.matcher(numberText).matches()) {
611             return Long.valueOf(numberText);
612         }
613
614         return Double.valueOf(numberText);
615     }
616 }