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