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.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;
42 * This class parses JSON elements from a GSON JsonReader. It disallows multiple elements of the same name unlike the
43 * default GSON JsonParser.
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;
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;
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));
64 Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
65 return new JsonParserStream(writer, schemaContext, (DataSchemaNode) parentNode);
68 public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext) {
69 return new JsonParserStream(writer, schemaContext, schemaContext);
72 public JsonParserStream parse(final JsonReader reader) {
73 // code copied from gson's JsonParser and Stream classes
75 final boolean lenient = reader.isLenient();
76 reader.setLenient(true);
77 boolean isEmpty = true;
81 final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
82 read(reader, compositeNodeDataWithSchema);
83 compositeNodeDataWithSchema.write(writer);
86 } catch (final EOFException e) {
90 // The stream ended prematurely so it is likely a syntax error.
91 throw new JsonSyntaxException(e);
92 } catch (final MalformedJsonException e) {
93 throw new JsonSyntaxException(e);
94 } catch (final IOException e) {
95 throw new JsonIOException(e);
96 } catch (final NumberFormatException e) {
97 throw new JsonSyntaxException(e);
98 } catch (StackOverflowError | OutOfMemoryError e) {
99 throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
101 reader.setLenient(lenient);
105 private void setValue(final AbstractNodeDataWithSchema parent, final String value) {
106 Preconditions.checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type", parent.getSchema().getQName());
108 final Object translatedValue = translateValueByType(value, parent.getSchema());
109 ((SimpleNodeDataWithSchema) parent).setValue(translatedValue);
112 public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
116 setValue(parent, in.nextString());
119 setValue(parent, Boolean.toString(in.nextBoolean()));
123 setValue(parent, null);
127 while (in.hasNext()) {
128 if (parent instanceof LeafNodeDataWithSchema) {
131 final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
138 final Set<String> namesakes = new HashSet<>();
141 * This allows parsing of incorrectly /as showcased/
142 * in testconf nesting of list items - eg.
143 * lists with one value are sometimes serialized
144 * without wrapping array.
147 if(isArray(parent)) {
148 parent = newArrayEntry(parent);
150 while (in.hasNext()) {
151 final String jsonElementName = in.nextName();
152 final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parent.getSchema());
153 final String localName = namespaceAndName.getName();
154 addNamespace(namespaceAndName.getUri());
155 if (namesakes.contains(jsonElementName)) {
156 throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
158 namesakes.add(jsonElementName);
159 final Deque<DataSchemaNode> childDataSchemaNodes = findSchemaNodeByNameAndNamespace(parent.getSchema(),
160 localName, getCurrentNamespace());
161 if (childDataSchemaNodes.isEmpty()) {
162 throw new IllegalStateException("Schema for node with name " + localName + " and namespace "
163 + getCurrentNamespace() + " doesn't exist.");
166 final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
168 * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
169 * will be able to load anyxml which conforms to YANG data using these
170 * parser, for other anyxml will be harder.
172 if (newChild instanceof AnyXmlNodeDataWithSchema) {
189 private static boolean isArray(final AbstractNodeDataWithSchema parent) {
190 return parent instanceof ListNodeDataWithSchema || parent instanceof LeafListNodeDataWithSchema;
193 private static AbstractNodeDataWithSchema newArrayEntry(final AbstractNodeDataWithSchema parent) {
194 AbstractNodeDataWithSchema newChild;
195 if (parent instanceof ListNodeDataWithSchema) {
196 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
197 } else if (parent instanceof LeafListNodeDataWithSchema) {
198 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
200 throw new IllegalStateException("Found an unexpected array nested under "+ parent.getSchema().getQName());
202 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
206 private Object translateValueByType(final String value, final DataSchemaNode node) {
207 if (node instanceof AnyXmlSchemaNode) {
209 * FIXME: Figure out some YANG extension dispatch, which will
210 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
215 return codecs.codecFor(node).deserialize(value);
218 private void removeNamespace() {
222 private void addNamespace(final URI namespace) {
223 namespaces.push(namespace);
226 private NamespaceAndName resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
227 final int lastIndexOfColon = childName.lastIndexOf(':');
228 String moduleNamePart = null;
229 String nodeNamePart = null;
230 URI namespace = null;
231 if (lastIndexOfColon != -1) {
232 moduleNamePart = childName.substring(0, lastIndexOfColon);
233 nodeNamePart = childName.substring(lastIndexOfColon + 1);
235 final Module m = schema.findModuleByName(moduleNamePart, null);
236 namespace = m == null ? null : m.getNamespace();
238 nodeNamePart = childName;
241 if (namespace == null) {
242 Set<URI> potentialUris = Collections.emptySet();
243 potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
244 if (potentialUris.contains(getCurrentNamespace())) {
245 namespace = getCurrentNamespace();
246 } else if (potentialUris.size() == 1) {
247 namespace = potentialUris.iterator().next();
248 } else if (potentialUris.size() > 1) {
249 throw new IllegalStateException("Choose suitable module name for element "+nodeNamePart+":"+toModuleNames(potentialUris));
250 } else if (potentialUris.isEmpty()) {
251 throw new IllegalStateException("Schema node with name "+nodeNamePart+" wasn't found under "+dataSchemaNode.getQName()+".");
255 return new NamespaceAndName(nodeNamePart, namespace);
258 private String toModuleNames(final Set<URI> potentialUris) {
259 final StringBuilder builder = new StringBuilder();
260 for (final URI potentialUri : potentialUris) {
261 builder.append("\n");
262 //FIXME how to get information about revision from JSON input? currently first available is used.
263 builder.append(schema.findModuleByNamespace(potentialUri).iterator().next().getName());
265 return builder.toString();
268 private Set<URI> resolveAllPotentialNamespaces(final String elementName, final DataSchemaNode dataSchemaNode) {
269 final Set<URI> potentialUris = new HashSet<>();
270 final Set<ChoiceSchemaNode> choices = new HashSet<>();
271 if (dataSchemaNode instanceof DataNodeContainer) {
272 for (final DataSchemaNode childSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
273 if (childSchemaNode instanceof ChoiceSchemaNode) {
274 choices.add((ChoiceSchemaNode)childSchemaNode);
275 } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
276 potentialUris.add(childSchemaNode.getQName().getNamespace());
280 for (final ChoiceSchemaNode choiceNode : choices) {
281 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
282 potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
286 return potentialUris;
289 private URI getCurrentNamespace() {
290 return namespaces.peek();
294 * Returns stack of schema nodes via which it was necessary to pass to get schema node with specified
295 * {@code childName} and {@code namespace}
297 * @param dataSchemaNode
300 * @return stack of schema nodes via which it was passed through. If found schema node is direct child then stack
301 * contains only one node. If it is found under choice and case then stack should contains 2*n+1 element
302 * (where n is number of choices through it was passed)
304 private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
305 final String childName, final URI namespace) {
306 final Deque<DataSchemaNode> result = new ArrayDeque<>();
307 final List<ChoiceSchemaNode> childChoices = new ArrayList<>();
308 DataSchemaNode potentialChildNode = null;
309 if (dataSchemaNode instanceof DataNodeContainer) {
310 for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
311 if (childNode instanceof ChoiceSchemaNode) {
312 childChoices.add((ChoiceSchemaNode) childNode);
314 final QName childQName = childNode.getQName();
316 if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
317 if (potentialChildNode == null ||
318 childQName.getRevision().after(potentialChildNode.getQName().getRevision())) {
319 potentialChildNode = childNode;
325 if (potentialChildNode != null) {
326 result.push(potentialChildNode);
330 // try to find data schema node in choice (looking for first match)
331 for (final ChoiceSchemaNode choiceNode : childChoices) {
332 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
333 final Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
335 if (!resultFromRecursion.isEmpty()) {
336 resultFromRecursion.push(concreteCase);
337 resultFromRecursion.push(choiceNode);
338 return resultFromRecursion;
345 private static class NamespaceAndName {
346 private final URI uri;
347 private final String name;
349 public NamespaceAndName(final String name, final URI uri) {
354 public String getName() {
358 public URI getUri() {
364 public void flush() throws IOException {
369 public void close() throws IOException {