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