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