BUG-576: fixed text file loading in test.
[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 import java.io.BufferedReader;
12 import java.io.File;
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;
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         final NormalizedNodeContainerBuilder<NodeIdentifier, ?, ?, ? extends NormalizedNode<?, ?>> parent =
86                 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(QName.create("dummy", "2014-12-31", "dummy")));
87
88         // StreamWriter which attaches NormalizedNode under parent
89         final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(parent);
90
91         // JSON -> StreamWriter parser
92         try (JsonParserStream handler = JsonParserStream.create(streamWriter, schemaContext)) {
93             handler.parse(new JsonReader(new StringReader(streamAsString)));
94         }
95
96         // Finally build the node
97         final NormalizedNode<?, ?> parsedData = parent.build();
98         LOG.debug("Parsed NormalizedNodes: {}", parsedData);
99
100         /*
101          * This is the serialization part.
102          */
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);
106
107         // String holder
108         final StringWriter writer = new StringWriter();
109
110         // StreamWriter which outputs JSON strings
111         final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.create(schemaContext, writer, 2);
112
113         // NormalizedNode -> StreamWriter
114         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
115
116         // Write multiple NormalizedNodes fluently, flush()/close() as needed
117         nodeWriter.write(firstChild).close();
118
119         // Just to put it somewhere
120         LOG.debug("Serialized JSON: {}", writer.toString());
121     }
122
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);
131         }
132         for (String fileName : fileList) {
133             if (new File(testDir, fileName).isDirectory() == false) {
134                 testFiles.add(new File(testDir, fileName));
135             }
136         }
137         return parser.parseFiles(testFiles);
138     }
139
140     private static String loadTextFile(final File file) throws IOException {
141         FileReader fileReader = new FileReader(file);
142         BufferedReader bufReader = new BufferedReader(fileReader);
143
144         String line = null;
145         StringBuilder result = new StringBuilder();
146         while ((line = bufReader.readLine()) != null) {
147             result.append(line);
148         }
149         bufReader.close();
150         return result.toString();
151     }
152 }