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;
18 import java.io.Closeable;
19 import java.io.EOFException;
20 import java.io.Flushable;
21 import java.io.IOException;
23 import java.util.ArrayDeque;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.Deque;
28 import java.util.HashSet;
29 import java.util.List;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
34 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
36 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
37 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
38 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.Module;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
47 * This class parses JSON elements from a GSON JsonReader. It disallows multiple elements of the same name unlike the
48 * default GSON JsonParser.
51 public final class JsonParserStream implements Closeable, Flushable {
52 private final Deque<URI> namespaces = new ArrayDeque<>();
53 private final NormalizedNodeStreamWriter writer;
54 private final JSONCodecFactory codecs;
55 private final SchemaContext schema;
56 private final DataSchemaNode parentNode;
58 private JsonParserStream(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext, final DataSchemaNode parentNode) {
59 this.schema = Preconditions.checkNotNull(schemaContext);
60 this.writer = Preconditions.checkNotNull(writer);
61 this.codecs = JSONCodecFactory.create(schemaContext);
62 this.parentNode = parentNode;
65 public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext, final SchemaNode 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) throws JsonIOException, JsonSyntaxException {
75 // code copied from gson's JsonParser and Stream classes
77 boolean lenient = reader.isLenient();
78 reader.setLenient(true);
79 boolean isEmpty = true;
83 TopLevelNodeDataWithSchema topLevelNodeDataWithSchema = new TopLevelNodeDataWithSchema(parentNode);
84 read(reader, topLevelNodeDataWithSchema);
85 topLevelNodeDataWithSchema.normalizeTopLevelNode();
86 topLevelNodeDataWithSchema.write(writer);
88 // return read(reader);
89 } catch (EOFException e) {
92 // return JsonNull.INSTANCE;
94 // The stream ended prematurely so it is likely a syntax error.
95 throw new JsonSyntaxException(e);
96 } catch (MalformedJsonException e) {
97 throw new JsonSyntaxException(e);
98 } catch (IOException e) {
99 throw new JsonIOException(e);
100 } catch (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 final void setValue(final AbstractNodeDataWithSchema parent, final String value) {
110 Preconditions.checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type", parent);
112 final Object translatedValue = translateValueByType(value, parent.getSchema());
113 ((SimpleNodeDataWithSchema) parent).setValue(translatedValue);
116 public void read(final JsonReader in, final AbstractNodeDataWithSchema parent) throws IOException {
120 setValue(parent, in.nextString());
123 setValue(parent, Boolean.toString(in.nextBoolean()));
127 setValue(parent, null);
131 while (in.hasNext()) {
132 AbstractNodeDataWithSchema newChild = null;
133 if (parent instanceof ListNodeDataWithSchema) {
134 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
135 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
136 } else if (parent instanceof LeafListNodeDataWithSchema) {
137 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
138 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
145 Set<String> namesakes = new HashSet<>();
147 while (in.hasNext()) {
148 final String jsonElementName = in.nextName();
149 final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parent.getSchema());
150 final String localName = namespaceAndName.getName();
151 addNamespace(namespaceAndName.getUri());
152 if (namesakes.contains(jsonElementName)) {
153 throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
155 namesakes.add(jsonElementName);
156 final Deque<DataSchemaNode> childDataSchemaNodes = findSchemaNodeByNameAndNamespace(parent.getSchema(),
157 localName, getCurrentNamespace());
158 if (childDataSchemaNodes.isEmpty()) {
159 throw new IllegalStateException("Schema for node with name " + localName + " and namespace "
160 + getCurrentNamespace() + " doesn't exist.");
163 AbstractNodeDataWithSchema newChild;
164 newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
165 // FIXME:anyxml data shouldn't be skipped but should be loaded somehow. will be specified after 17AUG2014
166 if (newChild instanceof AnyXmlNodeDataWithSchema) {
183 private Object translateValueByType(final String value, final DataSchemaNode node) {
184 final TypeDefinition<? extends Object> typeDefinition = typeDefinition(node);
185 if (typeDefinition == null) {
189 return codecs.codecFor(typeDefinition).deserialize(value);
192 private static TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
193 TypeDefinition<?> baseType = null;
194 if (node instanceof LeafListSchemaNode) {
195 baseType = ((LeafListSchemaNode) node).getType();
196 } else if (node instanceof LeafSchemaNode) {
197 baseType = ((LeafSchemaNode) node).getType();
198 } else if (node instanceof AnyXmlSchemaNode) {
201 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
204 if (baseType != null) {
205 while (baseType.getBaseType() != null) {
206 baseType = baseType.getBaseType();
212 private void removeNamespace() {
216 private void addNamespace(final URI namespace) {
217 namespaces.push(namespace);
220 private NamespaceAndName resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
221 int lastIndexOfColon = childName.lastIndexOf(':');
222 String moduleNamePart = null;
223 String nodeNamePart = null;
224 URI namespace = null;
225 if (lastIndexOfColon != -1) {
226 moduleNamePart = childName.substring(0, lastIndexOfColon);
227 nodeNamePart = childName.substring(lastIndexOfColon + 1);
229 final Module m = schema.findModuleByName(moduleNamePart, null);
230 namespace = m == null ? null : m.getNamespace();
232 nodeNamePart = childName;
235 if (namespace == null) {
236 Set<URI> potentialUris = Collections.emptySet();
237 potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
238 if (potentialUris.contains(getCurrentNamespace())) {
239 namespace = getCurrentNamespace();
240 } else if (potentialUris.size() == 1) {
241 namespace = potentialUris.iterator().next();
242 } else if (potentialUris.size() > 1) {
243 throw new IllegalStateException("Choose suitable module name for element "+nodeNamePart+":"+toModuleNames(potentialUris));
244 } else if (potentialUris.isEmpty()) {
245 throw new IllegalStateException("Schema node with name "+nodeNamePart+" wasn't found.");
249 return new NamespaceAndName(nodeNamePart, namespace);
252 private String toModuleNames(Set<URI> potentialUris) {
253 final StringBuilder builder = new StringBuilder();
254 for (URI potentialUri : potentialUris) {
255 builder.append("\n");
256 //FIXME how to get information about revision from JSON input? currently first available is used.
257 builder.append(schema.findModuleByNamespace(potentialUri).iterator().next().getName());
259 return builder.toString();
262 private Set<URI> resolveAllPotentialNamespaces(final String elementName, final DataSchemaNode dataSchemaNode) {
263 final Set<URI> potentialUris = new HashSet<>();
264 final Set<ChoiceNode> choices = new HashSet<>();
265 if (dataSchemaNode instanceof DataNodeContainer) {
266 for (DataSchemaNode childSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
267 if (childSchemaNode instanceof ChoiceNode) {
268 choices.add((ChoiceNode)childSchemaNode);
269 } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
270 potentialUris.add(childSchemaNode.getQName().getNamespace());
274 for (ChoiceNode choiceNode : choices) {
275 for (ChoiceCaseNode concreteCase : choiceNode.getCases()) {
276 potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
280 return potentialUris;
283 private URI getCurrentNamespace() {
284 return namespaces.peek();
288 * Returns stack of schema nodes via which it was necessary to pass to get schema node with specified
289 * {@code childName} and {@code namespace}
291 * @param dataSchemaNode
294 * @return stack of schema nodes via which it was passed through. If found schema node is direct child then stack
295 * contains only one node. If it is found under choice and case then stack should contains 2*n+1 element
296 * (where n is number of choices through it was passed)
298 private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
299 final String childName, final URI namespace) {
300 final Deque<DataSchemaNode> result = new ArrayDeque<>();
301 List<ChoiceNode> childChoices = new ArrayList<>();
302 if (dataSchemaNode instanceof DataNodeContainer) {
303 for (DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
304 if (childNode instanceof ChoiceNode) {
305 childChoices.add((ChoiceNode) childNode);
307 final QName childQName = childNode.getQName();
308 if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
309 result.push(childNode);
315 // try to find data schema node in choice (looking for first match)
316 for (ChoiceNode choiceNode : childChoices) {
317 for (ChoiceCaseNode concreteCase : choiceNode.getCases()) {
318 Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
320 if (!resultFromRecursion.isEmpty()) {
321 resultFromRecursion.push(concreteCase);
322 resultFromRecursion.push(choiceNode);
323 return resultFromRecursion;
330 private static class NamespaceAndName {
331 private final URI uri;
332 private final String name;
334 public NamespaceAndName(final String name, final URI uri) {
339 public String getName() {
343 public URI getUri() {
349 public void flush() throws IOException {
354 public void close() throws IOException {