1 package org.opendaylight.controller.sal.restconf.impl.test;
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;
10 import java.net.URISyntaxException;
13 import java.util.concurrent.Future;
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;
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;
37 import com.google.common.base.Preconditions;
39 public final class TestUtils {
41 private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
43 private final static YangModelParser parser = new YangParserImpl();
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);
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));
58 return parser.parseYangModels(testFiles);
61 public static SchemaContext loadSchemaContext(Set<Module> modules) {
62 return parser.resolveSchemaContext(modules);
65 public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
66 return parser.resolveSchemaContext(loadModules(resourceDirectory));
69 public static Module findModule(Set<Module> modules, String moduleName) {
71 for (Module module : modules) {
72 if (module.getName().equals(moduleName)) {
82 public static Document loadDocumentFrom(InputStream inputStream) {
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);
93 public static String getDocumentInPrintableForm(Document doc) {
94 Preconditions.checkNotNull(doc);
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");
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);
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);
122 normalizeCompositeNode(compositeNode, modules, dataSchemaNode, searchedModuleName + ":"
123 + searchedDataSchemaName);
126 return writeCompNodeWithSchemaContextToJson(compositeNode, modules, dataSchemaNode);
127 } catch (WebApplicationException | IOException e) {
128 // TODO Auto-generated catch block
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));
140 TestUtils.prepareMockForRestconfBeforeNormalization(modules, dataSchemaNode, restconf);
141 restconf.createConfigurationData(schemaNodePath, compositeNode);
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)) {
154 } else if (modules.size() == 1) {
155 module = modules.iterator().next();
160 public static Set<Module> resolveModules(String yangPath) {
161 Set<Module> modules = null;
164 modules = TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
165 } catch (FileNotFoundException e) {
172 public static DataSchemaNode resolveDataSchemaNode(Module module, String searchedDataSchemaName) {
173 assertNotNull("Module is missing", module);
175 DataSchemaNode dataSchemaNode = null;
176 if (searchedDataSchemaName != null) {
177 for (DataSchemaNode dsn : module.getChildNodes()) {
178 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
179 dataSchemaNode = dsn;
182 } else if (module.getChildNodes().size() == 1) {
183 dataSchemaNode = module.getChildNodes().iterator().next();
185 return dataSchemaNode;
188 public static String writeCompNodeWithSchemaContextToJson(CompositeNode compositeNode, Set<Module> modules,
189 DataSchemaNode dataSchemaNode) throws IOException, WebApplicationException {
192 assertNotNull(dataSchemaNode);
193 assertNotNull("Composite node can't be null", compositeNode);
194 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
196 ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
198 StructuredDataToJsonProvider structuredDataToJsonProvider = StructuredDataToJsonProvider.INSTANCE;
199 structuredDataToJsonProvider.writeTo(new StructuredData(compositeNode, dataSchemaNode), null, null, null, null,
202 jsonResult = byteArrayOS.toString();
207 public static CompositeNode loadCompositeNode(String xmlDataPath) {
208 InputStream xmlStream = TestUtils.class.getResourceAsStream(xmlDataPath);
209 CompositeNode compositeNode = null;
211 XmlReader xmlReader = new XmlReader();
212 compositeNode = xmlReader.read(xmlStream);
214 } catch (UnsupportedFormatException | XMLStreamException e) {
217 return compositeNode;
220 static void outputToFile(ByteArrayOutputStream outputStream, String outputDir) throws IOException {
221 FileOutputStream fileOS = null;
223 String path = TestUtils.class.getResource(outputDir).getPath();
224 File outFile = new File(path + "/data.json");
225 fileOS = new FileOutputStream(outFile);
227 fileOS.write(outputStream.toByteArray());
228 } catch (IOException e) {
232 } catch (FileNotFoundException e1) {
233 e1.printStackTrace();
237 static String readJsonFromFile(String path, boolean removeWhiteChars) {
238 FileReader fileReader = getFileReader(path);
240 StringBuilder strBuilder = new StringBuilder();
241 char[] buffer = new char[1000];
246 loadedCharNum = fileReader.read(buffer);
247 } catch (IOException e) {
250 if (loadedCharNum == -1) {
253 strBuilder.append(buffer, 0, loadedCharNum);
257 } catch (IOException e) {
258 System.out.println("The file wasn't closed");
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);
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;
278 fileReader = new FileReader(file);
279 } catch (FileNotFoundException e) {
282 assertNotNull("File reader can't be null.", fileReader);
286 private static String removeSpaces(String rawStr) {
287 StringBuilder strBuilder = new StringBuilder();
290 while (i < rawStr.length()) {
291 if (rawStr.substring(i, i + 1).equals("\"")) {
295 if (!rawStr.substring(i, i + 1).equals(" ") || (quoteCount % 2 == 1)) {
296 strBuilder.append(rawStr.charAt(i));
301 return strBuilder.toString();
304 public static QName buildQName(String name, String uri, String date) {
306 URI u = new URI(uri);
309 dt = Date.valueOf(date);
311 return new QName(u, dt, name);
312 } catch (URISyntaxException e) {
317 public static QName buildQName(String name) {
318 return buildQName(name, "", null);
321 public static void supplementNamespace(DataSchemaNode dataSchemaNode, CompositeNode compositeNode) {
322 RestconfImpl restconf = RestconfImpl.getInstance();
324 InstanceIdWithSchemaNode instIdAndSchema = new InstanceIdWithSchemaNode(mock(InstanceIdentifier.class),
327 ControllerContext controllerContext = mock(ControllerContext.class);
328 BrokerFacade broker = mock(BrokerFacade.class);
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(
337 restconf.setControllerContext(controllerContext);
338 restconf.setBroker(broker);
340 // method is called only because it contains call of method which
341 // supplement namespaces to compositeNode
342 restconf.createConfigurationData("something", compositeNode);
345 public static DataSchemaNode obtainSchemaFromYang(String yangFolder) throws FileNotFoundException {
346 return obtainSchemaFromYang(yangFolder, null);
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());
354 if (modules == null) {
357 if (modules.size() < 1) {
361 Module moduleRes = null;
362 if (modules.size() > 1) {
363 if (moduleName == null) {
366 for (Module module : modules) {
367 if (module.getName().equals(moduleName)) {
371 if (moduleRes == null) {
376 moduleRes = modules.iterator().next();
379 if (moduleRes.getChildNodes() == null) {
383 if (moduleRes.getChildNodes().size() != 1) {
386 DataSchemaNode dataSchemaNode = moduleRes.getChildNodes().iterator().next();
387 return dataSchemaNode;
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);
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());
406 BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
407 when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
409 new DummyFuture.Builder().rpcResult(
410 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
412 restconf.setBroker(mockedBrokerFacade);
415 static CompositeNode loadCompositeNodeWithXmlTreeBuilder(String xmlDataPath) {
416 InputStream xmlStream = TestUtils.class.getResourceAsStream(xmlDataPath);
417 CompositeNode compositeNode = null;
419 compositeNode = TestUtils.loadCompositeNodeWithXmlTreeBuilder(xmlStream);
420 } catch (FileNotFoundException e) {
423 return compositeNode;
430 public static CompositeNode loadCompositeNodeWithXmlTreeBuilder(InputStream xmlInputStream) throws FileNotFoundException {
431 if (xmlInputStream == null) {
432 throw new IllegalArgumentException();
436 dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream);
437 } catch (XMLStreamException e) {
438 logger.error("Error during building data tree from XML", e);
441 if (dataTree == null) {
442 logger.error("data tree is null");
445 if (dataTree instanceof SimpleNode) {
446 logger.error("RPC XML was resolved as SimpleNode");
449 return (CompositeNode) dataTree;