Switched codecs infrastructure to use yang-data-impl codecs
[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.assertNotNull;
4 import static org.mockito.Matchers.any;
5 import static org.mockito.Mockito.mock;
6 import static org.mockito.Mockito.when;
7
8 import java.io.*;
9 import java.net.URI;
10 import java.net.URISyntaxException;
11 import java.sql.Date;
12 import java.util.*;
13 import java.util.concurrent.Future;
14
15 import javax.ws.rs.WebApplicationException;
16 import javax.xml.parsers.*;
17 import javax.xml.stream.XMLStreamException;
18 import javax.xml.transform.*;
19 import javax.xml.transform.dom.DOMSource;
20 import javax.xml.transform.stream.StreamResult;
21
22 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
23 import org.opendaylight.controller.sal.rest.impl.*;
24 import org.opendaylight.controller.sal.restconf.impl.*;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.RpcResult;
27 import org.opendaylight.yangtools.yang.data.api.*;
28 import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder;
29 import org.opendaylight.yangtools.yang.model.api.*;
30 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
31 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.w3c.dom.Document;
35 import org.xml.sax.SAXException;
36
37 import com.google.common.base.Preconditions;
38
39 public final class TestUtils {
40
41     private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
42
43     private final static YangModelParser parser = new YangParserImpl();
44
45     public static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
46         final File testDir = new File(resourceDirectory);
47         final String[] fileList = testDir.list();
48         final List<File> testFiles = new ArrayList<File>();
49         if (fileList == null) {
50             throw new FileNotFoundException(resourceDirectory);
51         }
52         for (int i = 0; i < fileList.length; i++) {
53             String fileName = fileList[i];
54             if (new File(testDir, fileName).isDirectory() == false) {
55                 testFiles.add(new File(testDir, fileName));
56             }
57         }
58         return parser.parseYangModels(testFiles);
59     }
60
61     public static SchemaContext loadSchemaContext(Set<Module> modules) {
62         return parser.resolveSchemaContext(modules);
63     }
64
65     public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
66         return parser.resolveSchemaContext(loadModules(resourceDirectory));
67     }
68
69     public static Module findModule(Set<Module> modules, String moduleName) {
70         Module result = null;
71         for (Module module : modules) {
72             if (module.getName().equals(moduleName)) {
73                 result = module;
74                 break;
75             }
76         }
77         return result;
78     }
79
80
81
82     public static Document loadDocumentFrom(InputStream inputStream) {
83         try {
84             DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
85             DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
86             return docBuilder.parse(inputStream);
87         } catch (SAXException | IOException | ParserConfigurationException e) {
88             logger.error("Error during loading Document from XML", e);
89             return null;
90         }
91     }
92
93     public static String getDocumentInPrintableForm(Document doc) {
94         Preconditions.checkNotNull(doc);
95         try {
96             ByteArrayOutputStream out = new ByteArrayOutputStream();
97             TransformerFactory tf = TransformerFactory.newInstance();
98             Transformer transformer = tf.newTransformer();
99             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
100             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
101             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
102             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
103             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
104
105             transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
106             byte[] charData = out.toByteArray();
107             return new String(charData, "UTF-8");
108         } catch (IOException | TransformerException e) {
109             String msg = "Error during transformation of Document into String";
110             logger.error(msg, e);
111             return msg;
112         }
113
114     }
115
116     public static String convertCompositeNodeDataAndYangToJson(CompositeNode compositeNode, String yangPath,
117             String outputPath, String searchedModuleName, String searchedDataSchemaName) {
118         Set<Module> modules = resolveModules(yangPath);
119         Module module = resolveModule(searchedModuleName, modules);
120         DataSchemaNode dataSchemaNode = resolveDataSchemaNode(module, searchedDataSchemaName);
121
122         normalizeCompositeNode(compositeNode, modules, dataSchemaNode, searchedModuleName + ":"
123                 + searchedDataSchemaName);
124
125         try {
126             return writeCompNodeWithSchemaContextToJson(compositeNode, modules, dataSchemaNode);
127         } catch (WebApplicationException | IOException e) {
128             // TODO Auto-generated catch block
129             e.printStackTrace();
130         }
131         return null;
132
133     }
134
135     public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules,
136             DataSchemaNode dataSchemaNode, String schemaNodePath) {
137         RestconfImpl restconf = RestconfImpl.getInstance();
138         ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
139
140         TestUtils.prepareMockForRestconfBeforeNormalization(modules, dataSchemaNode, restconf);
141         restconf.createConfigurationData(schemaNodePath, compositeNode);
142     }
143
144     public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
145         assertNotNull("modules can't be null.", modules);
146         Module module = null;
147         if (searchedModuleName != null) {
148             for (Module m : modules) {
149                 if (m.getName().equals(searchedModuleName)) {
150                     module = m;
151                     break;
152                 }
153             }
154         } else if (modules.size() == 1) {
155             module = modules.iterator().next();
156         }
157         return module;
158     }
159
160     public static Set<Module> resolveModules(String yangPath) {
161         Set<Module> modules = null;
162
163         try {
164             modules = TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
165         } catch (FileNotFoundException e) {
166             e.printStackTrace();
167         }
168
169         return modules;
170     }
171
172     public static DataSchemaNode resolveDataSchemaNode(Module module, String searchedDataSchemaName) {
173         assertNotNull("Module is missing", module);
174
175         DataSchemaNode dataSchemaNode = null;
176         if (searchedDataSchemaName != null) {
177             for (DataSchemaNode dsn : module.getChildNodes()) {
178                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
179                     dataSchemaNode = dsn;
180                 }
181             }
182         } else if (module.getChildNodes().size() == 1) {
183             dataSchemaNode = module.getChildNodes().iterator().next();
184         }
185         return dataSchemaNode;
186     }
187
188     public static String writeCompNodeWithSchemaContextToJson(CompositeNode compositeNode, Set<Module> modules,
189             DataSchemaNode dataSchemaNode) throws IOException, WebApplicationException {
190         String jsonResult;
191
192         assertNotNull(dataSchemaNode);
193         assertNotNull("Composite node can't be null", compositeNode);
194         ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
195
196         ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
197
198         StructuredDataToJsonProvider structuredDataToJsonProvider = StructuredDataToJsonProvider.INSTANCE;
199         structuredDataToJsonProvider.writeTo(new StructuredData(compositeNode, dataSchemaNode), null, null, null, null,
200                 null, byteArrayOS);
201
202         jsonResult = byteArrayOS.toString();
203
204         return jsonResult;
205     }
206
207     public static CompositeNode loadCompositeNode(String xmlDataPath) {
208         InputStream xmlStream = TestUtils.class.getResourceAsStream(xmlDataPath);
209         CompositeNode compositeNode = null;
210         try {
211             XmlReader xmlReader = new XmlReader();
212             compositeNode = xmlReader.read(xmlStream);
213
214         } catch (UnsupportedFormatException | XMLStreamException e) {
215             e.printStackTrace();
216         }
217         return compositeNode;
218     }
219
220     static void outputToFile(ByteArrayOutputStream outputStream, String outputDir) throws IOException {
221         FileOutputStream fileOS = null;
222         try {
223             String path = TestUtils.class.getResource(outputDir).getPath();
224             File outFile = new File(path + "/data.json");
225             fileOS = new FileOutputStream(outFile);
226             try {
227                 fileOS.write(outputStream.toByteArray());
228             } catch (IOException e) {
229                 e.printStackTrace();
230             }
231             fileOS.close();
232         } catch (FileNotFoundException e1) {
233             e1.printStackTrace();
234         }
235     }
236
237     static String readJsonFromFile(String path, boolean removeWhiteChars) {
238         FileReader fileReader = getFileReader(path);
239
240         StringBuilder strBuilder = new StringBuilder();
241         char[] buffer = new char[1000];
242
243         while (true) {
244             int loadedCharNum;
245             try {
246                 loadedCharNum = fileReader.read(buffer);
247             } catch (IOException e) {
248                 break;
249             }
250             if (loadedCharNum == -1) {
251                 break;
252             }
253             strBuilder.append(buffer, 0, loadedCharNum);
254         }
255         try {
256             fileReader.close();
257         } catch (IOException e) {
258             System.out.println("The file wasn't closed");
259         }
260         String rawStr = strBuilder.toString();
261         if (removeWhiteChars) {
262             rawStr = rawStr.replace("\n", "");
263             rawStr = rawStr.replace("\r", "");
264             rawStr = rawStr.replace("\t", "");
265             rawStr = removeSpaces(rawStr);
266         }
267
268         return rawStr;
269     }
270
271     private static FileReader getFileReader(String path) {
272         String fullPath = TestUtils.class.getResource(path).getPath();
273         assertNotNull("Path to file can't be null.", fullPath);
274         File file = new File(fullPath);
275         assertNotNull("File can't be null", file);
276         FileReader fileReader = null;
277         try {
278             fileReader = new FileReader(file);
279         } catch (FileNotFoundException e) {
280             e.printStackTrace();
281         }
282         assertNotNull("File reader can't be null.", fileReader);
283         return fileReader;
284     }
285
286     private static String removeSpaces(String rawStr) {
287         StringBuilder strBuilder = new StringBuilder();
288         int i = 0;
289         int quoteCount = 0;
290         while (i < rawStr.length()) {
291             if (rawStr.substring(i, i + 1).equals("\"")) {
292                 quoteCount++;
293             }
294
295             if (!rawStr.substring(i, i + 1).equals(" ") || (quoteCount % 2 == 1)) {
296                 strBuilder.append(rawStr.charAt(i));
297             }
298             i++;
299         }
300
301         return strBuilder.toString();
302     }
303
304     public static QName buildQName(String name, String uri, String date) {
305         try {
306             URI u = new URI(uri);
307             Date dt = null;
308             if (date != null) {
309                 dt = Date.valueOf(date);
310             }
311             return new QName(u, dt, name);
312         } catch (URISyntaxException e) {
313             return null;
314         }
315     }
316
317     public static QName buildQName(String name) {
318         return buildQName(name, "", null);
319     }
320
321     public static void supplementNamespace(DataSchemaNode dataSchemaNode, CompositeNode compositeNode) {
322         RestconfImpl restconf = RestconfImpl.getInstance();
323
324         InstanceIdWithSchemaNode instIdAndSchema = new InstanceIdWithSchemaNode(mock(InstanceIdentifier.class),
325                 dataSchemaNode);
326
327         ControllerContext controllerContext = mock(ControllerContext.class);
328         BrokerFacade broker = mock(BrokerFacade.class);
329
330         RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(
331                 TransactionStatus.COMMITED).build();
332         Future<RpcResult<TransactionStatus>> future = DummyFuture.builder().rpcResult(rpcResult).build();
333         when(controllerContext.toInstanceIdentifier(any(String.class))).thenReturn(instIdAndSchema);
334         when(broker.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class))).thenReturn(
335                 future);
336
337         restconf.setControllerContext(controllerContext);
338         restconf.setBroker(broker);
339
340         // method is called only because it contains call of method which
341         // supplement namespaces to compositeNode
342         restconf.createConfigurationData("something", compositeNode);
343     }
344
345     public static DataSchemaNode obtainSchemaFromYang(String yangFolder) throws FileNotFoundException {
346         return obtainSchemaFromYang(yangFolder, null);
347     }
348
349     public static DataSchemaNode obtainSchemaFromYang(String yangFolder, String moduleName)
350             throws FileNotFoundException {
351         Set<Module> modules = null;
352         modules = TestUtils.loadModules(TestUtils.class.getResource(yangFolder).getPath());
353
354         if (modules == null) {
355             return null;
356         }
357         if (modules.size() < 1) {
358             return null;
359         }
360
361         Module moduleRes = null;
362         if (modules.size() > 1) {
363             if (moduleName == null) {
364                 return null;
365             } else {
366                 for (Module module : modules) {
367                     if (module.getName().equals(moduleName)) {
368                         moduleRes = module;
369                     }
370                 }
371                 if (moduleRes == null) {
372                     return null;
373                 }
374             }
375         } else {
376             moduleRes = modules.iterator().next();
377         }
378
379         if (moduleRes.getChildNodes() == null) {
380             return null;
381         }
382
383         if (moduleRes.getChildNodes().size() != 1) {
384             return null;
385         }
386         DataSchemaNode dataSchemaNode = moduleRes.getChildNodes().iterator().next();
387         return dataSchemaNode;
388
389     }
390
391     public static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
392         wrappedNode.setNamespace(new URI(""));
393         if (wrappedNode instanceof CompositeNodeWrapper) {
394             for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
395                 addDummyNamespaceToAllNodes(childNodeWrapper);
396             }
397         }
398     }
399
400     public static void prepareMockForRestconfBeforeNormalization(Set<Module> modules, DataSchemaNode dataSchemaNode,
401             RestconfImpl restconf) {
402         ControllerContext instance = ControllerContext.getInstance();
403         instance.setSchemas(TestUtils.loadSchemaContext(modules));
404         restconf.setControllerContext(ControllerContext.getInstance());
405
406         BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
407         when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
408                 .thenReturn(
409                         new DummyFuture.Builder().rpcResult(
410                                 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
411                                         .build()).build());
412         restconf.setBroker(mockedBrokerFacade);
413     }
414     
415     static CompositeNode loadCompositeNodeWithXmlTreeBuilder(String xmlDataPath) {
416         InputStream xmlStream = TestUtils.class.getResourceAsStream(xmlDataPath);
417         CompositeNode compositeNode = null;
418         try {
419             compositeNode = TestUtils.loadCompositeNodeWithXmlTreeBuilder(xmlStream);
420         } catch (FileNotFoundException e) {
421             e.printStackTrace();
422         }
423         return compositeNode;
424         
425         
426         
427     }
428     
429     
430     public static CompositeNode loadCompositeNodeWithXmlTreeBuilder(InputStream xmlInputStream) throws FileNotFoundException {
431         if (xmlInputStream == null) {
432             throw new IllegalArgumentException();
433         }
434         Node<?> dataTree;
435         try {
436             dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream);
437         } catch (XMLStreamException e) {
438             logger.error("Error during building data tree from XML", e);
439             return null;
440         }
441         if (dataTree == null) {
442             logger.error("data tree is null");
443             return null;
444         }
445         if (dataTree instanceof SimpleNode) {
446             logger.error("RPC XML was resolved as SimpleNode");
447             return null;
448         }
449         return (CompositeNode) dataTree;
450     }        
451
452 }