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