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 | 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);
104 reader.setLenient(lenient);
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());
115 final Object translatedValue = translateValueByType(value, parentSimpleNode.getSchema());
116 parentSimpleNode.setValue(translatedValue);
119 public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
123 setValue(parent, in.nextString());
126 setValue(parent, Boolean.toString(in.nextBoolean()));
130 setValue(parent, null);
134 while (in.hasNext()) {
135 if (parent instanceof LeafNodeDataWithSchema) {
138 final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
145 final Set<String> namesakes = new HashSet<>();
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.
154 if(isArray(parent)) {
155 parent = newArrayEntry(parent);
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();
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.");
169 namesakes.add(jsonElementName);
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.");
178 final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
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.
184 if (newChild instanceof AnyXmlNodeDataWithSchema) {
201 private static boolean isArray(final AbstractNodeDataWithSchema parent) {
202 return parent instanceof ListNodeDataWithSchema || parent instanceof LeafListNodeDataWithSchema;
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());
212 throw new IllegalStateException("Found an unexpected array nested under "+ parent.getSchema().getQName());
214 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
218 private Object translateValueByType(final String value, final DataSchemaNode node) {
219 if (node instanceof AnyXmlSchemaNode) {
221 * FIXME: Figure out some YANG extension dispatch, which will
222 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
227 return codecs.codecFor(node).deserialize(value);
230 private void removeNamespace() {
234 private void addNamespace(final URI namespace) {
235 namespaces.push(namespace);
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);
247 final Module m = schema.findModuleByName(moduleNamePart, null);
248 namespace = m == null ? null : m.getNamespace();
250 nodeNamePart = childName;
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()+".");
267 return new NamespaceAndName(nodeNamePart, namespace);
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());
277 return builder.toString();
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());
292 for (final ChoiceSchemaNode choiceNode : choices) {
293 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
294 potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
298 return potentialUris;
301 private URI getCurrentNamespace() {
302 return namespaces.peek();
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}
309 * @param dataSchemaNode
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)
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);
326 final QName childQName = childNode.getQName();
328 if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
329 if (potentialChildNode == null ||
330 childQName.getRevision().after(potentialChildNode.getQName().getRevision())) {
331 potentialChildNode = childNode;
337 if (potentialChildNode != null) {
338 result.push(potentialChildNode);
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,
347 if (!resultFromRecursion.isEmpty()) {
348 resultFromRecursion.push(concreteCase);
349 resultFromRecursion.push(choiceNode);
350 return resultFromRecursion;
357 private static class NamespaceAndName {
358 private final URI uri;
359 private final String name;
361 public NamespaceAndName(final String name, final URI uri) {
366 public String getName() {
370 public URI getUri() {
376 public void flush() throws IOException {
381 public void close() throws IOException {