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 String jsonResult = null;
141 Set<Module> modules = null;
144 modules = TestUtils.loadModules(ToJsonBasicDataTypesTest.class.getResource(yangPath).getPath());
145 } catch (FileNotFoundException e) {
148 assertNotNull("modules can't be null.", modules);
150 Module module = null;
151 if (searchedModuleName != null) {
152 for (Module m : modules) {
153 if (m.getName().equals(searchedModuleName)) {
158 } else if (modules.size() == 1) {
159 module = modules.iterator().next();
161 assertNotNull("Module is missing", module);
163 assertNotNull("Composite node can't be null", compositeNode);
165 StructuredDataToJsonProvider structuredDataToJsonProvider = StructuredDataToJsonProvider.INSTANCE;
166 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
167 DataSchemaNode dataSchemaNode = null;
168 if (searchedDataSchemaName != null) {
169 for (DataSchemaNode dsn : module.getChildNodes()) {
170 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
171 dataSchemaNode = dsn;
174 } else if (module.getChildNodes().size() == 1) {
175 dataSchemaNode = module.getChildNodes().iterator().next();
177 assertNotNull(dataSchemaNode);
178 // SchemaContextUtil.
180 ControllerContext controllerContext = ControllerContext.getInstance();
181 controllerContext.setSchemas(loadSchemaContext(modules));
182 StructuredData structuredData = new StructuredData(compositeNode, dataSchemaNode);
184 structuredDataToJsonProvider.writeTo(structuredData, null, null, null, null, null, byteArrayOS);
185 } catch (WebApplicationException | IOException e) {
188 assertFalse("Returning JSON string can't be empty for node " + dataSchemaNode.getQName().getLocalName(),
189 byteArrayOS.toString().isEmpty());
191 jsonResult = byteArrayOS.toString();
193 outputToFile(byteArrayOS, outputPath);
194 } catch (IOException e) {
195 System.out.println("Output file wasn't cloased sucessfuly.");
201 static CompositeNode loadCompositeNode(String xmlDataPath) {
202 InputStream xmlStream = ToJsonBasicDataTypesTest.class.getResourceAsStream(xmlDataPath);
203 CompositeNode compositeNode = null;
205 compositeNode = TestUtils.loadCompositeNode(xmlStream);
206 } catch (FileNotFoundException e) {
209 return compositeNode;
212 static void outputToFile(ByteArrayOutputStream outputStream, String outputDir) throws IOException {
213 FileOutputStream fileOS = null;
215 String path = ToJsonBasicDataTypesTest.class.getResource(outputDir).getPath();
216 File outFile = new File(path + "/data.json");
217 fileOS = new FileOutputStream(outFile);
219 fileOS.write(outputStream.toByteArray());
220 } catch (IOException e) {
224 } catch (FileNotFoundException e1) {
225 e1.printStackTrace();
229 static String readJsonFromFile(String path, boolean removeWhiteChars) {
230 FileReader fileReader = getFileReader(path);
232 StringBuilder strBuilder = new StringBuilder();
233 char[] buffer = new char[1000];
238 loadedCharNum = fileReader.read(buffer);
239 } catch (IOException e) {
242 if (loadedCharNum == -1) {
245 strBuilder.append(buffer, 0, loadedCharNum);
249 } catch (IOException e) {
250 System.out.println("The file wasn't closed");
252 String rawStr = strBuilder.toString();
253 if (removeWhiteChars) {
254 rawStr = rawStr.replace("\n", "");
255 rawStr = rawStr.replace("\r", "");
256 rawStr = rawStr.replace("\t", "");
257 rawStr = removeSpaces(rawStr);
263 private static FileReader getFileReader(String path) {
264 String fullPath = ToJsonBasicDataTypesTest.class.getResource(path).getPath();
265 assertNotNull("Path to file can't be null.", fullPath);
266 File file = new File(fullPath);
267 assertNotNull("File can't be null", file);
268 FileReader fileReader = null;
270 fileReader = new FileReader(file);
271 } catch (FileNotFoundException e) {
274 assertNotNull("File reader can't be null.", fileReader);
278 private static String removeSpaces(String rawStr) {
279 StringBuilder strBuilder = new StringBuilder();
282 while (i < rawStr.length()) {
283 if (rawStr.substring(i, i + 1).equals("\"")) {
287 if (!rawStr.substring(i, i + 1).equals(" ") || (quoteCount % 2 == 1)) {
288 strBuilder.append(rawStr.charAt(i));
293 return strBuilder.toString();
296 static QName buildQName(String name, String uri, String date) {
298 URI u = new URI(uri);
301 dt = Date.valueOf(date);
303 return new QName(u, dt, name);
304 } catch (URISyntaxException e) {
309 static QName buildQName(String name) {
310 return buildQName(name, "", null);
313 static void supplementNamespace(DataSchemaNode dataSchemaNode, CompositeNode compositeNode) {
314 RestconfImpl restconf = RestconfImpl.getInstance();
316 InstanceIdWithSchemaNode instIdAndSchema = new InstanceIdWithSchemaNode(mock(InstanceIdentifier.class),
319 ControllerContext controllerContext = mock(ControllerContext.class);
320 BrokerFacade broker = mock(BrokerFacade.class);
322 RpcResult<TransactionStatus> rpcResult = DummyRpcResult.builder().result(TransactionStatus.COMMITED).build();
323 Future<RpcResult<TransactionStatus>> future = DummyFuture.builder().rpcResult(rpcResult).build();
324 when(controllerContext.toInstanceIdentifier(any(String.class))).thenReturn(instIdAndSchema);
325 when(broker.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class))).thenReturn(
328 restconf.setControllerContext(controllerContext);
329 restconf.setBroker(broker);
331 // method is called only because it contains call of method which
332 // supplement namespaces to compositeNode
333 restconf.createConfigurationData("something", compositeNode);
336 static DataSchemaNode obtainSchemaFromYang(String yangFolder) throws FileNotFoundException {
337 return obtainSchemaFromYang(yangFolder, null);
340 static DataSchemaNode obtainSchemaFromYang(String yangFolder, String moduleName) throws FileNotFoundException {
341 Set<Module> modules = null;
342 modules = TestUtils.loadModules(ToJsonBasicDataTypesTest.class.getResource(yangFolder).getPath());
344 if (modules == null) {
347 if (modules.size() < 1) {
351 Module moduleRes = null;
352 if (modules.size() > 1) {
353 if (moduleName == null) {
356 for (Module module : modules) {
357 if (module.getName().equals(moduleName)) {
361 if (moduleRes == null) {
366 moduleRes = modules.iterator().next();
369 if (moduleRes.getChildNodes() == null) {
373 if (moduleRes.getChildNodes().size() != 1) {
376 DataSchemaNode dataSchemaNode = moduleRes.getChildNodes().iterator().next();
377 return dataSchemaNode;
381 static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
382 wrappedNode.setNamespace(new URI(""));
383 if (wrappedNode instanceof CompositeNodeWrapper) {
384 for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
385 addDummyNamespaceToAllNodes(childNodeWrapper);