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;
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;
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;
29 import org.w3c.dom.Document;
31 final class TestUtils {
33 private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
35 private final static YangModelParser parser = new YangParserImpl();
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);
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));
50 return parser.parseYangModels(testFiles);
53 public static SchemaContext loadSchemaContext(Set<Module> modules) {
54 return parser.resolveSchemaContext(modules);
57 public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
58 return parser.resolveSchemaContext(loadModules(resourceDirectory));
61 public static Module findModule(Set<Module> modules, String moduleName) {
63 for (Module module : modules) {
64 if (module.getName().equals(moduleName)) {
72 public static CompositeNode loadCompositeNode(InputStream xmlInputStream) throws FileNotFoundException {
73 if (xmlInputStream == null) {
74 throw new IllegalArgumentException();
78 dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream);
79 } catch (XMLStreamException e) {
80 logger.error("Error during building data tree from XML", e);
83 if (dataTree == null) {
84 logger.error("data tree is null");
87 if (dataTree instanceof SimpleNode) {
88 logger.error("RPC XML was resolved as SimpleNode");
91 return (CompositeNode) dataTree;
94 public static String getDocumentInPrintableForm(Document 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 static String convertCompositeNodeDataAndYangToJson(CompositeNode compositeNode, String yangPath, String outputPath) {
117 String jsonResult = null;
118 Set<Module> modules = null;
121 modules = TestUtils.loadModules(ToJsonBasicDataTypesTest.class.getResource(yangPath).getPath());
122 } catch (FileNotFoundException e) {
125 assertNotNull("modules can't be null.", modules);
127 assertNotNull("Composite node can't be null", compositeNode);
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);
135 structuredDataToJsonProvider.writeTo(structuredData, null, null, null, null, null, byteArrayOS);
136 } catch (WebApplicationException | IOException e) {
140 "Returning JSON string can't be empty for node " + dataSchemaNode.getQName().getLocalName(),
141 byteArrayOS.toString().isEmpty());
143 jsonResult = byteArrayOS.toString();
145 outputToFile(byteArrayOS, outputPath);
146 } catch (IOException e) {
147 System.out.println("Output file wasn't cloased sucessfuly.");
154 static CompositeNode loadCompositeNode(String xmlDataPath) {
155 InputStream xmlStream = ToJsonBasicDataTypesTest.class.getResourceAsStream(xmlDataPath);
156 CompositeNode compositeNode = null;
158 compositeNode = TestUtils.loadCompositeNode(xmlStream);
159 } catch (FileNotFoundException e) {
162 return compositeNode;
165 static void outputToFile(ByteArrayOutputStream outputStream, String outputDir) throws IOException {
166 FileOutputStream fileOS = null;
168 String path = ToJsonBasicDataTypesTest.class.getResource(outputDir).getPath();
169 File outFile = new File(path + "/data.json");
170 fileOS = new FileOutputStream(outFile);
172 fileOS.write(outputStream.toByteArray());
173 } catch (IOException e) {
177 } catch (FileNotFoundException e1) {
178 e1.printStackTrace();
182 static String readJsonFromFile(String path, boolean removeWhiteChars) {
183 FileReader fileReader = getFileReader(path);
185 StringBuilder strBuilder = new StringBuilder();
186 char[] buffer = new char[1000];
191 loadedCharNum = fileReader.read(buffer);
192 } catch (IOException e) {
195 if (loadedCharNum == -1) {
198 strBuilder.append(buffer, 0, loadedCharNum);
202 } catch (IOException e) {
203 System.out.println("The file wasn't closed");
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);
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;
223 fileReader = new FileReader(file);
224 } catch (FileNotFoundException e) {
227 assertNotNull("File reader can't be null.", fileReader);
231 private static String removeSpaces(String rawStr) {
232 StringBuilder strBuilder = new StringBuilder();
235 while (i < rawStr.length()) {
236 if (rawStr.substring(i, i + 1).equals("\"")) {
240 if (!rawStr.substring(i, i + 1).equals(" ") || (quoteCount % 2 == 1)) {
241 strBuilder.append(rawStr.charAt(i));
246 return strBuilder.toString();
249 static QName buildQName(String name, String uri, String date) {
251 URI u = new URI(uri);
254 dt = Date.valueOf(date);
256 return new QName(u, dt, name);
257 } catch (URISyntaxException e) {
262 static QName buildQName(String name) {
263 return buildQName(name, "", null);
266 static void supplementNamespace(DataSchemaNode dataSchemaNode, CompositeNode compositeNode) {
267 RestconfImpl restconf = RestconfImpl.getInstance();
269 InstanceIdWithSchemaNode instIdAndSchema = new InstanceIdWithSchemaNode(mock(InstanceIdentifier.class),
272 ControllerContext controllerContext = mock(ControllerContext.class);
273 BrokerFacade broker = mock(BrokerFacade.class);
275 when(controllerContext.toInstanceIdentifier(any(String.class))).thenReturn(instIdAndSchema);
276 when(broker.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class))).thenReturn(
279 restconf.setControllerContext(controllerContext);
280 restconf.setBroker(broker);
282 // method is called only because it contains call of method which
283 // supplement namespaces to compositeNode
284 restconf.createConfigurationData("something", compositeNode);
287 static DataSchemaNode obtainSchemaFromYang(String yangFolder) throws FileNotFoundException {
288 return obtainSchemaFromYang(yangFolder, null);
291 static DataSchemaNode obtainSchemaFromYang(String yangFolder, String moduleName) throws FileNotFoundException {
292 Set<Module> modules = null;
293 modules = TestUtils.loadModules(ToJsonBasicDataTypesTest.class.getResource(yangFolder).getPath());
295 if (modules == null) {
298 if (modules.size() < 1) {
302 Module moduleRes = null;
303 if (modules.size() > 1) {
304 if (moduleName == null) {
307 for (Module module: modules) {
308 if (module.getName().equals(moduleName)) {
312 if (moduleRes == null) {
317 moduleRes = modules.iterator().next();
320 if (moduleRes.getChildNodes() == null) {
324 if (moduleRes.getChildNodes().size() != 1) {
327 DataSchemaNode dataSchemaNode = moduleRes.getChildNodes().iterator().next();
328 return dataSchemaNode;
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);