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