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