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