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.gson.stream.JsonReader;
11 import java.io.BufferedReader;
13 import java.io.FileNotFoundException;
14 import java.io.FileReader;
15 import java.io.IOException;
16 import java.io.StringReader;
17 import java.io.StringWriter;
18 import java.net.URISyntaxException;
19 import java.util.ArrayList;
20 import java.util.List;
21 import org.junit.BeforeClass;
22 import org.junit.Test;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
26 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
28 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.stream.LoggingNormalizedNodeStreamWriter;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
32 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
33 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
34 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
36 import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
37 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 public class StreamToNormalizedNodeTest {
42 private static final Logger LOG = LoggerFactory.getLogger(StreamToNormalizedNodeTest.class);
43 private static SchemaContext schemaContext;
44 private static String streamAsString;
47 public static void initialization() throws IOException, URISyntaxException {
48 schemaContext = loadModules("/complexjson/yang");
49 streamAsString = loadTextFile(new File(StreamToNormalizedNodeTest.class.getResource(
50 "/complexjson/complex-json.json").toURI()));
54 * Demonstrates how to log events produced by a {@link JsonReader}.
59 public void ownStreamWriterImplementationDemonstration() throws IOException {
60 // GSON's JsonReader reading from the loaded string (our event source)
61 final JsonReader reader = new JsonReader(new StringReader(streamAsString));
63 // StreamWriter which outputs SLF4J events
64 final LoggingNormalizedNodeStreamWriter logWriter = new LoggingNormalizedNodeStreamWriter();
66 // JSON -> StreamWriter parser
67 try (final JsonParserStream jsonHandler = JsonParserStream.create(logWriter, schemaContext)) {
68 // Process multiple readers, flush()/close() as needed
69 jsonHandler.parse(reader);
74 * Demonstrates how to create an immutable NormalizedNode tree from a {@link JsonReader} and
75 * then writes the data back into string representation.
80 public void immutableNormalizedNodeStreamWriterDemonstration() throws IOException {
82 * This is the parsing part
84 // This is where we will output the nodes
85 final NormalizedNodeContainerBuilder<NodeIdentifier, ?, ?, ? extends NormalizedNode<?, ?>> parent =
86 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(QName.create("dummy", "2014-12-31", "dummy")));
88 // StreamWriter which attaches NormalizedNode under parent
89 final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(parent);
91 // JSON -> StreamWriter parser
92 try (JsonParserStream handler = JsonParserStream.create(streamWriter, schemaContext)) {
93 handler.parse(new JsonReader(new StringReader(streamAsString)));
96 // Finally build the node
97 final NormalizedNode<?, ?> parsedData = parent.build();
98 LOG.debug("Parsed NormalizedNodes: {}", parsedData);
101 * This is the serialization part.
103 // We want to write the first child out
104 final DataContainerChild<? extends PathArgument, ?> firstChild = ((ContainerNode) parsedData).getValue().iterator().next();
105 LOG.debug("Serializing first child: {}", firstChild);
108 final StringWriter writer = new StringWriter();
110 // StreamWriter which outputs JSON strings
111 final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.create(schemaContext, writer, 2);
113 // NormalizedNode -> StreamWriter
114 final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
116 // Write multiple NormalizedNodes fluently, flush()/close() as needed
117 nodeWriter.write(firstChild).close();
119 // Just to put it somewhere
120 LOG.debug("Serialized JSON: {}", writer.toString());
123 private static SchemaContext loadModules(final String resourceDirectory) throws IOException {
124 YangContextParser parser = new YangParserImpl();
125 String path = StreamToNormalizedNodeTest.class.getResource(resourceDirectory).getPath();
126 final File testDir = new File(path);
127 final String[] fileList = testDir.list();
128 final List<File> testFiles = new ArrayList<File>();
129 if (fileList == null) {
130 throw new FileNotFoundException(resourceDirectory);
132 for (String fileName : fileList) {
133 if (new File(testDir, fileName).isDirectory() == false) {
134 testFiles.add(new File(testDir, fileName));
137 return parser.parseFiles(testFiles);
140 private static String loadTextFile(final File file) throws IOException {
141 FileReader fileReader = new FileReader(file);
142 BufferedReader bufReader = new BufferedReader(fileReader);
145 StringBuilder result = new StringBuilder();
146 while ((line = bufReader.readLine()) != null) {
150 return result.toString();