Yang and XML conversion to Json test with equals
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / TestUtils.java
1 package org.opendaylight.controller.sal.restconf.impl.test;
2
3 import static org.junit.Assert.assertFalse;
4 import static org.junit.Assert.assertNotNull;
5
6 import java.io.*;
7 import java.util.ArrayList;
8 import java.util.List;
9 import java.util.Set;
10
11 import javax.ws.rs.WebApplicationException;
12 import javax.xml.stream.XMLStreamException;
13 import javax.xml.transform.OutputKeys;
14 import javax.xml.transform.Transformer;
15 import javax.xml.transform.TransformerException;
16 import javax.xml.transform.TransformerFactory;
17 import javax.xml.transform.dom.DOMSource;
18 import javax.xml.transform.stream.StreamResult;
19
20 import org.opendaylight.controller.sal.rest.impl.*;
21 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
22 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
23 import org.opendaylight.yangtools.yang.data.api.Node;
24 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
25 import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder;
26 import org.opendaylight.yangtools.yang.model.api.*;
27 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
28 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.w3c.dom.Document;
32
33 final class TestUtils {
34
35     private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
36
37     private final static YangModelParser parser = new YangParserImpl();
38
39     public static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
40         final File testDir = new File(resourceDirectory);
41         final String[] fileList = testDir.list();
42         final List<File> testFiles = new ArrayList<File>();
43         if (fileList == null) {
44             throw new FileNotFoundException(resourceDirectory);
45         }
46         for (int i = 0; i < fileList.length; i++) {
47             String fileName = fileList[i];
48             if (new File(testDir, fileName).isDirectory() == false) {
49                 testFiles.add(new File(testDir, fileName));
50             }
51         }
52         return parser.parseYangModels(testFiles);
53     }
54
55     public static SchemaContext loadSchemaContext(Set<Module> modules) {
56         return parser.resolveSchemaContext(modules);
57     }
58
59     public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
60         return parser.resolveSchemaContext(loadModules(resourceDirectory));
61     }
62
63     public static Module findModule(Set<Module> modules, String moduleName) {
64         Module result = null;
65         for (Module module : modules) {
66             if (module.getName().equals(moduleName)) {
67                 result = module;
68                 break;
69             }
70         }
71         return result;
72     }
73
74     public static CompositeNode loadCompositeNode(InputStream xmlInputStream) throws FileNotFoundException {
75         if (xmlInputStream == null) {
76             throw new IllegalArgumentException();
77         }
78         Node<?> dataTree;
79         try {
80             dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream);
81         } catch (XMLStreamException e) {
82             logger.error("Error during building data tree from XML", e);
83             return null;
84         }
85         if (dataTree == null) {
86             logger.error("data tree is null");
87             return null;
88         }
89         if (dataTree instanceof SimpleNode) {
90             logger.error("RPC XML was resolved as SimpleNode");
91             return null;
92         }
93         return (CompositeNode) dataTree;
94     }
95
96     public static String getDocumentInPrintableForm(Document doc) {
97         try {
98             ByteArrayOutputStream out = new ByteArrayOutputStream();
99             TransformerFactory tf = TransformerFactory.newInstance();
100             Transformer transformer = tf.newTransformer();
101             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
102             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
103             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
104             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
105             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
106
107             transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
108             byte[] charData = out.toByteArray();
109             return new String(charData, "UTF-8");
110         } catch (IOException | TransformerException e) {
111             String msg = "Error during transformation of Document into String";
112             logger.error(msg, e);
113             return msg;
114         }
115
116     }
117
118     static String convertXmlDataAndYangToJson(String xmlDataPath, String yangPath, String outputPath) {
119         String jsonResult = null;
120         Set<Module> modules = null;
121
122         try {
123             modules = TestUtils.loadModules(YangAndXmlToJsonBasicDataTypesTest.class.getResource(yangPath).getPath());
124         } catch (FileNotFoundException e) {
125             e.printStackTrace();
126         }
127         assertNotNull("modules can't be null.", modules);
128
129         InputStream xmlStream = YangAndXmlToJsonBasicDataTypesTest.class.getResourceAsStream(xmlDataPath);
130         CompositeNode compositeNode = null;
131         try {
132             compositeNode = TestUtils.loadCompositeNode(xmlStream);
133         } catch (FileNotFoundException e) {
134             e.printStackTrace();
135         }
136         assertNotNull("Composite node can't be null", compositeNode);
137
138         StructuredDataToJsonProvider structuredDataToJsonProvider = StructuredDataToJsonProvider.INSTANCE;
139         for (Module module : modules) {
140             ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
141             for (DataSchemaNode dataSchemaNode : module.getChildNodes()) {
142                 StructuredData structuredData = new StructuredData(compositeNode, dataSchemaNode);
143                 try {
144                     structuredDataToJsonProvider.writeTo(structuredData, null, null, null, null, null, byteArrayOS);
145                 } catch (WebApplicationException | IOException e) {
146                     e.printStackTrace();
147                 }
148                 assertFalse(
149                         "Returning JSON string can't be empty for node " + dataSchemaNode.getQName().getLocalName(),
150                         byteArrayOS.toString().isEmpty());
151             }
152             jsonResult = byteArrayOS.toString();
153             try {
154                 outputToFile(byteArrayOS, outputPath);
155             } catch (IOException e) {
156                 System.out.println("Output file wasn't cloased sucessfuly.");
157             }
158
159         }
160         return jsonResult;
161     }
162
163     static void outputToFile(ByteArrayOutputStream outputStream, String outputDir) throws IOException {
164         FileOutputStream fileOS = null;
165         try {
166             String path = YangAndXmlToJsonBasicDataTypesTest.class.getResource(outputDir).getPath();
167             File outFile = new File(path + "/data.json");
168             fileOS = new FileOutputStream(outFile);
169             try {
170                 fileOS.write(outputStream.toByteArray());
171             } catch (IOException e) {
172                 e.printStackTrace();
173             }
174             fileOS.close();
175         } catch (FileNotFoundException e1) {
176             e1.printStackTrace();
177         }
178     }
179
180     static String readJsonFromFile(String path, boolean removeWhiteChars) {
181         FileReader fileReader = getFileReader(path);
182
183         StringBuilder strBuilder = new StringBuilder();
184         char[] buffer = new char[1000];
185
186         while (true) {
187             int loadedCharNum;
188             try {
189                 loadedCharNum = fileReader.read(buffer);
190             } catch (IOException e) {
191                 break;
192             }
193             if (loadedCharNum == -1) {
194                 break;
195             }
196             strBuilder.append(buffer, 0, loadedCharNum);
197         }
198         try {
199             fileReader.close();
200         } catch (IOException e) {
201             System.out.println("The file wasn't closed");
202         }
203         String rawStr = strBuilder.toString();
204         if (removeWhiteChars) {
205             rawStr = rawStr.replace("\n", "");
206             rawStr = rawStr.replace("\r", "");
207             rawStr = rawStr.replace("\t", "");
208             rawStr = removeSpaces(rawStr);
209         }
210
211         return rawStr;
212     }
213
214     private static FileReader getFileReader(String path) {
215         String fullPath = YangAndXmlToJsonBasicDataTypesTest.class.getResource(path).getPath();
216         assertNotNull("Path to file can't be null.", fullPath);
217         File file = new File(fullPath);
218         assertNotNull("File can't be null", file);
219         FileReader fileReader = null;
220         try {
221             fileReader = new FileReader(file);
222         } catch (FileNotFoundException e) {
223             e.printStackTrace();
224         }
225         assertNotNull("File reader can't be null.", fileReader);
226         return fileReader;
227     }
228
229     private static String removeSpaces(String rawStr) {
230         StringBuilder strBuilder = new StringBuilder();
231         int i = 0;
232         int quoteCount = 0;
233         while (i < rawStr.length()) {
234             if (rawStr.substring(i, i + 1).equals("\"")) {
235                 quoteCount++;
236             }
237
238             if (!rawStr.substring(i, i + 1).equals(" ") || (quoteCount % 2 == 1)) {
239                 strBuilder.append(rawStr.charAt(i));
240             }
241             i++;
242         }
243
244         return strBuilder.toString();
245     }
246
247 }