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,
56 final DataSchemaNode parentNode) {
57 this.schema = Preconditions.checkNotNull(schemaContext);
58 this.writer = DataSchemaNodeAwareAdaptor.forWriter(writer);
59 this.codecs = JSONCodecFactory.create(schemaContext);
60 this.parentNode = parentNode;
63 public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
64 final SchemaNode parentNode ) {
65 if (parentNode instanceof RpcDefinition) {
66 return new JsonParserStream(writer, schemaContext, new RpcAsContainer((RpcDefinition) parentNode));
68 Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
69 return new JsonParserStream(writer, schemaContext, (DataSchemaNode) parentNode);
72 public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext) {
73 return new JsonParserStream(writer, schemaContext, schemaContext);
76 public JsonParserStream parse(final JsonReader reader) {
77 // code copied from gson's JsonParser and Stream classes
79 final boolean lenient = reader.isLenient();
80 reader.setLenient(true);
81 boolean isEmpty = true;
85 final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
86 read(reader, compositeNodeDataWithSchema);
87 compositeNodeDataWithSchema.write(writer);
90 } catch (final EOFException e) {
94 // The stream ended prematurely so it is likely a syntax error.
95 throw new JsonSyntaxException(e);
96 } catch (final MalformedJsonException e) {
97 throw new JsonSyntaxException(e);
98 } catch (final IOException e) {
99 throw new JsonIOException(e);
100 } catch (final NumberFormatException e) {
101 throw new JsonSyntaxException(e);
102 } catch (StackOverflowError | OutOfMemoryError e) {
103 throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
105 reader.setLenient(lenient);
109 private void setValue(final AbstractNodeDataWithSchema parent, final String value) {
110 Preconditions.checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
111 parent.getSchema().getQName());
112 final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
113 Preconditions.checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
114 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
116 final Object translatedValue = translateValueByType(value, parentSimpleNode.getSchema());
117 parentSimpleNode.setValue(translatedValue);
120 public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
124 setValue(parent, in.nextString());
127 setValue(parent, Boolean.toString(in.nextBoolean()));
131 setValue(parent, null);
135 while (in.hasNext()) {
136 if (parent instanceof LeafNodeDataWithSchema) {
139 final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
146 final Set<String> namesakes = new HashSet<>();
149 * This allows parsing of incorrectly /as showcased/
150 * in testconf nesting of list items - eg.
151 * lists with one value are sometimes serialized
152 * without wrapping array.
155 if(isArray(parent)) {
156 parent = newArrayEntry(parent);
158 while (in.hasNext()) {
159 final String jsonElementName = in.nextName();
160 final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parent.getSchema());
161 final String localName = namespaceAndName.getName();
162 addNamespace(namespaceAndName.getUri());
163 if (namesakes.contains(jsonElementName)) {
164 throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
166 namesakes.add(jsonElementName);
167 final Deque<DataSchemaNode> childDataSchemaNodes = findSchemaNodeByNameAndNamespace(parent.getSchema(),
168 localName, getCurrentNamespace());
169 if (childDataSchemaNodes.isEmpty()) {
170 throw new IllegalStateException("Schema for node with name " + localName + " and namespace "
171 + getCurrentNamespace() + " doesn't exist.");
174 final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
176 * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
177 * will be able to load anyxml which conforms to YANG data using these
178 * parser, for other anyxml will be harder.
180 if (newChild instanceof AnyXmlNodeDataWithSchema) {
197 private static boolean isArray(final AbstractNodeDataWithSchema parent) {
198 return parent instanceof ListNodeDataWithSchema || parent instanceof LeafListNodeDataWithSchema;
201 private static AbstractNodeDataWithSchema newArrayEntry(final AbstractNodeDataWithSchema parent) {
202 AbstractNodeDataWithSchema newChild;
203 if (parent instanceof ListNodeDataWithSchema) {
204 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
205 } else if (parent instanceof LeafListNodeDataWithSchema) {
206 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
208 throw new IllegalStateException("Found an unexpected array nested under "+ parent.getSchema().getQName());
210 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
214 private Object translateValueByType(final String value, final DataSchemaNode node) {
215 if (node instanceof AnyXmlSchemaNode) {
217 * FIXME: Figure out some YANG extension dispatch, which will
218 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
223 return codecs.codecFor(node).deserialize(value);
226 private void removeNamespace() {
230 private void addNamespace(final URI namespace) {
231 namespaces.push(namespace);
234 private NamespaceAndName resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
235 final int lastIndexOfColon = childName.lastIndexOf(':');
236 String moduleNamePart = null;
237 String nodeNamePart = null;
238 URI namespace = null;
239 if (lastIndexOfColon != -1) {
240 moduleNamePart = childName.substring(0, lastIndexOfColon);
241 nodeNamePart = childName.substring(lastIndexOfColon + 1);
243 final Module m = schema.findModuleByName(moduleNamePart, null);
244 namespace = m == null ? null : m.getNamespace();
246 nodeNamePart = childName;
249 if (namespace == null) {
250 Set<URI> potentialUris = Collections.emptySet();
251 potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
252 if (potentialUris.contains(getCurrentNamespace())) {
253 namespace = getCurrentNamespace();
254 } else if (potentialUris.size() == 1) {
255 namespace = potentialUris.iterator().next();
256 } else if (potentialUris.size() > 1) {
257 throw new IllegalStateException("Choose suitable module name for element "+nodeNamePart+":"+toModuleNames(potentialUris));
258 } else if (potentialUris.isEmpty()) {
259 throw new IllegalStateException("Schema node with name "+nodeNamePart+" wasn't found under "+dataSchemaNode.getQName()+".");
263 return new NamespaceAndName(nodeNamePart, namespace);
266 private String toModuleNames(final Set<URI> potentialUris) {
267 final StringBuilder builder = new StringBuilder();
268 for (final URI potentialUri : potentialUris) {
269 builder.append("\n");
270 //FIXME how to get information about revision from JSON input? currently first available is used.
271 builder.append(schema.findModuleByNamespace(potentialUri).iterator().next().getName());
273 return builder.toString();
276 private Set<URI> resolveAllPotentialNamespaces(final String elementName, final DataSchemaNode dataSchemaNode) {
277 final Set<URI> potentialUris = new HashSet<>();
278 final Set<ChoiceSchemaNode> choices = new HashSet<>();
279 if (dataSchemaNode instanceof DataNodeContainer) {
280 for (final DataSchemaNode childSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
281 if (childSchemaNode instanceof ChoiceSchemaNode) {
282 choices.add((ChoiceSchemaNode)childSchemaNode);
283 } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
284 potentialUris.add(childSchemaNode.getQName().getNamespace());
288 for (final ChoiceSchemaNode choiceNode : choices) {
289 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
290 potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
294 return potentialUris;
297 private URI getCurrentNamespace() {
298 return namespaces.peek();
302 * Returns stack of schema nodes via which it was necessary to pass to get schema node with specified
303 * {@code childName} and {@code namespace}
305 * @param dataSchemaNode
308 * @return stack of schema nodes via which it was passed through. If found schema node is direct child then stack
309 * contains only one node. If it is found under choice and case then stack should contains 2*n+1 element
310 * (where n is number of choices through it was passed)
312 private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
313 final String childName, final URI namespace) {
314 final Deque<DataSchemaNode> result = new ArrayDeque<>();
315 final List<ChoiceSchemaNode> childChoices = new ArrayList<>();
316 DataSchemaNode potentialChildNode = null;
317 if (dataSchemaNode instanceof DataNodeContainer) {
318 for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
319 if (childNode instanceof ChoiceSchemaNode) {
320 childChoices.add((ChoiceSchemaNode) childNode);
322 final QName childQName = childNode.getQName();
324 if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
325 if (potentialChildNode == null ||
326 childQName.getRevision().after(potentialChildNode.getQName().getRevision())) {
327 potentialChildNode = childNode;
333 if (potentialChildNode != null) {
334 result.push(potentialChildNode);
338 // try to find data schema node in choice (looking for first match)
339 for (final ChoiceSchemaNode choiceNode : childChoices) {
340 for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
341 final Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
343 if (!resultFromRecursion.isEmpty()) {
344 resultFromRecursion.push(concreteCase);
345 resultFromRecursion.push(choiceNode);
346 return resultFromRecursion;
353 private static class NamespaceAndName {
354 private final URI uri;
355 private final String name;
357 public NamespaceAndName(final String name, final URI uri) {
362 public String getName() {
366 public URI getUri() {
372 public void flush() throws IOException {
377 public void close() throws IOException {