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;
44 * This class parses JSON elements from a GSON JsonReader. It disallows multiple elements of the same name unlike the
45 * default GSON JsonParser.
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;
55 private JsonParserStream(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext, final DataSchemaNode parentNode) {
56 this.schema = Preconditions.checkNotNull(schemaContext);
57 this.writer = DataSchemaNodeAwareAdaptor.forWriter(writer);
58 this.codecs = JSONCodecFactory.create(schemaContext);
59 this.parentNode = parentNode;
62 public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext, final SchemaNode parentNode ) {
63 if(parentNode instanceof RpcDefinition) {
64 return new JsonParserStream(writer, schemaContext, new RpcAsContainer((RpcDefinition) parentNode));
66 Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
67 return new JsonParserStream(writer, schemaContext, (DataSchemaNode) parentNode);
70 public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext) {
71 return new JsonParserStream(writer, schemaContext, schemaContext);
74 public JsonParserStream parse(final JsonReader reader) {
75 // code copied from gson's JsonParser and Stream classes
77 final boolean lenient = reader.isLenient();
78 reader.setLenient(true);
79 boolean isEmpty = true;
83 final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
84 read(reader, compositeNodeDataWithSchema);
85 compositeNodeDataWithSchema.write(writer);
88 } catch (final EOFException e) {
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);
103 reader.setLenient(lenient);
107 private void setValue(final AbstractNodeDataWithSchema parent, final String value) {
108 Preconditions.checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
109 parent.getSchema().getQName());
110 final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
111 Preconditions.checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
112 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
114 final Object translatedValue = translateValueByType(value, parentSimpleNode.getSchema());
115 parentSimpleNode.setValue(translatedValue);
118 public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
122 setValue(parent, in.nextString());
125 setValue(parent, Boolean.toString(in.nextBoolean()));
129 setValue(parent, null);
133 while (in.hasNext()) {
134 if (parent instanceof LeafNodeDataWithSchema) {
137 final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
144 final Set<String> namesakes = new HashSet<>();
147 * This allows parsing of incorrectly /as showcased/
148 * in testconf nesting of list items - eg.
149 * lists with one value are sometimes serialized
150 * without wrapping array.
153 if(isArray(parent)) {
154 parent = newArrayEntry(parent);
156 while (in.hasNext()) {
157 final String jsonElementName = in.nextName();
158 final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parent.getSchema());
159 final String localName = namespaceAndName.getName();
160 addNamespace(namespaceAndName.getUri());
161 if (namesakes.contains(jsonElementName)) {
162 throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
164 namesakes.add(jsonElementName);
165 final Deque<DataSchemaNode> childDataSchemaNodes = findSchemaNodeByNameAndNamespace(parent.getSchema(),
166 localName, getCurrentNamespace());
167 if (childDataSchemaNodes.isEmpty()) {
168 throw new IllegalStateException("Schema for node with name " + localName + " and namespace "
169 + getCurrentNamespace() + " doesn't exist.");
172 final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
174 * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
175 * will be able to load anyxml which conforms to YANG data using these
176 * parser, for other anyxml will be harder.
178 if (newChild instanceof AnyXmlNodeDataWithSchema) {
195 private static boolean isArray(final AbstractNodeDataWithSchema parent) {
196 return parent instanceof ListNodeDataWithSchema || parent instanceof LeafListNodeDataWithSchema;
199 private static AbstractNodeDataWithSchema newArrayEntry(final AbstractNodeDataWithSchema parent) {
200 AbstractNodeDataWithSchema newChild;
201 if (parent instanceof ListNodeDataWithSchema) {
202 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
203 } else if (parent instanceof LeafListNodeDataWithSchema) {
204 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
206 throw new IllegalStateException("Found an unexpected array nested under "+ parent.getSchema().getQName());
208 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
212 private Object translateValueByType(final String value, final DataSchemaNode node) {
213 if (node instanceof AnyXmlSchemaNode) {
215 * FIXME: Figure out some YANG extension dispatch, which will
216 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
221 return codecs.codecFor(node).deserialize(value);
224 private void removeNamespace() {
228 private void addNamespace(final URI namespace) {
229 namespaces.push(namespace);
232 private NamespaceAndName resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
233 final int lastIndexOfColon = childName.lastIndexOf(':');
234 String moduleNamePart = null;
235 String nodeNamePart = null;
236 URI namespace = null;
237 if (lastIndexOfColon != -1) {
238 moduleNamePart = childName.substring(0, lastIndexOfColon);
239 nodeNamePart = childName.substring(lastIndexOfColon + 1);
241 final Module m = schema.findModuleByName(moduleNamePart, null);
242 namespace = m == null ? null : m.getNamespace();
244 nodeNamePart = childName;
247 if (namespace == null) {
248 Set<URI> potentialUris = Collections.emptySet();
249 potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
250 if (potentialUris.contains(getCurrentNamespace())) {
251 namespace = getCurrentNamespace();
252 } else if (potentialUris.size() == 1) {
253 namespace = potentialUris.iterator().next();
254 } else if (potentialUris.size() > 1) {
255 throw new IllegalStateException("Choose suitable module name for element "+nodeNamePart+":"+toModuleNames(potentialUris));
256 } else if (potentialUris.isEmpty()) {
257 throw new IllegalStateException("Schema node with name "+nodeNamePart+" wasn't found under "+dataSchemaNode.getQName()+".");
261 return new NamespaceAndName(nodeNamePart, namespace);
264 private String toModuleNames(final Set<URI> potentialUris) {
265 final StringBuilder builder = new StringBuilder();
266 for (final URI potentialUri : potentialUris) {
267 builder.append("\n");
268 //FIXME how to get information about revision from JSON input? currently first available is used.
269 builder.append(schema.findModuleByNamespace(potentialUri).iterator().next().getName());
271 return builder.toString();
274 private Set<URI> resolveAllPotentialNamespaces(final String elementName, final DataSchemaNode dataSchemaNode) {
275 final Set<URI> potentialUris = new HashSet<>();
276 final Set<ChoiceSchemaNode> choices = new HashSet<>();
277 if (dataSchemaNode instanceof DataNodeContainer) {
278 for (final DataSchemaNode childSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
279 if (childSchemaNode instanceof ChoiceSchemaNode) {
280 choices.add((ChoiceSchemaNode)childSchemaNode);
281 } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
282 potentialUris.add(childSchemaNode.getQName().getNamespace());
286 for (final ChoiceSchemaNode choiceNode : choices) {
287 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
288 potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
292 return potentialUris;
295 private URI getCurrentNamespace() {
296 return namespaces.peek();
300 * Returns stack of schema nodes via which it was necessary to pass to get schema node with specified
301 * {@code childName} and {@code namespace}
303 * @param dataSchemaNode
306 * @return stack of schema nodes via which it was passed through. If found schema node is direct child then stack
307 * contains only one node. If it is found under choice and case then stack should contains 2*n+1 element
308 * (where n is number of choices through it was passed)
310 private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
311 final String childName, final URI namespace) {
312 final Deque<DataSchemaNode> result = new ArrayDeque<>();
313 final List<ChoiceSchemaNode> childChoices = new ArrayList<>();
314 DataSchemaNode potentialChildNode = null;
315 if (dataSchemaNode instanceof DataNodeContainer) {
316 for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
317 if (childNode instanceof ChoiceSchemaNode) {
318 childChoices.add((ChoiceSchemaNode) childNode);
320 final QName childQName = childNode.getQName();
322 if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
323 if (potentialChildNode == null ||
324 childQName.getRevision().after(potentialChildNode.getQName().getRevision())) {
325 potentialChildNode = childNode;
331 if (potentialChildNode != null) {
332 result.push(potentialChildNode);
336 // try to find data schema node in choice (looking for first match)
337 for (final ChoiceSchemaNode choiceNode : childChoices) {
338 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
339 final Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
341 if (!resultFromRecursion.isEmpty()) {
342 resultFromRecursion.push(concreteCase);
343 resultFromRecursion.push(choiceNode);
344 return resultFromRecursion;
351 private static class NamespaceAndName {
352 private final URI uri;
353 private final String name;
355 public NamespaceAndName(final String name, final URI uri) {
360 public String getName() {
364 public URI getUri() {
370 public void flush() throws IOException {
375 public void close() throws IOException {