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