Merge changes I0bc3b486,I67f2ca3e,Ie591417d,I01acd9f9,I8e1526a6,I0876d878,I0ed71b9c...
[yangtools.git] / yang / yang-data-codec-gson / src / test / java / org / opendaylight / yangtools / yang / data / codec / gson / StreamToNormalizedNodeTest.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.codec.gson;
9
10 import com.google.gson.stream.JsonReader;
11
12 import java.io.BufferedReader;
13 import java.io.File;
14 import java.io.FileNotFoundException;
15 import java.io.FileReader;
16 import java.io.IOException;
17 import java.io.StringReader;
18 import java.io.StringWriter;
19 import java.net.URI;
20 import java.net.URISyntaxException;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import org.junit.BeforeClass;
25 import org.junit.Test;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
27 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.LoggingNormalizedNodeStreamWriter;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
33 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
34 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
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;
40
41 public class StreamToNormalizedNodeTest {
42     private static final Logger LOG = LoggerFactory.getLogger(StreamToNormalizedNodeTest.class);
43     private static SchemaContext schemaContext;
44     private static String streamAsString;
45
46     @BeforeClass
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()));
51     }
52
53     /**
54      * Demonstrates how to log events produced by a {@link JsonReader}.
55      *
56      * @throws IOException
57      */
58     @Test
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));
62
63         // StreamWriter which outputs SLF4J events
64         final LoggingNormalizedNodeStreamWriter logWriter = new LoggingNormalizedNodeStreamWriter();
65
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);
70         }
71     }
72
73     /**
74      * Demonstrates how to create an immutable NormalizedNode tree from a {@link JsonReader} and
75      * then writes the data back into string representation.
76      *
77      * @throws IOException
78      */
79     @Test
80     public void immutableNormalizedNodeStreamWriterDemonstration() throws IOException {
81         /*
82          * This is the parsing part
83          */
84         // This is where we will output the nodes
85         NormalizedNodeResult result = new NormalizedNodeResult();
86
87         // StreamWriter which attaches NormalizedNode under parent
88         final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
89
90         // JSON -> StreamWriter parser
91         try (JsonParserStream handler = JsonParserStream.create(streamWriter, schemaContext)) {
92             handler.parse(new JsonReader(new StringReader(streamAsString)));
93         }
94
95         // Finally build the node
96         final NormalizedNode<?, ?> parsedData = result.getResult();
97         LOG.debug("Parsed NormalizedNodes: {}", parsedData);
98
99         /*
100          * This is the serialization part.
101          */
102         // We want to write the first child out
103         final DataContainerChild<? extends PathArgument, ?> firstChild = (DataContainerChild<? extends PathArgument, ?>) parsedData;
104         LOG.debug("Serializing first child: {}", firstChild);
105
106         // String holder
107         final StringWriter writer = new StringWriter();
108
109         // StreamWriter which outputs JSON strings
110         final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.create(schemaContext, writer, 2);
111
112         // NormalizedNode -> StreamWriter
113         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
114
115         // Write multiple NormalizedNodes fluently, flush()/close() as needed
116         nodeWriter.write(firstChild).close();
117
118         // Just to put it somewhere
119         LOG.debug("Serialized JSON: {}", writer.toString());
120     }
121
122     private static SchemaContext loadModules(final String resourceDirectory) throws IOException, URISyntaxException {
123         YangContextParser parser = new YangParserImpl();
124         URI path = StreamToNormalizedNodeTest.class.getResource(resourceDirectory).toURI();
125         final File testDir = new File(path);
126         final String[] fileList = testDir.list();
127         final List<File> testFiles = new ArrayList<File>();
128         if (fileList == null) {
129             throw new FileNotFoundException(resourceDirectory);
130         }
131         for (String fileName : fileList) {
132             if (new File(testDir, fileName).isDirectory() == false) {
133                 testFiles.add(new File(testDir, fileName));
134             }
135         }
136         return parser.parseFiles(testFiles);
137     }
138
139     private static String loadTextFile(final File file) throws IOException {
140         FileReader fileReader = new FileReader(file);
141         BufferedReader bufReader = new BufferedReader(fileReader);
142
143         String line = null;
144         StringBuilder result = new StringBuilder();
145         while ((line = bufReader.readLine()) != null) {
146             result.append(line);
147         }
148         bufReader.close();
149         return result.toString();
150     }
151 }