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.Date;
26 import java.util.Deque;
27 import java.util.HashSet;
28 import java.util.List;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
34 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.Module;
38 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
43 * This class parses JSON elements from a GSON JsonReader. It disallows multiple elements of the same name unlike the
44 * default GSON JsonParser.
47 public final class JsonParserStream implements Closeable, Flushable {
48 private final Deque<URI> namespaces = new ArrayDeque<>();
49 private final NormalizedNodeStreamWriter writer;
50 private final JSONCodecFactory codecs;
51 private final SchemaContext schema;
52 private final DataSchemaNode parentNode;
54 private JsonParserStream(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext, final DataSchemaNode parentNode) {
55 this.schema = Preconditions.checkNotNull(schemaContext);
56 this.writer = Preconditions.checkNotNull(writer);
57 this.codecs = JSONCodecFactory.create(schemaContext);
58 this.parentNode = parentNode;
61 public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext, final SchemaNode parentNode ) {
62 if(parentNode instanceof RpcDefinition) {
63 return new JsonParserStream(writer, schemaContext, new RpcAsContainer((RpcDefinition) parentNode));
65 Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
66 return new JsonParserStream(writer, schemaContext, (DataSchemaNode) parentNode);
69 public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext) {
70 return new JsonParserStream(writer, schemaContext, schemaContext);
73 public JsonParserStream parse(final JsonReader reader) throws JsonIOException, JsonSyntaxException {
74 // code copied from gson's JsonParser and Stream classes
76 final boolean lenient = reader.isLenient();
77 reader.setLenient(true);
78 boolean isEmpty = true;
82 final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
83 read(reader, compositeNodeDataWithSchema);
84 compositeNodeDataWithSchema.write(writer);
87 // return read(reader);
88 } catch (final EOFException e) {
91 // return JsonNull.INSTANCE;
93 // The stream ended prematurely so it is likely a syntax error.
94 throw new JsonSyntaxException(e);
95 } catch (final MalformedJsonException e) {
96 throw new JsonSyntaxException(e);
97 } catch (final IOException e) {
98 throw new JsonIOException(e);
99 } catch (final NumberFormatException e) {
100 throw new JsonSyntaxException(e);
101 } catch (StackOverflowError | OutOfMemoryError e) {
102 throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
104 reader.setLenient(lenient);
108 private final void setValue(final AbstractNodeDataWithSchema parent, final String value) {
109 Preconditions.checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type", parent);
111 final Object translatedValue = translateValueByType(value, parent.getSchema());
112 ((SimpleNodeDataWithSchema) parent).setValue(translatedValue);
115 public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
119 setValue(parent, in.nextString());
122 setValue(parent, Boolean.toString(in.nextBoolean()));
126 setValue(parent, null);
130 while (in.hasNext()) {
131 final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
137 final Set<String> namesakes = new HashSet<>();
140 * This allows parsing of incorrectly /as showcased/
141 * in testconf nesting of list items - eg.
142 * lists with one value are sometimes serialized
143 * without wrapping array.
146 if(isArray(parent)) {
147 parent = newArrayEntry(parent);
149 while (in.hasNext()) {
150 final String jsonElementName = in.nextName();
151 final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parent.getSchema());
152 final String localName = namespaceAndName.getName();
153 addNamespace(namespaceAndName.getUri());
154 if (namesakes.contains(jsonElementName)) {
155 throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
157 namesakes.add(jsonElementName);
158 final Deque<DataSchemaNode> childDataSchemaNodes = findSchemaNodeByNameAndNamespace(parent.getSchema(),
159 localName, getCurrentNamespace());
160 if (childDataSchemaNodes.isEmpty()) {
161 throw new IllegalStateException("Schema for node with name " + localName + " and namespace "
162 + getCurrentNamespace() + " doesn't exist.");
165 final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
167 * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
168 * will be able to load anyxml which conforms to YANG data using these
169 * parser, for other anyxml will be harder.
171 if (newChild instanceof AnyXmlNodeDataWithSchema) {
188 private boolean isArray(final AbstractNodeDataWithSchema parent) {
189 return parent instanceof ListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema;
192 private AbstractNodeDataWithSchema newArrayEntry(final AbstractNodeDataWithSchema parent) {
193 AbstractNodeDataWithSchema newChild;
194 if (parent instanceof ListNodeDataWithSchema) {
195 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
196 } else if (parent instanceof LeafListNodeDataWithSchema) {
197 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
199 throw new IllegalStateException("Incorrec nesting caused by parser.");
201 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
205 private Object translateValueByType(final String value, final DataSchemaNode node) {
206 if (node instanceof AnyXmlSchemaNode) {
208 * FIXME: Figure out some YANG extension dispatch, which will
209 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
214 return codecs.codecFor(node).deserialize(value);
217 private void removeNamespace() {
221 private void addNamespace(final URI namespace) {
222 namespaces.push(namespace);
225 private NamespaceAndName resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
226 final int lastIndexOfColon = childName.lastIndexOf(':');
227 String moduleNamePart = null;
228 String nodeNamePart = null;
229 URI namespace = null;
230 if (lastIndexOfColon != -1) {
231 moduleNamePart = childName.substring(0, lastIndexOfColon);
232 nodeNamePart = childName.substring(lastIndexOfColon + 1);
234 final Module m = schema.findModuleByName(moduleNamePart, null);
235 namespace = m == null ? null : m.getNamespace();
237 nodeNamePart = childName;
240 if (namespace == null) {
241 Set<URI> potentialUris = Collections.emptySet();
242 potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
243 if (potentialUris.contains(getCurrentNamespace())) {
244 namespace = getCurrentNamespace();
245 } else if (potentialUris.size() == 1) {
246 namespace = potentialUris.iterator().next();
247 } else if (potentialUris.size() > 1) {
248 throw new IllegalStateException("Choose suitable module name for element "+nodeNamePart+":"+toModuleNames(potentialUris));
249 } else if (potentialUris.isEmpty()) {
250 throw new IllegalStateException("Schema node with name "+nodeNamePart+" wasn't found.");
254 return new NamespaceAndName(nodeNamePart, namespace);
257 private String toModuleNames(final Set<URI> potentialUris) {
258 final StringBuilder builder = new StringBuilder();
259 for (final URI potentialUri : potentialUris) {
260 builder.append("\n");
261 //FIXME how to get information about revision from JSON input? currently first available is used.
262 builder.append(schema.findModuleByNamespace(potentialUri).iterator().next().getName());
264 return builder.toString();
267 private Set<URI> resolveAllPotentialNamespaces(final String elementName, final DataSchemaNode dataSchemaNode) {
268 final Set<URI> potentialUris = new HashSet<>();
269 final Set<ChoiceSchemaNode> choices = new HashSet<>();
270 if (dataSchemaNode instanceof DataNodeContainer) {
271 for (final DataSchemaNode childSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
272 if (childSchemaNode instanceof ChoiceSchemaNode) {
273 choices.add((ChoiceSchemaNode)childSchemaNode);
274 } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
275 potentialUris.add(childSchemaNode.getQName().getNamespace());
279 for (final ChoiceSchemaNode choiceNode : choices) {
280 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
281 potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
285 return potentialUris;
288 private URI getCurrentNamespace() {
289 return namespaces.peek();
293 * Returns stack of schema nodes via which it was necessary to pass to get schema node with specified
294 * {@code childName} and {@code namespace}
296 * @param dataSchemaNode
299 * @return stack of schema nodes via which it was passed through. If found schema node is direct child then stack
300 * contains only one node. If it is found under choice and case then stack should contains 2*n+1 element
301 * (where n is number of choices through it was passed)
303 private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
304 final String childName, final URI namespace) {
305 final Deque<DataSchemaNode> result = new ArrayDeque<>();
306 final List<ChoiceSchemaNode> childChoices = new ArrayList<>();
307 DataSchemaNode potentialChildNode = null;
308 if (dataSchemaNode instanceof DataNodeContainer) {
309 for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
310 if (childNode instanceof ChoiceSchemaNode) {
311 childChoices.add((ChoiceSchemaNode) childNode);
313 final QName childQName = childNode.getQName();
315 if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
316 if (potentialChildNode == null ||
317 childQName.getRevision().after(potentialChildNode.getQName().getRevision())) {
318 potentialChildNode = childNode;
324 if (potentialChildNode != null) {
325 result.push(potentialChildNode);
329 // try to find data schema node in choice (looking for first match)
330 for (final ChoiceSchemaNode choiceNode : childChoices) {
331 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
332 final Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
334 if (!resultFromRecursion.isEmpty()) {
335 resultFromRecursion.push(concreteCase);
336 resultFromRecursion.push(choiceNode);
337 return resultFromRecursion;
344 private static class NamespaceAndName {
345 private final URI uri;
346 private final String name;
348 public NamespaceAndName(final String name, final URI uri) {
353 public String getName() {
357 public URI getUri() {
363 public void flush() throws IOException {
368 public void close() throws IOException {