Bug 3874: Support of yang modeled AnyXML - JSON deserialization
[yangtools.git] / yang / 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 com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
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.net.URI;
22 import java.util.ArrayDeque;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.Deque;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Set;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.DataSchemaNodeAwareAdaptor;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.SchemaAwareNormalizedNodeStreamWriter;
33 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
35 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
37 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.Module;
39 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
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.YangModeledAnyXmlSchemaNode;
43
44 /**
45  * This class parses JSON elements from a GSON JsonReader. It disallows multiple elements of the same name unlike the
46  * default GSON JsonParser.
47  */
48 @Beta
49 public final class JsonParserStream implements Closeable, Flushable {
50     private final Deque<URI> namespaces = new ArrayDeque<>();
51     private final SchemaAwareNormalizedNodeStreamWriter writer;
52     private final JSONCodecFactory codecs;
53     private final SchemaContext schema;
54     private final DataSchemaNode parentNode;
55
56     private JsonParserStream(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
57             final DataSchemaNode parentNode) {
58         this.schema = Preconditions.checkNotNull(schemaContext);
59         this.writer = DataSchemaNodeAwareAdaptor.forWriter(writer);
60         this.codecs = JSONCodecFactory.create(schemaContext);
61         this.parentNode = parentNode;
62     }
63
64     public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
65             final SchemaNode parentNode ) {
66         if (parentNode instanceof RpcDefinition) {
67             return new JsonParserStream(writer, schemaContext, new RpcAsContainer((RpcDefinition) parentNode));
68         }
69         Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
70         return new JsonParserStream(writer, schemaContext, (DataSchemaNode) parentNode);
71     }
72
73     public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext) {
74         return new JsonParserStream(writer, schemaContext, schemaContext);
75     }
76
77     public JsonParserStream parse(final JsonReader reader) {
78         // code copied from gson's JsonParser and Stream classes
79
80         final boolean lenient = reader.isLenient();
81         reader.setLenient(true);
82         boolean isEmpty = true;
83         try {
84             reader.peek();
85             isEmpty = false;
86             final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
87             read(reader, compositeNodeDataWithSchema);
88             compositeNodeDataWithSchema.write(writer);
89
90             return this;
91         } catch (final EOFException e) {
92             if (isEmpty) {
93                 return this;
94             }
95             // The stream ended prematurely so it is likely a syntax error.
96             throw new JsonSyntaxException(e);
97         } catch (final MalformedJsonException e) {
98             throw new JsonSyntaxException(e);
99         } catch (final IOException e) {
100             throw new JsonIOException(e);
101         } catch (final NumberFormatException e) {
102             throw new JsonSyntaxException(e);
103         } catch (StackOverflowError | OutOfMemoryError e) {
104             throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
105         } finally {
106             reader.setLenient(lenient);
107         }
108     }
109
110     private void setValue(final AbstractNodeDataWithSchema parent, final String value) {
111         Preconditions.checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
112                 parent.getSchema().getQName());
113         final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
114         Preconditions.checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
115                 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
116
117         final Object translatedValue = translateValueByType(value, parentSimpleNode.getSchema());
118         parentSimpleNode.setValue(translatedValue);
119     }
120
121     public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
122         switch (in.peek()) {
123         case STRING:
124         case NUMBER:
125             setValue(parent, in.nextString());
126             break;
127         case BOOLEAN:
128             setValue(parent, Boolean.toString(in.nextBoolean()));
129             break;
130         case NULL:
131             in.nextNull();
132             setValue(parent, null);
133             break;
134         case BEGIN_ARRAY:
135             in.beginArray();
136             while (in.hasNext()) {
137                 if (parent instanceof LeafNodeDataWithSchema) {
138                     read(in, parent);
139                 } else {
140                     final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
141                     read(in, newChild);
142                 }
143             }
144             in.endArray();
145             return;
146         case BEGIN_OBJECT:
147             final Set<String> namesakes = new HashSet<>();
148             in.beginObject();
149             /*
150              * This allows parsing of incorrectly /as showcased/
151              * in testconf nesting of list items - eg.
152              * lists with one value are sometimes serialized
153              * without wrapping array.
154              *
155              */
156             if(isArray(parent)) {
157                 parent = newArrayEntry(parent);
158             }
159             while (in.hasNext()) {
160                 final String jsonElementName = in.nextName();
161                 DataSchemaNode parentSchema = parent.getSchema();
162                 if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
163                     parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
164                 }
165                 final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parentSchema);
166                 final String localName = namespaceAndName.getName();
167                 addNamespace(namespaceAndName.getUri());
168                 if (namesakes.contains(jsonElementName)) {
169                     throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
170                 }
171                 namesakes.add(jsonElementName);
172
173                 final Deque<DataSchemaNode> childDataSchemaNodes = findSchemaNodeByNameAndNamespace(parentSchema,
174                         localName, getCurrentNamespace());
175                 if (childDataSchemaNodes.isEmpty()) {
176                     throw new IllegalStateException("Schema for node with name " + localName + " and namespace "
177                             + getCurrentNamespace() + " doesn't exist.");
178                 }
179
180                 final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
181                 /*
182                  * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
183                  * will be able to load anyxml which conforms to YANG data using these
184                  * parser, for other anyxml will be harder.
185                  */
186                 if (newChild instanceof AnyXmlNodeDataWithSchema) {
187                     in.skipValue();
188                 } else {
189                     read(in, newChild);
190                 }
191                 removeNamespace();
192             }
193             in.endObject();
194             return;
195         case END_DOCUMENT:
196         case NAME:
197         case END_OBJECT:
198         case END_ARRAY:
199             break;
200         }
201     }
202
203     private static boolean isArray(final AbstractNodeDataWithSchema parent) {
204         return parent instanceof ListNodeDataWithSchema || parent instanceof LeafListNodeDataWithSchema;
205     }
206
207     private static AbstractNodeDataWithSchema newArrayEntry(final AbstractNodeDataWithSchema parent) {
208         AbstractNodeDataWithSchema newChild;
209         if (parent instanceof ListNodeDataWithSchema) {
210             newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
211         } else if (parent instanceof LeafListNodeDataWithSchema) {
212             newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
213         } else {
214             throw new IllegalStateException("Found an unexpected array nested under "+ parent.getSchema().getQName());
215         }
216         ((CompositeNodeDataWithSchema) parent).addChild(newChild);
217         return newChild;
218     }
219
220     private Object translateValueByType(final String value, final DataSchemaNode node) {
221         if (node instanceof AnyXmlSchemaNode) {
222             /*
223              *  FIXME: Figure out some YANG extension dispatch, which will
224              *  reuse JSON parsing or XML parsing - anyxml is not well-defined in
225              * JSON.
226              */
227             return value;
228         }
229         return codecs.codecFor(node).deserialize(value);
230     }
231
232     private void removeNamespace() {
233         namespaces.pop();
234     }
235
236     private void addNamespace(final URI namespace) {
237         namespaces.push(namespace);
238     }
239
240     private NamespaceAndName resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
241         final int lastIndexOfColon = childName.lastIndexOf(':');
242         String moduleNamePart = null;
243         String nodeNamePart = null;
244         URI namespace = null;
245         if (lastIndexOfColon != -1) {
246             moduleNamePart = childName.substring(0, lastIndexOfColon);
247             nodeNamePart = childName.substring(lastIndexOfColon + 1);
248
249             final Module m = schema.findModuleByName(moduleNamePart, null);
250             namespace = m == null ? null : m.getNamespace();
251         } else {
252             nodeNamePart = childName;
253         }
254
255         if (namespace == null) {
256             Set<URI> potentialUris = Collections.emptySet();
257             potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
258             if (potentialUris.contains(getCurrentNamespace())) {
259                 namespace = getCurrentNamespace();
260             } else if (potentialUris.size() == 1) {
261                 namespace = potentialUris.iterator().next();
262             } else if (potentialUris.size() > 1) {
263                 throw new IllegalStateException("Choose suitable module name for element "+nodeNamePart+":"+toModuleNames(potentialUris));
264             } else if (potentialUris.isEmpty()) {
265                 throw new IllegalStateException("Schema node with name "+nodeNamePart+" wasn't found under "+dataSchemaNode.getQName()+".");
266             }
267         }
268
269         return new NamespaceAndName(nodeNamePart, namespace);
270     }
271
272     private String toModuleNames(final Set<URI> potentialUris) {
273         final StringBuilder builder = new StringBuilder();
274         for (final URI potentialUri : potentialUris) {
275             builder.append("\n");
276             //FIXME how to get information about revision from JSON input? currently first available is used.
277             builder.append(schema.findModuleByNamespace(potentialUri).iterator().next().getName());
278         }
279         return builder.toString();
280     }
281
282     private Set<URI> resolveAllPotentialNamespaces(final String elementName, final DataSchemaNode dataSchemaNode) {
283         final Set<URI> potentialUris = new HashSet<>();
284         final Set<ChoiceSchemaNode> choices = new HashSet<>();
285         if (dataSchemaNode instanceof DataNodeContainer) {
286             for (final DataSchemaNode childSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
287                 if (childSchemaNode instanceof ChoiceSchemaNode) {
288                     choices.add((ChoiceSchemaNode)childSchemaNode);
289                 } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
290                     potentialUris.add(childSchemaNode.getQName().getNamespace());
291                 }
292             }
293
294             for (final ChoiceSchemaNode choiceNode : choices) {
295                 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
296                     potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
297                 }
298             }
299         }
300         return potentialUris;
301     }
302
303     private URI getCurrentNamespace() {
304         return namespaces.peek();
305     }
306
307     /**
308      * Returns stack of schema nodes via which it was necessary to pass to get schema node with specified
309      * {@code childName} and {@code namespace}
310      *
311      * @param dataSchemaNode
312      * @param childName
313      * @param namespace
314      * @return stack of schema nodes via which it was passed through. If found schema node is direct child then stack
315      *         contains only one node. If it is found under choice and case then stack should contains 2*n+1 element
316      *         (where n is number of choices through it was passed)
317      */
318     private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
319             final String childName, final URI namespace) {
320         final Deque<DataSchemaNode> result = new ArrayDeque<>();
321         final List<ChoiceSchemaNode> childChoices = new ArrayList<>();
322         DataSchemaNode potentialChildNode = null;
323         if (dataSchemaNode instanceof DataNodeContainer) {
324             for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
325                 if (childNode instanceof ChoiceSchemaNode) {
326                     childChoices.add((ChoiceSchemaNode) childNode);
327                 } else {
328                     final QName childQName = childNode.getQName();
329
330                     if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
331                         if (potentialChildNode == null ||
332                                 childQName.getRevision().after(potentialChildNode.getQName().getRevision())) {
333                             potentialChildNode = childNode;
334                         }
335                     }
336                 }
337             }
338         }
339         if (potentialChildNode != null) {
340             result.push(potentialChildNode);
341             return result;
342         }
343
344         // try to find data schema node in choice (looking for first match)
345         for (final ChoiceSchemaNode choiceNode : childChoices) {
346             for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
347                 final Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
348                         namespace);
349                 if (!resultFromRecursion.isEmpty()) {
350                     resultFromRecursion.push(concreteCase);
351                     resultFromRecursion.push(choiceNode);
352                     return resultFromRecursion;
353                 }
354             }
355         }
356         return result;
357     }
358
359     private static class NamespaceAndName {
360         private final URI uri;
361         private final String name;
362
363         public NamespaceAndName(final String name, final URI uri) {
364             this.name = name;
365             this.uri = uri;
366         }
367
368         public String getName() {
369             return name;
370         }
371
372         public URI getUri() {
373             return uri;
374         }
375     }
376
377     @Override
378     public void flush() throws IOException {
379         writer.flush();
380     }
381
382     @Override
383     public void close() throws IOException {
384         writer.flush();
385         writer.close();
386     }
387 }