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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.annotations.Beta;
15 import com.google.gson.JsonIOException;
16 import com.google.gson.JsonParseException;
17 import com.google.gson.JsonSyntaxException;
18 import com.google.gson.stream.JsonReader;
19 import com.google.gson.stream.MalformedJsonException;
20 import java.io.Closeable;
21 import java.io.EOFException;
22 import java.io.Flushable;
23 import java.io.IOException;
24 import java.util.AbstractMap.SimpleImmutableEntry;
25 import java.util.ArrayDeque;
26 import java.util.Deque;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.Map.Entry;
31 import javax.xml.transform.dom.DOMSource;
32 import org.eclipse.jdt.annotation.NonNull;
33 import org.opendaylight.yangtools.util.xml.UntrustedXML;
34 import org.opendaylight.yangtools.yang.common.XMLNamespace;
35 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
36 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
37 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
38 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
39 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema.ChildReusePolicy;
40 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
41 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
42 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
43 import org.opendaylight.yangtools.yang.data.util.MultipleEntryDataWithSchema;
44 import org.opendaylight.yangtools.yang.data.util.OperationAsContainer;
45 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
46 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
47 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.Module;
52 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.w3c.dom.Document;
58 import org.w3c.dom.Element;
59 import org.w3c.dom.Text;
62 * This class parses JSON elements from a GSON JsonReader. It disallows multiple elements of the same name unlike the
63 * default GSON JsonParser.
66 public final class JsonParserStream implements Closeable, Flushable {
67 static final String ANYXML_ARRAY_ELEMENT_ID = "array-element";
69 private static final Logger LOG = LoggerFactory.getLogger(JsonParserStream.class);
70 private final Deque<XMLNamespace> namespaces = new ArrayDeque<>();
71 private final NormalizedNodeStreamWriter writer;
72 private final JSONCodecFactory codecs;
73 private final DataSchemaNode parentNode;
75 // TODO: consider class specialization to remove this field
76 private final boolean lenient;
78 private JsonParserStream(final NormalizedNodeStreamWriter writer, final JSONCodecFactory codecs,
79 final DataSchemaNode parentNode, final boolean lenient) {
80 this.writer = requireNonNull(writer);
81 this.codecs = requireNonNull(codecs);
82 this.parentNode = parentNode;
83 this.lenient = lenient;
87 * Create a new {@link JsonParserStream} backed by specified {@link NormalizedNodeStreamWriter}
88 * and {@link JSONCodecFactory}. The stream will be logically rooted at the top of the SchemaContext associated
89 * with the specified codec factory.
91 * @param writer NormalizedNodeStreamWriter to use for instantiation of normalized nodes
92 * @param codecFactory {@link JSONCodecFactory} to use for parsing leaves
93 * @return A new {@link JsonParserStream}
94 * @throws NullPointerException if any of the arguments are null
96 public static @NonNull JsonParserStream create(final @NonNull NormalizedNodeStreamWriter writer,
97 final @NonNull JSONCodecFactory codecFactory) {
98 return new JsonParserStream(writer, codecFactory, codecFactory.getEffectiveModelContext(), false);
102 * Create a new {@link JsonParserStream} backed by specified {@link NormalizedNodeStreamWriter}
103 * and {@link JSONCodecFactory}. The stream will be logically rooted at the specified parent node.
105 * @param writer NormalizedNodeStreamWriter to use for instantiation of normalized nodes
106 * @param codecFactory {@link JSONCodecFactory} to use for parsing leaves
107 * @param parentNode Logical root node
108 * @return A new {@link JsonParserStream}
109 * @throws NullPointerException if any of the arguments are null
111 public static @NonNull JsonParserStream create(final @NonNull NormalizedNodeStreamWriter writer,
112 final @NonNull JSONCodecFactory codecFactory, final @NonNull SchemaNode parentNode) {
113 return new JsonParserStream(writer, codecFactory, validateParent(parentNode), false);
117 * Create a new {@link JsonParserStream} backed by specified {@link NormalizedNodeStreamWriter}
118 * and {@link JSONCodecFactory}. The stream will be logically rooted at the top of the SchemaContext associated
119 * with the specified codec factory.
122 * Returned parser will treat incoming JSON data leniently:
124 * <li>JSON elements referring to unknown constructs will be silently ignored</li>
127 * @param writer NormalizedNodeStreamWriter to use for instantiation of normalized nodes
128 * @param codecFactory {@link JSONCodecFactory} to use for parsing leaves
129 * @return A new {@link JsonParserStream}
130 * @throws NullPointerException if any of the arguments are null
132 public static @NonNull JsonParserStream createLenient(final @NonNull NormalizedNodeStreamWriter writer,
133 final @NonNull JSONCodecFactory codecFactory) {
134 return new JsonParserStream(writer, codecFactory, codecFactory.getEffectiveModelContext(), true);
138 * Create a new {@link JsonParserStream} backed by specified {@link NormalizedNodeStreamWriter}
139 * and {@link JSONCodecFactory}. The stream will be logically rooted at the specified parent node.
142 * Returned parser will treat incoming JSON data leniently:
144 * <li>JSON elements referring to unknown constructs will be silently ignored</li>
147 * @param writer NormalizedNodeStreamWriter to use for instantiation of normalized nodes
148 * @param codecFactory {@link JSONCodecFactory} to use for parsing leaves
149 * @param parentNode Logical root node
150 * @return A new {@link JsonParserStream}
151 * @throws NullPointerException if any of the arguments are null
153 public static @NonNull JsonParserStream createLenient(final @NonNull NormalizedNodeStreamWriter writer,
154 final @NonNull JSONCodecFactory codecFactory, final @NonNull SchemaNode parentNode) {
155 return new JsonParserStream(writer, codecFactory, validateParent(parentNode), true);
158 public JsonParserStream parse(final JsonReader reader) {
159 // code copied from gson's JsonParser and Stream classes
161 final boolean readerLenient = reader.isLenient();
162 reader.setLenient(true);
163 boolean isEmpty = true;
167 final CompositeNodeDataWithSchema<?> compositeNodeDataWithSchema =
168 new CompositeNodeDataWithSchema<>(parentNode);
169 read(reader, compositeNodeDataWithSchema);
170 compositeNodeDataWithSchema.write(writer);
173 } catch (final EOFException e) {
177 // The stream ended prematurely so it is likely a syntax error.
178 throw new JsonSyntaxException(e);
179 } catch (final MalformedJsonException | NumberFormatException e) {
180 throw new JsonSyntaxException(e);
181 } catch (final IOException e) {
182 throw new JsonIOException(e);
183 } catch (StackOverflowError | OutOfMemoryError e) {
184 throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
186 reader.setLenient(readerLenient);
190 private void traverseAnyXmlValue(final JsonReader in, final Document doc, final Element parentElement)
195 Text textNode = doc.createTextNode(in.nextString());
196 parentElement.appendChild(textNode);
199 textNode = doc.createTextNode(Boolean.toString(in.nextBoolean()));
200 parentElement.appendChild(textNode);
204 textNode = doc.createTextNode("null");
205 parentElement.appendChild(textNode);
209 while (in.hasNext()) {
210 final Element childElement = doc.createElement(ANYXML_ARRAY_ELEMENT_ID);
211 parentElement.appendChild(childElement);
212 traverseAnyXmlValue(in, doc, childElement);
218 while (in.hasNext()) {
219 final Element childElement = doc.createElement(in.nextName());
220 parentElement.appendChild(childElement);
221 traverseAnyXmlValue(in, doc, childElement);
230 private void readAnyXmlValue(final JsonReader in, final AnyXmlNodeDataWithSchema parent,
231 final String anyXmlObjectName) throws IOException {
232 final String anyXmlObjectNS = getCurrentNamespace().toString();
233 final Document doc = UntrustedXML.newDocumentBuilder().newDocument();
234 final Element rootElement = doc.createElementNS(anyXmlObjectNS, anyXmlObjectName);
235 doc.appendChild(rootElement);
236 traverseAnyXmlValue(in, doc, rootElement);
238 final DOMSource domSource = new DOMSource(doc.getDocumentElement());
239 parent.setValue(domSource);
242 public void read(final JsonReader in, AbstractNodeDataWithSchema<?> parent) throws IOException {
246 setValue(parent, in.nextString());
249 setValue(parent, Boolean.toString(in.nextBoolean()));
253 setValue(parent, null);
257 while (in.hasNext()) {
258 if (parent instanceof LeafNodeDataWithSchema) {
261 final AbstractNodeDataWithSchema<?> newChild = newArrayEntry(parent);
268 final Set<String> namesakes = new HashSet<>();
271 * This allows parsing of incorrectly /as showcased/
272 * in testconf nesting of list items - eg.
273 * lists with one value are sometimes serialized
274 * without wrapping array.
277 if (isArray(parent)) {
278 parent = newArrayEntry(parent);
280 while (in.hasNext()) {
281 final String jsonElementName = in.nextName();
282 final DataSchemaNode parentSchema = parent.getSchema();
283 final Entry<String, XMLNamespace> namespaceAndName =
284 resolveNamespace(jsonElementName, parentSchema);
285 final String localName = namespaceAndName.getKey();
286 final XMLNamespace namespace = namespaceAndName.getValue();
287 if (lenient && (localName == null || namespace == null)) {
288 LOG.debug("Schema node with name {} was not found under {}", localName,
289 parentSchema.getQName());
293 addNamespace(namespace);
294 if (!namesakes.add(jsonElementName)) {
295 throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
298 final Deque<DataSchemaNode> childDataSchemaNodes =
299 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, localName,
300 getCurrentNamespace());
301 checkState(!childDataSchemaNodes.isEmpty(),
302 "Schema for node with name %s and namespace %s does not exist at %s",
303 localName, getCurrentNamespace(), parentSchema);
306 final AbstractNodeDataWithSchema<?> newChild = ((CompositeNodeDataWithSchema<?>) parent)
307 .addChild(childDataSchemaNodes, ChildReusePolicy.NOOP);
308 if (newChild instanceof AnyXmlNodeDataWithSchema) {
309 readAnyXmlValue(in, (AnyXmlNodeDataWithSchema) newChild, jsonElementName);
322 private static boolean isArray(final AbstractNodeDataWithSchema<?> parent) {
323 return parent instanceof ListNodeDataWithSchema || parent instanceof LeafListNodeDataWithSchema;
326 private static AbstractNodeDataWithSchema<?> newArrayEntry(final AbstractNodeDataWithSchema<?> parent) {
327 if (!(parent instanceof MultipleEntryDataWithSchema)) {
328 throw new IllegalStateException("Found an unexpected array nested under " + parent.getSchema().getQName());
330 return ((MultipleEntryDataWithSchema<?>) parent).newChildEntry();
333 private void setValue(final AbstractNodeDataWithSchema<?> parent, final String value) {
334 checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
335 parent.getSchema().getQName());
336 final SimpleNodeDataWithSchema<?> parentSimpleNode = (SimpleNodeDataWithSchema<?>) parent;
337 checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
338 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
340 final Object translatedValue = translateValueByType(value, parentSimpleNode.getSchema());
341 parentSimpleNode.setValue(translatedValue);
344 private Object translateValueByType(final String value, final DataSchemaNode node) {
345 checkArgument(node instanceof TypedDataSchemaNode);
346 return codecs.codecFor((TypedDataSchemaNode) node).parseValue(null, value);
349 private void removeNamespace() {
353 private void addNamespace(final XMLNamespace namespace) {
354 namespaces.push(namespace);
357 private Entry<String, XMLNamespace> resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
358 final int lastIndexOfColon = childName.lastIndexOf(':');
359 String moduleNamePart = null;
360 String nodeNamePart = null;
361 XMLNamespace namespace = null;
362 if (lastIndexOfColon != -1) {
363 moduleNamePart = childName.substring(0, lastIndexOfColon);
364 nodeNamePart = childName.substring(lastIndexOfColon + 1);
366 final Iterator<? extends Module> m = codecs.getEffectiveModelContext().findModules(moduleNamePart)
368 namespace = m.hasNext() ? m.next().getNamespace() : null;
370 nodeNamePart = childName;
373 if (namespace == null) {
374 final Set<XMLNamespace> potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
375 if (potentialUris.contains(getCurrentNamespace())) {
376 namespace = getCurrentNamespace();
377 } else if (potentialUris.size() == 1) {
378 namespace = potentialUris.iterator().next();
379 } else if (potentialUris.size() > 1) {
380 throw new IllegalStateException("Choose suitable module name for element " + nodeNamePart + ":"
381 + toModuleNames(potentialUris));
382 } else if (potentialUris.isEmpty() && !lenient) {
383 throw new IllegalStateException("Schema node with name " + nodeNamePart + " was not found under "
384 + dataSchemaNode.getQName() + ".");
388 return new SimpleImmutableEntry<>(nodeNamePart, namespace);
391 private String toModuleNames(final Set<XMLNamespace> potentialUris) {
392 final StringBuilder builder = new StringBuilder();
393 for (final XMLNamespace potentialUri : potentialUris) {
394 builder.append('\n');
395 //FIXME how to get information about revision from JSON input? currently first available is used.
396 builder.append(codecs.getEffectiveModelContext().findModules(potentialUri).iterator().next().getName());
398 return builder.toString();
401 private Set<XMLNamespace> resolveAllPotentialNamespaces(final String elementName,
402 final DataSchemaNode dataSchemaNode) {
403 final Set<XMLNamespace> potentialUris = new HashSet<>();
404 final Set<ChoiceSchemaNode> choices = new HashSet<>();
405 if (dataSchemaNode instanceof DataNodeContainer) {
406 for (final DataSchemaNode childSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
407 if (childSchemaNode instanceof ChoiceSchemaNode) {
408 choices.add((ChoiceSchemaNode)childSchemaNode);
409 } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
410 potentialUris.add(childSchemaNode.getQName().getNamespace());
414 for (final ChoiceSchemaNode choiceNode : choices) {
415 for (final CaseSchemaNode concreteCase : choiceNode.getCases()) {
416 potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
420 return potentialUris;
423 private XMLNamespace getCurrentNamespace() {
424 return namespaces.peek();
427 private static DataSchemaNode validateParent(final SchemaNode parent) {
428 if (parent instanceof DataSchemaNode) {
429 return (DataSchemaNode) parent;
430 } else if (parent instanceof OperationDefinition) {
431 return OperationAsContainer.of((OperationDefinition) parent);
433 throw new IllegalArgumentException("Illegal parent node " + requireNonNull(parent));
438 public void flush() throws IOException {
443 public void close() throws IOException {