d9d2fd1d0c1ce8bae87c309ab0dd9d7bb738bdce
[yangtools.git] / codec / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / JsonParserStream.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 java.util.Objects.requireNonNull;
11
12 import com.google.gson.JsonIOException;
13 import com.google.gson.JsonParseException;
14 import com.google.gson.JsonSyntaxException;
15 import com.google.gson.stream.JsonReader;
16 import com.google.gson.stream.MalformedJsonException;
17 import java.io.Closeable;
18 import java.io.EOFException;
19 import java.io.Flushable;
20 import java.io.IOException;
21 import java.util.AbstractMap.SimpleImmutableEntry;
22 import java.util.ArrayDeque;
23 import java.util.Deque;
24 import java.util.HashSet;
25 import java.util.Map.Entry;
26 import java.util.Set;
27 import javax.xml.transform.dom.DOMSource;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.yangtools.rfc8040.model.api.YangDataSchemaNode;
30 import org.opendaylight.yangtools.util.xml.UntrustedXML;
31 import org.opendaylight.yangtools.yang.common.XMLNamespace;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
33 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
34 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
35 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
36 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema.ChildReusePolicy;
37 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
38 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
39 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
40 import org.opendaylight.yangtools.yang.data.util.MultipleEntryDataWithSchema;
41 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
42 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
43 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
47 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
48 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
49 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
51 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Document;
55 import org.w3c.dom.Element;
56 import org.w3c.dom.Text;
57
58 /**
59  * This class parses JSON elements from a GSON JsonReader. It disallows multiple elements of the same name unlike the
60  * default GSON JsonParser.
61  */
62 public final class JsonParserStream implements Closeable, Flushable {
63     static final String ANYXML_ARRAY_ELEMENT_ID = "array-element";
64
65     private static final Logger LOG = LoggerFactory.getLogger(JsonParserStream.class);
66     private final Deque<XMLNamespace> namespaces = new ArrayDeque<>();
67     private final NormalizedNodeStreamWriter writer;
68     private final JSONCodecFactory codecs;
69     private final DataSchemaNode parentNode;
70
71     private final SchemaInferenceStack stack;
72
73     // TODO: consider class specialization to remove this field
74     private final boolean lenient;
75
76     private JsonParserStream(final NormalizedNodeStreamWriter writer, final JSONCodecFactory codecs,
77             final SchemaInferenceStack stack, final boolean lenient) {
78         this.writer = requireNonNull(writer);
79         this.codecs = requireNonNull(codecs);
80         this.stack = requireNonNull(stack);
81         this.lenient = lenient;
82
83         if (!stack.isEmpty()) {
84             final EffectiveStatement<?, ?> parent = stack.currentStatement();
85             if (parent instanceof DataSchemaNode data) {
86                 parentNode = data;
87             } else if (parent instanceof OperationDefinition oper) {
88                 parentNode = oper.toContainerLike();
89             } else if (parent instanceof NotificationDefinition notif) {
90                 parentNode = notif.toContainerLike();
91             } else if (parent instanceof YangDataSchemaNode yangData) {
92                 parentNode = yangData.toContainerLike();
93             } else {
94                 throw new IllegalArgumentException("Illegal parent node " + parent);
95             }
96         } else {
97             parentNode = stack.modelContext();
98         }
99     }
100
101     /**
102      * Create a new {@link JsonParserStream} backed by specified {@link NormalizedNodeStreamWriter}
103      * and {@link JSONCodecFactory}. The stream will be logically rooted at the top of the SchemaContext associated
104      * with the specified codec factory.
105      *
106      * @param writer NormalizedNodeStreamWriter to use for instantiation of normalized nodes
107      * @param codecFactory {@link JSONCodecFactory} to use for parsing leaves
108      * @return A new {@link JsonParserStream}
109      * @throws NullPointerException if any of the arguments are null
110      */
111     public static @NonNull JsonParserStream create(final @NonNull NormalizedNodeStreamWriter writer,
112             final @NonNull JSONCodecFactory codecFactory) {
113         return new JsonParserStream(writer, codecFactory,
114             SchemaInferenceStack.of(codecFactory.modelContext()), false);
115     }
116
117     /**
118      * Create a new {@link JsonParserStream} backed by specified {@link NormalizedNodeStreamWriter}
119      * and {@link JSONCodecFactory}. The stream will be logically rooted at the specified parent node.
120      *
121      * @param writer NormalizedNodeStreamWriter to use for instantiation of normalized nodes
122      * @param codecFactory {@link JSONCodecFactory} to use for parsing leaves
123      * @param parentNode Logical root node
124      * @return A new {@link JsonParserStream}
125      * @throws NullPointerException if any of the arguments are null
126      */
127     public static @NonNull JsonParserStream create(final @NonNull NormalizedNodeStreamWriter writer,
128             final @NonNull JSONCodecFactory codecFactory, final @NonNull EffectiveStatementInference parentNode) {
129         return new JsonParserStream(writer, codecFactory, SchemaInferenceStack.ofInference(parentNode), false);
130     }
131
132     /**
133      * Create a new {@link JsonParserStream} backed by specified {@link NormalizedNodeStreamWriter}
134      * and {@link JSONCodecFactory}. The stream will be logically rooted at the top of the SchemaContext associated
135      * with the specified codec factory.
136      *
137      * <p>
138      * Returned parser will treat incoming JSON data leniently:
139      * <ul>
140      *   <li>JSON elements referring to unknown constructs will be silently ignored</li>
141      * </ul>
142      *
143      * @param writer NormalizedNodeStreamWriter to use for instantiation of normalized nodes
144      * @param codecFactory {@link JSONCodecFactory} to use for parsing leaves
145      * @return A new {@link JsonParserStream}
146      * @throws NullPointerException if any of the arguments are null
147      */
148     public static @NonNull JsonParserStream createLenient(final @NonNull NormalizedNodeStreamWriter writer,
149             final @NonNull JSONCodecFactory codecFactory) {
150         return new JsonParserStream(writer, codecFactory,
151             SchemaInferenceStack.of(codecFactory.modelContext()), true);
152     }
153
154     /**
155      * Create a new {@link JsonParserStream} backed by specified {@link NormalizedNodeStreamWriter}
156      * and {@link JSONCodecFactory}. The stream will be logically rooted at the specified parent node.
157      *
158      * <p>
159      * Returned parser will treat incoming JSON data leniently:
160      * <ul>
161      *   <li>JSON elements referring to unknown constructs will be silently ignored</li>
162      * </ul>
163      *
164      * @param writer NormalizedNodeStreamWriter to use for instantiation of normalized nodes
165      * @param codecFactory {@link JSONCodecFactory} to use for parsing leaves
166      * @param parentNode Logical root node
167      * @return A new {@link JsonParserStream}
168      * @throws NullPointerException if any of the arguments are null
169      */
170     public static @NonNull JsonParserStream createLenient(final @NonNull NormalizedNodeStreamWriter writer,
171             final @NonNull JSONCodecFactory codecFactory, final @NonNull EffectiveStatementInference parentNode) {
172         return new JsonParserStream(writer, codecFactory, SchemaInferenceStack.ofInference(parentNode), true);
173     }
174
175     public JsonParserStream parse(final JsonReader reader) {
176         // code copied from gson's JsonParser and Stream classes
177
178         final boolean readerLenient = reader.isLenient();
179         reader.setLenient(true);
180         boolean isEmpty = true;
181         try {
182             reader.peek();
183             isEmpty = false;
184             // FIXME: this has a special-case bypass for SchemaContext, where we end up emitting just the child while
185             //        the usual of() would result in SchemaContext.NAME being the root
186             final var compositeNodeDataWithSchema = new CompositeNodeDataWithSchema<>(parentNode);
187             read(reader, compositeNodeDataWithSchema);
188             compositeNodeDataWithSchema.write(writer);
189
190             return this;
191         } catch (final EOFException e) {
192             if (isEmpty) {
193                 return this;
194             }
195             // The stream ended prematurely so it is likely a syntax error.
196             throw new JsonSyntaxException(e);
197         } catch (final MalformedJsonException | NumberFormatException e) {
198             throw new JsonSyntaxException(e);
199         } catch (final IOException e) {
200             throw new JsonIOException(e);
201         } catch (StackOverflowError | OutOfMemoryError e) {
202             throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
203         } finally {
204             reader.setLenient(readerLenient);
205         }
206     }
207
208     private void traverseAnyXmlValue(final JsonReader in, final Document doc, final Element parentElement)
209             throws IOException {
210         switch (in.peek()) {
211             case STRING:
212             case NUMBER:
213                 Text textNode = doc.createTextNode(in.nextString());
214                 parentElement.appendChild(textNode);
215                 break;
216             case BOOLEAN:
217                 textNode = doc.createTextNode(Boolean.toString(in.nextBoolean()));
218                 parentElement.appendChild(textNode);
219                 break;
220             case NULL:
221                 in.nextNull();
222                 textNode = doc.createTextNode("null");
223                 parentElement.appendChild(textNode);
224                 break;
225             case BEGIN_ARRAY:
226                 in.beginArray();
227                 while (in.hasNext()) {
228                     final var childElement = doc.createElement(ANYXML_ARRAY_ELEMENT_ID);
229                     parentElement.appendChild(childElement);
230                     traverseAnyXmlValue(in, doc, childElement);
231                 }
232                 in.endArray();
233                 break;
234             case BEGIN_OBJECT:
235                 in.beginObject();
236                 while (in.hasNext()) {
237                     final var childElement = doc.createElement(in.nextName());
238                     parentElement.appendChild(childElement);
239                     traverseAnyXmlValue(in, doc, childElement);
240                 }
241                 in.endObject();
242                 break;
243             default:
244                 break;
245         }
246     }
247
248     private void readAnyXmlValue(final JsonReader in, final AnyXmlNodeDataWithSchema parent,
249             final String anyXmlObjectName) throws IOException {
250         final var doc = UntrustedXML.newDocumentBuilder().newDocument();
251         final var rootElement = doc.createElementNS(getCurrentNamespace().toString(), anyXmlObjectName);
252         doc.appendChild(rootElement);
253         traverseAnyXmlValue(in, doc, rootElement);
254
255         parent.setValue(new DOMSource(doc.getDocumentElement()));
256     }
257
258     private void read(final JsonReader in, AbstractNodeDataWithSchema<?> parent) throws IOException {
259         switch (in.peek()) {
260             case STRING:
261             case NUMBER:
262                 setValue(parent, in.nextString());
263                 break;
264             case BOOLEAN:
265                 setValue(parent, Boolean.toString(in.nextBoolean()));
266                 break;
267             case NULL:
268                 in.nextNull();
269                 setValue(parent, null);
270                 break;
271             case BEGIN_ARRAY:
272                 in.beginArray();
273                 while (in.hasNext()) {
274                     if (parent instanceof LeafNodeDataWithSchema) {
275                         read(in, parent);
276                     } else {
277                         read(in, newArrayEntry(parent));
278                     }
279                 }
280                 in.endArray();
281                 return;
282             case BEGIN_OBJECT:
283                 final var namesakes = new HashSet<String>();
284                 in.beginObject();
285                 /*
286                  * This allows parsing of incorrectly /as showcased/
287                  * in testconf nesting of list items - eg.
288                  * lists with one value are sometimes serialized
289                  * without wrapping array.
290                  *
291                  */
292                 if (isArray(parent)) {
293                     parent = newArrayEntry(parent);
294                 }
295                 while (in.hasNext()) {
296                     final var jsonElementName = in.nextName();
297                     final var parentSchema = parent.getSchema();
298                     final var namespaceAndName = resolveNamespace(jsonElementName, parentSchema);
299                     final var localName = namespaceAndName.getKey();
300                     final var namespace = namespaceAndName.getValue();
301                     if (lenient && (localName == null || namespace == null)) {
302                         LOG.debug("Schema node with name {} was not found under {}", localName,
303                             parentSchema.getQName());
304                         in.skipValue();
305                         continue;
306                     }
307                     addNamespace(namespace);
308                     if (!namesakes.add(jsonElementName)) {
309                         throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
310                     }
311
312                     final var childDataSchemaNodes = ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema,
313                         localName, getCurrentNamespace());
314                     if (childDataSchemaNodes.isEmpty()) {
315                         throw new IllegalStateException(
316                             "Schema for node with name %s and namespace %s does not exist at %s".formatted(
317                                 localName, getCurrentNamespace(), parentSchema));
318                     }
319
320                     final var qname = childDataSchemaNodes.peekLast().getQName();
321                     final var newChild = ((CompositeNodeDataWithSchema<?>) parent)
322                             .addChild(childDataSchemaNodes, ChildReusePolicy.NOOP);
323                     if (newChild instanceof AnyXmlNodeDataWithSchema anyxml) {
324                         readAnyXmlValue(in, anyxml, jsonElementName);
325                     } else {
326                         stack.enterDataTree(qname);
327                         read(in, newChild);
328                         stack.exit();
329                     }
330                     removeNamespace();
331                 }
332                 in.endObject();
333                 return;
334             default:
335                 break;
336         }
337     }
338
339     private static boolean isArray(final AbstractNodeDataWithSchema<?> parent) {
340         return parent instanceof ListNodeDataWithSchema || parent instanceof LeafListNodeDataWithSchema;
341     }
342
343     private static AbstractNodeDataWithSchema<?> newArrayEntry(final AbstractNodeDataWithSchema<?> parent) {
344         if (parent instanceof MultipleEntryDataWithSchema<?> multiple) {
345             return multiple.newChildEntry();
346         }
347         throw new IllegalStateException("Found an unexpected array nested under " + parent.getSchema().getQName());
348     }
349
350     private void setValue(final AbstractNodeDataWithSchema<?> parent, final String value) {
351         if (!(parent instanceof SimpleNodeDataWithSchema<?> parentSimpleNode)) {
352             throw new IllegalArgumentException("Node " + parent.getSchema().getQName() + " is not a simple type");
353         }
354         final var prevValue = parentSimpleNode.getValue();
355         if (prevValue != null) {
356             throw new IllegalArgumentException("Node '%s' has already set its value to '%s'".formatted(
357                 parentSimpleNode.getSchema().getQName(), prevValue));
358         }
359
360         final var translatedValue = translateValueByType(value, parentSimpleNode.getSchema());
361         parentSimpleNode.setValue(translatedValue);
362     }
363
364     private Object translateValueByType(final String value, final DataSchemaNode node) {
365         if (node instanceof TypedDataSchemaNode typedNode) {
366             return codecs.codecFor(typedNode, stack).parseValue(value);
367         }
368         throw new IllegalArgumentException("Unexpected node " + node);
369     }
370
371     private void removeNamespace() {
372         namespaces.pop();
373     }
374
375     private void addNamespace(final XMLNamespace namespace) {
376         namespaces.push(namespace);
377     }
378
379     private Entry<String, XMLNamespace> resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
380         final int lastIndexOfColon = childName.lastIndexOf(':');
381         final String nodeNamePart;
382         XMLNamespace namespace;
383         if (lastIndexOfColon != -1) {
384             final var moduleNamePart = childName.substring(0, lastIndexOfColon);
385             nodeNamePart = childName.substring(lastIndexOfColon + 1);
386
387             final var m = codecs.modelContext().findModuleStatements(moduleNamePart).iterator();
388             namespace = m.hasNext() ? m.next().localQNameModule().namespace() : null;
389         } else {
390             nodeNamePart = childName;
391             namespace = null;
392         }
393
394         if (namespace == null) {
395             final var potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
396             if (potentialUris.contains(getCurrentNamespace())) {
397                 namespace = getCurrentNamespace();
398             } else if (potentialUris.size() == 1) {
399                 namespace = potentialUris.iterator().next();
400             } else if (potentialUris.size() > 1) {
401                 throw new IllegalStateException("Choose suitable module name for element " + nodeNamePart + ":"
402                         + toModuleNames(potentialUris));
403             } else if (potentialUris.isEmpty() && !lenient) {
404                 throw new IllegalStateException("Schema node with name " + nodeNamePart + " was not found under "
405                         + dataSchemaNode.getQName() + ".");
406             }
407         }
408
409         return new SimpleImmutableEntry<>(nodeNamePart, namespace);
410     }
411
412     private String toModuleNames(final Set<XMLNamespace> potentialUris) {
413         final var sb = new StringBuilder();
414         for (var potentialUri : potentialUris) {
415             sb.append('\n');
416             // FIXME how to get information about revision from JSON input? currently first available is used.
417             sb.append(codecs.modelContext().findModuleStatements(potentialUri).iterator().next()
418                 .argument().getLocalName());
419         }
420         return sb.toString();
421     }
422
423     private Set<XMLNamespace> resolveAllPotentialNamespaces(final String elementName,
424             final DataSchemaNode dataSchemaNode) {
425         final var potentialUris = new HashSet<XMLNamespace>();
426         final var choices = new HashSet<ChoiceSchemaNode>();
427         if (dataSchemaNode instanceof DataNodeContainer container) {
428             for (var childSchemaNode : container.getChildNodes()) {
429                 if (childSchemaNode instanceof ChoiceSchemaNode choice) {
430                     choices.add(choice);
431                 } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
432                     potentialUris.add(childSchemaNode.getQName().getNamespace());
433                 }
434             }
435
436             for (var choiceNode : choices) {
437                 for (var concreteCase : choiceNode.getCases()) {
438                     potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
439                 }
440             }
441         }
442         return potentialUris;
443     }
444
445     private XMLNamespace getCurrentNamespace() {
446         return namespaces.peek();
447     }
448
449     @Override
450     public void flush() throws IOException {
451         writer.flush();
452     }
453
454     @Override
455     public void close() throws IOException {
456         writer.flush();
457         writer.close();
458     }
459 }