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