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