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