1 package org.opendaylight.controller.sal.restconf.impl.test;
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;
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.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;
32 import org.w3c.dom.Document;
33 import org.xml.sax.SAXException;
35 import com.google.common.base.Preconditions;
37 final class TestUtils {
39 private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
41 private final static YangModelParser parser = new YangParserImpl();
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);
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));
56 return parser.parseYangModels(testFiles);
59 public static SchemaContext loadSchemaContext(Set<Module> modules) {
60 return parser.resolveSchemaContext(modules);
63 public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
64 return parser.resolveSchemaContext(loadModules(resourceDirectory));
67 public static Module findModule(Set<Module> modules, String moduleName) {
69 for (Module module : modules) {
70 if (module.getName().equals(moduleName)) {
78 public static CompositeNode loadCompositeNode(InputStream xmlInputStream) throws FileNotFoundException {
79 if (xmlInputStream == null) {
80 throw new IllegalArgumentException();
84 dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream);
85 } catch (XMLStreamException e) {
86 logger.error("Error during building data tree from XML", e);
89 if (dataTree == null) {
90 logger.error("data tree is null");
93 if (dataTree instanceof SimpleNode) {
94 logger.error("RPC XML was resolved as SimpleNode");
97 return (CompositeNode) dataTree;
100 public static Document loadDocumentFrom(InputStream inputStream) {
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);
111 public static String getDocumentInPrintableForm(Document doc) {
112 Preconditions.checkNotNull(doc);
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");
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);
134 static String convertCompositeNodeDataAndYangToJson(CompositeNode compositeNode, String yangPath, String outputPath) {
135 return convertCompositeNodeDataAndYangToJson(compositeNode, yangPath, outputPath, null, null);
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);
145 return writeCompNodeWithSchemaContextToJson(compositeNode, outputPath, modules, dataSchemaNode);
146 } catch (WebApplicationException | IOException e) {
147 // TODO Auto-generated catch block
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)) {
164 } else if (modules.size() == 1) {
165 module = modules.iterator().next();
170 static Set<Module> resolveModules(String yangPath) {
171 Set<Module> modules = null;
174 modules = TestUtils.loadModules(ToJsonBasicDataTypesTest.class.getResource(yangPath).getPath());
175 } catch (FileNotFoundException e) {
182 static DataSchemaNode resolveDataSchemaNode(Module module, String searchedDataSchemaName) {
183 assertNotNull("Module is missing", module);
185 DataSchemaNode dataSchemaNode = null;
186 if (searchedDataSchemaName != null) {
187 for (DataSchemaNode dsn : module.getChildNodes()) {
188 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
189 dataSchemaNode = dsn;
192 } else if (module.getChildNodes().size() == 1) {
193 dataSchemaNode = module.getChildNodes().iterator().next();
195 return dataSchemaNode;
198 static String writeCompNodeWithSchemaContextToJson(CompositeNode compositeNode, String outputPath,
199 Set<Module> modules, DataSchemaNode dataSchemaNode) throws IOException, WebApplicationException {
202 assertNotNull(dataSchemaNode);
203 assertNotNull("Composite node can't be null", compositeNode);
204 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
206 ControllerContext contContext = ControllerContext.getInstance();
207 contContext.setSchemas(loadSchemaContext(modules));
209 StructuredDataToJsonProvider structuredDataToJsonProvider = StructuredDataToJsonProvider.INSTANCE;
210 structuredDataToJsonProvider.writeTo(new StructuredData(compositeNode, dataSchemaNode), null, null, null, null,
213 jsonResult = byteArrayOS.toString();
215 outputToFile(byteArrayOS, outputPath);
216 } catch (IOException e) {
217 System.out.println("Output file wasn't cloased sucessfuly.");
223 static CompositeNode loadCompositeNode(String xmlDataPath) {
224 InputStream xmlStream = ToJsonBasicDataTypesTest.class.getResourceAsStream(xmlDataPath);
225 CompositeNode compositeNode = null;
227 compositeNode = TestUtils.loadCompositeNode(xmlStream);
228 } catch (FileNotFoundException e) {
231 return compositeNode;
234 static void outputToFile(ByteArrayOutputStream outputStream, String outputDir) throws IOException {
235 FileOutputStream fileOS = null;
237 String path = ToJsonBasicDataTypesTest.class.getResource(outputDir).getPath();
238 File outFile = new File(path + "/data.json");
239 fileOS = new FileOutputStream(outFile);
241 fileOS.write(outputStream.toByteArray());
242 } catch (IOException e) {
246 } catch (FileNotFoundException e1) {
247 e1.printStackTrace();
251 static String readJsonFromFile(String path, boolean removeWhiteChars) {
252 FileReader fileReader = getFileReader(path);
254 StringBuilder strBuilder = new StringBuilder();
255 char[] buffer = new char[1000];
260 loadedCharNum = fileReader.read(buffer);
261 } catch (IOException e) {
264 if (loadedCharNum == -1) {
267 strBuilder.append(buffer, 0, loadedCharNum);
271 } catch (IOException e) {
272 System.out.println("The file wasn't closed");
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);
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;
292 fileReader = new FileReader(file);
293 } catch (FileNotFoundException e) {
296 assertNotNull("File reader can't be null.", fileReader);
300 private static String removeSpaces(String rawStr) {
301 StringBuilder strBuilder = new StringBuilder();
304 while (i < rawStr.length()) {
305 if (rawStr.substring(i, i + 1).equals("\"")) {
309 if (!rawStr.substring(i, i + 1).equals(" ") || (quoteCount % 2 == 1)) {
310 strBuilder.append(rawStr.charAt(i));
315 return strBuilder.toString();
318 static QName buildQName(String name, String uri, String date) {
320 URI u = new URI(uri);
323 dt = Date.valueOf(date);
325 return new QName(u, dt, name);
326 } catch (URISyntaxException e) {
331 static QName buildQName(String name) {
332 return buildQName(name, "", null);
335 static void supplementNamespace(DataSchemaNode dataSchemaNode, CompositeNode compositeNode) {
336 RestconfImpl restconf = RestconfImpl.getInstance();
338 InstanceIdWithSchemaNode instIdAndSchema = new InstanceIdWithSchemaNode(mock(InstanceIdentifier.class),
341 ControllerContext controllerContext = mock(ControllerContext.class);
342 BrokerFacade broker = mock(BrokerFacade.class);
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(
350 restconf.setControllerContext(controllerContext);
351 restconf.setBroker(broker);
353 // method is called only because it contains call of method which
354 // supplement namespaces to compositeNode
355 restconf.createConfigurationData("something", compositeNode);
358 static DataSchemaNode obtainSchemaFromYang(String yangFolder) throws FileNotFoundException {
359 return obtainSchemaFromYang(yangFolder, null);
362 static DataSchemaNode obtainSchemaFromYang(String yangFolder, String moduleName) throws FileNotFoundException {
363 Set<Module> modules = null;
364 modules = TestUtils.loadModules(ToJsonBasicDataTypesTest.class.getResource(yangFolder).getPath());
366 if (modules == null) {
369 if (modules.size() < 1) {
373 Module moduleRes = null;
374 if (modules.size() > 1) {
375 if (moduleName == null) {
378 for (Module module : modules) {
379 if (module.getName().equals(moduleName)) {
383 if (moduleRes == null) {
388 moduleRes = modules.iterator().next();
391 if (moduleRes.getChildNodes() == null) {
395 if (moduleRes.getChildNodes().size() != 1) {
398 DataSchemaNode dataSchemaNode = moduleRes.getChildNodes().iterator().next();
399 return dataSchemaNode;
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);