Merge "BUG-576: fixed possible null pointer dereference in BindingGeneratorImpl"
[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.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
29 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.LoggingNormalizedNodeStreamWriter;
33 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
34 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
35 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
36 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
37 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
38 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
41 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 public class StreamToNormalizedNodeTest {
46     private static final Logger LOG = LoggerFactory.getLogger(StreamToNormalizedNodeTest.class);
47     private static SchemaContext schemaContext;
48     private static String streamAsString;
49
50     @BeforeClass
51     public static void initialization() throws IOException, URISyntaxException {
52         schemaContext = loadModules("/complexjson/yang");
53         streamAsString = loadTextFile(new File(StreamToNormalizedNodeTest.class.getResource(
54                 "/complexjson/complex-json.json").toURI()));
55     }
56
57     /**
58      * Demonstrates how to log events produced by a {@link JsonReader}.
59      *
60      * @throws IOException
61      */
62     @Test
63     public void ownStreamWriterImplementationDemonstration() throws IOException {
64         // GSON's JsonReader reading from the loaded string (our event source)
65         final JsonReader reader = new JsonReader(new StringReader(streamAsString));
66
67         // StreamWriter which outputs SLF4J events
68         final LoggingNormalizedNodeStreamWriter logWriter = new LoggingNormalizedNodeStreamWriter();
69
70         // JSON -> StreamWriter parser
71         try (final JsonParserStream jsonHandler = JsonParserStream.create(logWriter, schemaContext)) {
72             // Process multiple readers, flush()/close() as needed
73             jsonHandler.parse(reader);
74         }
75     }
76
77     /**
78      * Demonstrates how to create an immutable NormalizedNode tree from a {@link JsonReader} and
79      * then writes the data back into string representation.
80      *
81      * @throws IOException
82      */
83     @Test
84     public void immutableNormalizedNodeStreamWriterDemonstration() throws IOException {
85         /*
86          * This is the parsing part
87          */
88         // This is where we will output the nodes
89         NormalizedNodeResult result = new NormalizedNodeResult();
90
91         // StreamWriter which attaches NormalizedNode under parent
92         final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
93
94         // JSON -> StreamWriter parser
95         try (JsonParserStream handler = JsonParserStream.create(streamWriter, schemaContext)) {
96             handler.parse(new JsonReader(new StringReader(streamAsString)));
97         }
98
99         // Finally build the node
100         final NormalizedNode<?, ?> parsedData = result.getResult();
101         LOG.debug("Parsed NormalizedNodes: {}", parsedData);
102
103         /*
104          * This is the serialization part.
105          */
106         // We want to write the first child out
107         final DataContainerChild<? extends PathArgument, ?> firstChild = (DataContainerChild<? extends PathArgument, ?>) parsedData;
108         LOG.debug("Serializing first child: {}", firstChild);
109
110         // String holder
111         final StringWriter writer = new StringWriter();
112
113         // StreamWriter which outputs JSON strings
114         final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.create(schemaContext, writer, 2);
115
116         // NormalizedNode -> StreamWriter
117         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
118
119         // Write multiple NormalizedNodes fluently, flush()/close() as needed
120         nodeWriter.write(firstChild).close();
121
122         // Just to put it somewhere
123         LOG.debug("Serialized JSON: {}", writer.toString());
124     }
125
126     private static SchemaContext loadModules(final String resourceDirectory) throws IOException, URISyntaxException {
127         YangContextParser parser = new YangParserImpl();
128         URI path = StreamToNormalizedNodeTest.class.getResource(resourceDirectory).toURI();
129         final File testDir = new File(path);
130         final String[] fileList = testDir.list();
131         final List<File> testFiles = new ArrayList<File>();
132         if (fileList == null) {
133             throw new FileNotFoundException(resourceDirectory);
134         }
135         for (String fileName : fileList) {
136             if (new File(testDir, fileName).isDirectory() == false) {
137                 testFiles.add(new File(testDir, fileName));
138             }
139         }
140         return parser.parseFiles(testFiles);
141     }
142
143     private static String loadTextFile(final File file) throws IOException {
144         FileReader fileReader = new FileReader(file);
145         BufferedReader bufReader = new BufferedReader(fileReader);
146
147         String line = null;
148         StringBuilder result = new StringBuilder();
149         while ((line = bufReader.readLine()) != null) {
150             result.append(line);
151         }
152         bufReader.close();
153         return result.toString();
154     }
155 }