Merge "Ganymed patch fix"
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / YangAndXmlToJsonConversion.java
1 package org.opendaylight.controller.sal.restconf.impl.test;
2
3 import static org.junit.Assert.*;
4
5 import java.io.*;
6 import java.util.Set;
7 import java.util.regex.*;
8
9 import javax.ws.rs.WebApplicationException;
10
11 import org.junit.*;
12 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
13 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
14 import org.opendaylight.yangtools.yang.model.api.*;
15 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
16
17 public class YangAndXmlToJsonConversion {
18
19     @Ignore
20     @Test
21     /**
22      * Test for simple yang types (leaf, list, leaf-list, container and various combination of them)
23      * 
24      */
25     public void simpleYangTypesTest() {
26         String jsonOutput = null;
27
28         jsonOutput = convertXmlDataAndYangToJson("/yang-to-json-conversion/simple-yang-types/xml/data.xml",
29                 "/yang-to-json-conversion/simple-yang-types");
30
31 //         jsonOutput =
32 //         readJsonFromFile("/yang-to-json-conversion/simple-yang-types/xml/output.json");
33
34         verifyJsonOutputForSimpleYangTypes(jsonOutput);
35
36     }
37
38     private void verifyJsonOutputForSimpleYangTypes(String jsonOutput) {
39
40         assertTrue("First and last character has to be '{' and '}'", Pattern.compile("\\A\\{.*\\}\\z", Pattern.DOTALL)
41                 .matcher(jsonOutput).matches());
42
43         String prefix = "\"(smptp:|)";
44
45         // subnodes of cont1
46         String cont1 = prefix + "cont1\":\\{";
47         testLeaf(cont1, "lf11", new String("lf"), jsonOutput, prefix);
48         testLeafList(cont1, "lflst11", jsonOutput, prefix, new Integer(55), new Integer(56), new Integer(57));
49         testLeafList(cont1, "lflst12", jsonOutput, prefix, new String("lflst12 str1"), new String("lflst12 str2"),
50                 new String("lflst12 str1"));
51
52         // subnodes of lst111
53         // first object of lst111
54         String lst11 = cont1 + ".*" + prefix + "lst11\":\\[\\{";
55         testLeaf(lst11, "lf111", new Integer(140), jsonOutput, prefix);
56         testLeaf(lst11, "lf112", new String("lf112 str"), jsonOutput, prefix);
57
58         // subnodes of cont111
59         String cont111 = lst11 + ".*" + prefix + "cont111\":\\{";
60         testLeaf(cont111, "lf1111", new String("lf1111 str"), jsonOutput, prefix);
61         testLeafList(cont1, "lflst1111", jsonOutput, prefix, new Integer(2048), new Integer(1024), new Integer(4096));
62
63         // subnodes of lst1111
64         String lst1111 = cont111 + ".*" + prefix + "lst1111\":\\[\\{";
65         testLeaf(lst1111, "lf1111A", new String("lf1111A str11"), jsonOutput, prefix);
66         testLeaf(lst1111, "lf1111B", new Integer(4), jsonOutput, prefix);
67         testLeaf(lst1111, "lf1111A", new String("lf1111A str12"), jsonOutput, prefix);
68         testLeaf(lst1111, "lf1111B", new Integer(7), jsonOutput, prefix);
69         // :subnodes of lst1111
70         // :subnodes of cont111
71         // :first object of lst111
72
73         // second object of lst111
74         testLeaf(lst11, "lf111", new Integer(141), jsonOutput, prefix);
75         testLeaf(lst11, "lf112", new String("lf112 str2"), jsonOutput, prefix);
76
77         // subnodes of cont111
78         testLeaf(cont111, "lf1111", new String("lf1111 str2"), jsonOutput, prefix);
79         testLeafList(cont1, "lflst1111", jsonOutput, prefix, new Integer(2049), new Integer(1025), new Integer(4097));
80
81         // subnodes of lst1111
82         testLeaf(lst1111, "lf1111A", new String("lf1111A str21"), jsonOutput, prefix);
83         testLeaf(lst1111, "lf1111B", new Integer(5), jsonOutput, prefix);
84         testLeaf(lst1111, "lf1111A", new String("lf1111A str22"), jsonOutput, prefix);
85         testLeaf(lst1111, "lf1111B", new Integer(8), jsonOutput, prefix);
86         // :subnodes of lst111
87         // :subnodes of cont111
88         // :second object of lst111
89         // :second object of lst111
90         // :subnodes of cont1
91     }
92
93     private void testLeaf(String prevRegEx, String lstName, Object value, String jsonFile, String elementPrefix) {
94         String newValue = null;
95         if (value instanceof Integer) {
96             newValue = value.toString();
97         } else if (value instanceof String) {
98             newValue = "\"" + value.toString() + "\"";
99         }
100         String lf = elementPrefix + lstName + "\":" + newValue;
101         assertTrue(">>\"" + lstName + "\":" + newValue + "<< is missing",
102                 Pattern.compile(".*" + prevRegEx + ".*" + lf + ".*", Pattern.DOTALL).matcher(jsonFile).matches());
103
104     }
105
106     private void testLeafList(String prevRegEx, String lflstName, String jsonFile, String elementPrefix,
107             Object... dataInList) {
108         // order of element in the list isn't defined :(
109         String lflstBegin = elementPrefix + lflstName + "\":\\[";
110         String lflstEnd = ".*\\],";
111         assertTrue(
112                 ">>\"" + lflstName + "\": [],<< is missing",
113                 Pattern.compile(".*" + prevRegEx + ".*" + lflstBegin + lflstEnd + ".*", Pattern.DOTALL)
114                         .matcher(jsonFile).matches());
115
116         for (Object obj : dataInList) {
117             testValueOfLeafList(prevRegEx, lflstBegin, obj, jsonFile);
118         }
119     }
120
121     private void testValueOfLeafList(String prevRegEx, String lflstPrevRegEx, Object value, String jsonFile) {
122         String lflstData = null;
123         lflstData = regExForDataValueInList(value);
124         assertNotNull(lflstPrevRegEx + ": value doesn't have correct type.", lflstData);
125         assertTrue(
126                 prevRegEx + ": data value >" + value + "< is missing.",
127                 Pattern.compile(".*" + prevRegEx + ".*" + lflstPrevRegEx + lflstData + ".*", Pattern.DOTALL)
128                         .matcher(jsonFile).matches());
129
130     }
131
132     /**
133      * Data value can be first, inner, last or only one member of list
134      * 
135      * @param dataValue
136      * @return
137      */
138     private String regExForDataValueInList(Object dataValue) {
139         String newDataValue;
140         if (dataValue instanceof Integer) {
141             newDataValue = dataValue.toString();
142             return "(" + newDataValue + "(,[0-9]+)+|([0-9]+,)+" + newDataValue + "(,[0-9]+)+|([0-9]+,)+" + newDataValue
143                     + "|" + newDataValue + ")\\]";
144         } else if (dataValue instanceof String) {
145             newDataValue = "\"" + dataValue.toString() + "\"";
146             return "(" + newDataValue + "(,\".+\")+|(\".+\",)+" + newDataValue + "(,\".+\")+|(\".+\",)+" + newDataValue
147                     + "|" + newDataValue + ")\\]";
148         }
149         return null;
150     }
151
152     private String readJsonFromFile(String path) {
153         String fullPath = YangAndXmlToJsonConversion.class.getResource(path).getPath();
154         assertNotNull("Path to file can't be null.", fullPath);
155         File file = new File(fullPath);
156         assertNotNull("File can't be null", file);
157         FileReader fileReader = null;
158         try {
159             fileReader = new FileReader(file);
160         } catch (FileNotFoundException e) {
161             e.printStackTrace();
162         }
163         assertNotNull("File reader can't be null.", fileReader);
164
165         StringBuilder strBuilder = new StringBuilder();
166         char[] buffer = new char[1000];
167
168         while (true) {
169             int loadedCharNum;
170             try {
171                 loadedCharNum = fileReader.read(buffer);
172             } catch (IOException e) {
173                 break;
174             }
175             if (loadedCharNum == -1) {
176                 break;
177             }
178             strBuilder.append(buffer, 0, loadedCharNum);
179         }
180         try {
181             fileReader.close();
182         } catch (IOException e) {
183             System.out.println("The file wasn't closed");
184             ;
185         }
186         String rawStr = strBuilder.toString();
187         rawStr = rawStr.replace("\n", "");
188         rawStr = rawStr.replace("\r", "");
189         rawStr = rawStr.replace("\t", "");
190         rawStr = removeSpaces(rawStr);
191
192         return rawStr;
193     }
194
195     private String removeSpaces(String rawStr) {
196         StringBuilder strBuilder = new StringBuilder();
197         int i = 0;
198         int quoteCount = 0;
199         while (i < rawStr.length()) {
200             if (rawStr.substring(i, i + 1).equals("\"")) {
201                 quoteCount++;
202             }
203
204             if (!rawStr.substring(i, i + 1).equals(" ") || (quoteCount % 2 == 1)) {
205                 strBuilder.append(rawStr.charAt(i));
206             }
207             i++;
208         }
209
210         return strBuilder.toString();
211     }
212
213     private String convertXmlDataAndYangToJson(String xmlDataPath, String yangPath) {
214         String jsonResult = null;
215         Set<Module> modules = null;
216
217         try {
218             modules = TestUtils.loadModules(YangAndXmlToJsonConversion.class.getResource(yangPath).getPath());
219         } catch (FileNotFoundException e) {
220             e.printStackTrace();
221         }
222         assertNotNull("modules can't be null.", modules);
223
224         InputStream xmlStream = YangAndXmlToJsonConversion.class.getResourceAsStream(xmlDataPath);
225         CompositeNode compositeNode = null;
226         try {
227             compositeNode = TestUtils.loadCompositeNode(xmlStream);
228         } catch (FileNotFoundException e) {
229             e.printStackTrace();
230         }
231         assertNotNull("Composite node can't be null", compositeNode);
232
233         StructuredDataToJsonProvider structuredDataToJsonProvider = StructuredDataToJsonProvider.INSTANCE;
234         for (Module module : modules) {
235             for (DataSchemaNode dataSchemaNode : module.getChildNodes()) {
236                 StructuredData structuredData = new StructuredData(compositeNode, dataSchemaNode);
237                 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
238                 try {
239                     structuredDataToJsonProvider.writeTo(structuredData, null, null, null, null, null, byteArrayOS);
240                 } catch (WebApplicationException | IOException e) {
241                     e.printStackTrace();
242                 }
243                 assertFalse(
244                         "Returning JSON string can't be empty for node " + dataSchemaNode.getQName().getLocalName(),
245                         byteArrayOS.toString().isEmpty());
246                 jsonResult = byteArrayOS.toString();
247                 try {
248                     outputToFile(byteArrayOS);
249                 } catch (IOException e) {
250                     System.out.println("Output file wasn't cloased sucessfuly.");
251                 }
252             }
253         }
254         return jsonResult;
255     }
256
257     private void outputToFile(ByteArrayOutputStream outputStream) throws IOException {
258         FileOutputStream fileOS = null;
259         try {
260             String path = YangAndXmlToJsonConversion.class.getResource("/yang-to-json-conversion/xml").getPath();
261             File outFile = new File(path + "/data.json");
262             fileOS = new FileOutputStream(outFile);
263             try {
264                 fileOS.write(outputStream.toByteArray());
265             } catch (IOException e) {
266                 e.printStackTrace();
267             }
268             fileOS.close();
269         } catch (FileNotFoundException e1) {
270             e1.printStackTrace();
271         }
272     }
273 }