More test for improving of code coverage + test refactoring
[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.junit.Assert.assertTrue;
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.URI;
11 import java.net.URISyntaxException;
12 import java.sql.Date;
13 import java.util.*;
14
15 import javax.ws.rs.WebApplicationException;
16 import javax.ws.rs.ext.MessageBodyReader;
17 import javax.ws.rs.ext.MessageBodyWriter;
18 import javax.xml.parsers.*;
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.UnsupportedFormatException;
26 import org.opendaylight.controller.sal.rest.impl.XmlReader;
27 import org.opendaylight.controller.sal.restconf.impl.*;
28 import org.opendaylight.controller.sal.restconf.impl.json.to.cnsn.test.JsonToCnSnTest;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
32 import org.opendaylight.yangtools.yang.model.api.*;
33 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
34 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.w3c.dom.Document;
38 import org.xml.sax.SAXException;
39
40 import com.google.common.base.Preconditions;
41
42 public final class TestUtils {
43
44     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
45
46     private final static YangModelParser parser = new YangParserImpl();
47
48     public static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
49         final File testDir = new File(resourceDirectory);
50         final String[] fileList = testDir.list();
51         final List<File> testFiles = new ArrayList<File>();
52         if (fileList == null) {
53             throw new FileNotFoundException(resourceDirectory);
54         }
55         for (int i = 0; i < fileList.length; i++) {
56             String fileName = fileList[i];
57             if (new File(testDir, fileName).isDirectory() == false) {
58                 testFiles.add(new File(testDir, fileName));
59             }
60         }
61         return parser.parseYangModels(testFiles);
62     }
63
64     public static SchemaContext loadSchemaContext(Set<Module> modules) {
65         return parser.resolveSchemaContext(modules);
66     }
67
68     public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
69         return parser.resolveSchemaContext(loadModules(resourceDirectory));
70     }
71
72     public static Module findModule(Set<Module> modules, String moduleName) {
73         Module result = null;
74         for (Module module : modules) {
75             if (module.getName().equals(moduleName)) {
76                 result = module;
77                 break;
78             }
79         }
80         return result;
81     }
82
83     public static Document loadDocumentFrom(InputStream inputStream) {
84         try {
85             DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
86             DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
87             return docBuilder.parse(inputStream);
88         } catch (SAXException | IOException | ParserConfigurationException e) {
89             LOG.error("Error during loading Document from XML", e);
90             return null;
91         }
92     }
93
94     public static String getDocumentInPrintableForm(Document doc) {
95         Preconditions.checkNotNull(doc);
96         try {
97             ByteArrayOutputStream out = new ByteArrayOutputStream();
98             TransformerFactory tf = TransformerFactory.newInstance();
99             Transformer transformer = tf.newTransformer();
100             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
101             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
102             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
103             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
104             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
105
106             transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
107             byte[] charData = out.toByteArray();
108             return new String(charData, "UTF-8");
109         } catch (IOException | TransformerException e) {
110             String msg = "Error during transformation of Document into String";
111             LOG.error(msg, e);
112             return msg;
113         }
114
115     }
116
117     /**
118      * 
119      * Fill missing data (namespaces) and build correct data type in
120      * {@code compositeNode} according to {@code dataSchemaNode}. The method
121      * {@link RestconfImpl#createConfigurationData createConfigurationData} is
122      * used because it contains calling of method {code normalizeNode}
123      */
124     public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
125         RestconfImpl restconf = RestconfImpl.getInstance();
126         ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
127
128         prepareMockForRestconfBeforeNormalization(modules, restconf);
129         restconf.createConfigurationData(schemaNodePath, compositeNode);
130     }
131
132     public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
133         assertNotNull("modules can't be null.", modules);
134         if (searchedModuleName != null) {
135             for (Module m : modules) {
136                 if (m.getName().equals(searchedModuleName)) {
137                     return m;
138                 }
139             }
140         } else if (modules.size() == 1) {
141             return modules.iterator().next();
142         }
143         return null;
144     }
145
146     public static Set<Module> resolveModulesFrom(String yangPath) {
147         try {
148             return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
149         } catch (FileNotFoundException e) {
150             LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
151         }
152
153         return null;
154     }
155
156     public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
157         assertNotNull("Module can't be null", module);
158
159         if (searchedDataSchemaName != null) {
160             for (DataSchemaNode dsn : module.getChildNodes()) {
161                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
162                     return dsn;
163                 }
164             }
165         } else if (module.getChildNodes().size() == 1) {
166             return module.getChildNodes().iterator().next();
167         }
168         return null;
169     }
170
171     public static CompositeNode loadCompositeNode(String xmlDataPath) {
172         return loadCompositeNode(xmlDataPath, false);
173     }
174
175     public static CompositeNode loadCompositeNode(String xmlDataPath, boolean addDumyNamespace) {
176         InputStream xmlStream = TestUtils.class.getResourceAsStream(xmlDataPath);
177         CompositeNode compositeNode = null;
178         try {
179             XmlReader xmlReader = new XmlReader();
180             compositeNode = xmlReader.read(xmlStream);
181         } catch (UnsupportedFormatException | XMLStreamException e) {
182             LOG.error(e.getMessage());
183         }
184         if (addDumyNamespace) {
185             try {
186                 addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
187             } catch (URISyntaxException e) {
188                 LOG.error(e.getMessage());
189             }
190         }
191         return compositeNode;
192     }
193
194     public static QName buildQName(String name, String uri, String date, String prefix) {
195         try {
196             URI u = new URI(uri);
197             Date dt = null;
198             if (date != null) {
199                 dt = Date.valueOf(date);
200             }
201             return new QName(u, dt, prefix, name);
202         } catch (URISyntaxException e) {
203             return null;
204         }
205     }
206
207     public static QName buildQName(String name, String uri, String date) {
208         return buildQName(name, uri, date, null);
209     }
210
211     public static QName buildQName(String name) {
212         return buildQName(name, "", null);
213     }
214
215     public static DataSchemaNode obtainSchemaFromYang(String yangFolder) throws FileNotFoundException {
216         return obtainSchemaFromYang(yangFolder, null);
217     }
218
219     public static DataSchemaNode obtainSchemaFromYang(String yangFolder, String moduleName)
220             throws FileNotFoundException {
221         Set<Module> modules = null;
222         modules = TestUtils.loadModules(TestUtils.class.getResource(yangFolder).getPath());
223
224         if (modules == null) {
225             return null;
226         }
227         if (modules.size() < 1) {
228             return null;
229         }
230
231         Module moduleRes = null;
232         if (modules.size() > 1) {
233             if (moduleName == null) {
234                 return null;
235             } else {
236                 for (Module module : modules) {
237                     if (module.getName().equals(moduleName)) {
238                         moduleRes = module;
239                     }
240                 }
241                 if (moduleRes == null) {
242                     return null;
243                 }
244             }
245         } else {
246             moduleRes = modules.iterator().next();
247         }
248
249         if (moduleRes.getChildNodes() == null) {
250             return null;
251         }
252
253         if (moduleRes.getChildNodes().size() != 1) {
254             return null;
255         }
256         DataSchemaNode dataSchemaNode = moduleRes.getChildNodes().iterator().next();
257         return dataSchemaNode;
258     }
259
260     public static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
261         wrappedNode.setNamespace(new URI(""));
262         if (wrappedNode instanceof CompositeNodeWrapper) {
263             for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
264                 addDummyNamespaceToAllNodes(childNodeWrapper);
265             }
266         }
267     }
268
269     private static void prepareMockForRestconfBeforeNormalization(Set<Module> modules, RestconfImpl restconf) {
270
271         ControllerContext controllerContext = ControllerContext.getInstance();
272         BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
273
274         controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
275
276         when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
277                 .thenReturn(
278                         new DummyFuture.Builder().rpcResult(
279                                 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
280                                         .build()).build());
281
282         restconf.setControllerContext(ControllerContext.getInstance());
283         restconf.setBroker(mockedBrokerFacade);
284     }
285
286     public static CompositeNode readInputToCnSn(String jsonPath, boolean dummyNamespaces,
287             MessageBodyReader<CompositeNode> reader) throws WebApplicationException {
288
289         InputStream jsonStream = JsonToCnSnTest.class.getResourceAsStream(jsonPath);
290         try {
291             CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, jsonStream);
292             assertTrue(compositeNode instanceof CompositeNodeWrapper);
293             if (dummyNamespaces) {
294                 try {
295                     TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
296                     return ((CompositeNodeWrapper) compositeNode).unwrap();
297                 } catch (URISyntaxException e) {
298                     LOG.error(e.getMessage());
299                     assertTrue(e.getMessage(), false);
300                 }
301             }
302             return compositeNode;
303         } catch (IOException e) {
304             LOG.error(e.getMessage());
305             assertTrue(e.getMessage(), false);
306         }
307         return null;
308     }
309
310     public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set<Module> modules,
311             DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
312             WebApplicationException {
313
314         assertNotNull(dataSchemaNode);
315         assertNotNull("Composite node can't be null", compositeNode);
316         ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
317
318         ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
319
320         messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode), null, null, null, null, null,
321                 byteArrayOS);
322
323         return byteArrayOS.toString();
324
325     }
326
327 }