2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.codec.gson;
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;
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;
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;
45 * This class parses JSON elements from a GSON JsonReader. It disallows multiple elements of the same name unlike the
46 * default GSON JsonParser.
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;
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;
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));
69 Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
70 return new JsonParserStream(writer, schemaContext, (DataSchemaNode) parentNode);
73 public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext) {
74 return new JsonParserStream(writer, schemaContext, schemaContext);
77 public JsonParserStream parse(final JsonReader reader) {
78 // code copied from gson's JsonParser and Stream classes
80 final boolean lenient = reader.isLenient();
81 reader.setLenient(true);
82 boolean isEmpty = true;
86 final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
87 read(reader, compositeNodeDataWithSchema);
88 compositeNodeDataWithSchema.write(writer);
91 } catch (final EOFException e) {
95 // The stream ended prematurely so it is likely a syntax error.
96 throw new JsonSyntaxException(e);
97 } catch (final MalformedJsonException e) {
98 throw new JsonSyntaxException(e);
99 } catch (final IOException e) {
100 throw new JsonIOException(e);
101 } catch (final NumberFormatException e) {
102 throw new JsonSyntaxException(e);
103 } catch (StackOverflowError | OutOfMemoryError e) {
104 throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
106 reader.setLenient(lenient);
110 private void setValue(final AbstractNodeDataWithSchema parent, final String value) {
111 Preconditions.checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
112 parent.getSchema().getQName());
113 final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
114 Preconditions.checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
115 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
117 final Object translatedValue = translateValueByType(value, parentSimpleNode.getSchema());
118 parentSimpleNode.setValue(translatedValue);
121 public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
125 setValue(parent, in.nextString());
128 setValue(parent, Boolean.toString(in.nextBoolean()));
132 setValue(parent, null);
136 while (in.hasNext()) {
137 if (parent instanceof LeafNodeDataWithSchema) {
140 final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
147 final Set<String> namesakes = new HashSet<>();
150 * This allows parsing of incorrectly /as showcased/
151 * in testconf nesting of list items - eg.
152 * lists with one value are sometimes serialized
153 * without wrapping array.
156 if(isArray(parent)) {
157 parent = newArrayEntry(parent);
159 while (in.hasNext()) {
160 final String jsonElementName = in.nextName();
161 DataSchemaNode parentSchema = parent.getSchema();
162 if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
163 parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
165 final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parentSchema);
166 final String localName = namespaceAndName.getName();
167 addNamespace(namespaceAndName.getUri());
168 if (namesakes.contains(jsonElementName)) {
169 throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
171 namesakes.add(jsonElementName);
173 final Deque<DataSchemaNode> childDataSchemaNodes = findSchemaNodeByNameAndNamespace(parentSchema,
174 localName, getCurrentNamespace());
175 if (childDataSchemaNodes.isEmpty()) {
176 throw new IllegalStateException("Schema for node with name " + localName + " and namespace "
177 + getCurrentNamespace() + " doesn't exist.");
180 final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
182 * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
183 * will be able to load anyxml which conforms to YANG data using these
184 * parser, for other anyxml will be harder.
186 if (newChild instanceof AnyXmlNodeDataWithSchema) {
203 private static boolean isArray(final AbstractNodeDataWithSchema parent) {
204 return parent instanceof ListNodeDataWithSchema || parent instanceof LeafListNodeDataWithSchema;
207 private static AbstractNodeDataWithSchema newArrayEntry(final AbstractNodeDataWithSchema parent) {
208 AbstractNodeDataWithSchema newChild;
209 if (parent instanceof ListNodeDataWithSchema) {
210 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
211 } else if (parent instanceof LeafListNodeDataWithSchema) {
212 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
214 throw new IllegalStateException("Found an unexpected array nested under "+ parent.getSchema().getQName());
216 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
220 private Object translateValueByType(final String value, final DataSchemaNode node) {
221 if (node instanceof AnyXmlSchemaNode) {
223 * FIXME: Figure out some YANG extension dispatch, which will
224 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
229 return codecs.codecFor(node).deserialize(value);
232 private void removeNamespace() {
236 private void addNamespace(final URI namespace) {
237 namespaces.push(namespace);
240 private NamespaceAndName resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
241 final int lastIndexOfColon = childName.lastIndexOf(':');
242 String moduleNamePart = null;
243 String nodeNamePart = null;
244 URI namespace = null;
245 if (lastIndexOfColon != -1) {
246 moduleNamePart = childName.substring(0, lastIndexOfColon);
247 nodeNamePart = childName.substring(lastIndexOfColon + 1);
249 final Module m = schema.findModuleByName(moduleNamePart, null);
250 namespace = m == null ? null : m.getNamespace();
252 nodeNamePart = childName;
255 if (namespace == null) {
256 Set<URI> potentialUris = Collections.emptySet();
257 potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
258 if (potentialUris.contains(getCurrentNamespace())) {
259 namespace = getCurrentNamespace();
260 } else if (potentialUris.size() == 1) {
261 namespace = potentialUris.iterator().next();
262 } else if (potentialUris.size() > 1) {
263 throw new IllegalStateException("Choose suitable module name for element "+nodeNamePart+":"+toModuleNames(potentialUris));
264 } else if (potentialUris.isEmpty()) {
265 throw new IllegalStateException("Schema node with name "+nodeNamePart+" wasn't found under "+dataSchemaNode.getQName()+".");
269 return new NamespaceAndName(nodeNamePart, namespace);
272 private String toModuleNames(final Set<URI> potentialUris) {
273 final StringBuilder builder = new StringBuilder();
274 for (final URI potentialUri : potentialUris) {
275 builder.append("\n");
276 //FIXME how to get information about revision from JSON input? currently first available is used.
277 builder.append(schema.findModuleByNamespace(potentialUri).iterator().next().getName());
279 return builder.toString();
282 private Set<URI> resolveAllPotentialNamespaces(final String elementName, final DataSchemaNode dataSchemaNode) {
283 final Set<URI> potentialUris = new HashSet<>();
284 final Set<ChoiceSchemaNode> choices = new HashSet<>();
285 if (dataSchemaNode instanceof DataNodeContainer) {
286 for (final DataSchemaNode childSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
287 if (childSchemaNode instanceof ChoiceSchemaNode) {
288 choices.add((ChoiceSchemaNode)childSchemaNode);
289 } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
290 potentialUris.add(childSchemaNode.getQName().getNamespace());
294 for (final ChoiceSchemaNode choiceNode : choices) {
295 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
296 potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
300 return potentialUris;
303 private URI getCurrentNamespace() {
304 return namespaces.peek();
308 * Returns stack of schema nodes via which it was necessary to pass to get schema node with specified
309 * {@code childName} and {@code namespace}
311 * @param dataSchemaNode
314 * @return stack of schema nodes via which it was passed through. If found schema node is direct child then stack
315 * contains only one node. If it is found under choice and case then stack should contains 2*n+1 element
316 * (where n is number of choices through it was passed)
318 private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
319 final String childName, final URI namespace) {
320 final Deque<DataSchemaNode> result = new ArrayDeque<>();
321 final List<ChoiceSchemaNode> childChoices = new ArrayList<>();
322 DataSchemaNode potentialChildNode = null;
323 if (dataSchemaNode instanceof DataNodeContainer) {
324 for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
325 if (childNode instanceof ChoiceSchemaNode) {
326 childChoices.add((ChoiceSchemaNode) childNode);
328 final QName childQName = childNode.getQName();
330 if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
331 if (potentialChildNode == null ||
332 childQName.getRevision().after(potentialChildNode.getQName().getRevision())) {
333 potentialChildNode = childNode;
339 if (potentialChildNode != null) {
340 result.push(potentialChildNode);
344 // try to find data schema node in choice (looking for first match)
345 for (final ChoiceSchemaNode choiceNode : childChoices) {
346 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
347 final Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
349 if (!resultFromRecursion.isEmpty()) {
350 resultFromRecursion.push(concreteCase);
351 resultFromRecursion.push(choiceNode);
352 return resultFromRecursion;
359 private static class NamespaceAndName {
360 private final URI uri;
361 private final String name;
363 public NamespaceAndName(final String name, final URI uri) {
368 public String getName() {
372 public URI getUri() {
378 public void flush() throws IOException {
383 public void close() throws IOException {