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