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.DocumentBuilder;
17 import javax.xml.parsers.DocumentBuilderFactory;
18 import javax.xml.parsers.ParserConfigurationException;
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;
24 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
25 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
26 import org.opendaylight.controller.sal.restconf.impl.*;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.common.RpcResult;
29 import org.opendaylight.yangtools.yang.data.api.*;
30 import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder;
31 import org.opendaylight.yangtools.yang.model.api.*;
32 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
33 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
35 import org.w3c.dom.Document;
36 import org.xml.sax.SAXException;
38 import com.google.common.base.Preconditions;
40 final class TestUtils {
42 private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
44 private final static YangModelParser parser = new YangParserImpl();
46 public static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
47 final File testDir = new File(resourceDirectory);
48 final String[] fileList = testDir.list();
49 final List<File> testFiles = new ArrayList<File>();
50 if (fileList == null) {
51 throw new FileNotFoundException(resourceDirectory);
53 for (int i = 0; i < fileList.length; i++) {
54 String fileName = fileList[i];
55 if (new File(testDir, fileName).isDirectory() == false) {
56 testFiles.add(new File(testDir, fileName));
59 return parser.parseYangModels(testFiles);
62 public static SchemaContext loadSchemaContext(Set<Module> modules) {
63 return parser.resolveSchemaContext(modules);
66 public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
67 return parser.resolveSchemaContext(loadModules(resourceDirectory));
70 public static Module findModule(Set<Module> modules, String moduleName) {
72 for (Module module : modules) {
73 if (module.getName().equals(moduleName)) {
81 public static CompositeNode loadCompositeNode(InputStream xmlInputStream) throws FileNotFoundException {
82 if (xmlInputStream == null) {
83 throw new IllegalArgumentException();
87 dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream);
88 } catch (XMLStreamException e) {
89 logger.error("Error during building data tree from XML", e);
92 if (dataTree == null) {
93 logger.error("data tree is null");
96 if (dataTree instanceof SimpleNode) {
97 logger.error("RPC XML was resolved as SimpleNode");
100 return (CompositeNode) dataTree;
103 public static Document loadDocumentFrom(InputStream inputStream) {
105 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
106 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
107 return docBuilder.parse(inputStream);
108 } catch (SAXException | IOException | ParserConfigurationException e) {
109 logger.error("Error during loading Document from XML", e);
114 public static String getDocumentInPrintableForm(Document doc) {
115 Preconditions.checkNotNull(doc);
117 ByteArrayOutputStream out = new ByteArrayOutputStream();
118 TransformerFactory tf = TransformerFactory.newInstance();
119 Transformer transformer = tf.newTransformer();
120 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
121 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
122 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
123 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
124 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
126 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
127 byte[] charData = out.toByteArray();
128 return new String(charData, "UTF-8");
129 } catch (IOException | TransformerException e) {
130 String msg = "Error during transformation of Document into String";
131 logger.error(msg, e);
137 static String convertCompositeNodeDataAndYangToJson(CompositeNode compositeNode, String yangPath, String outputPath) {
138 String jsonResult = null;
139 Set<Module> modules = null;
142 modules = TestUtils.loadModules(ToJsonBasicDataTypesTest.class.getResource(yangPath).getPath());
143 } catch (FileNotFoundException e) {
146 assertNotNull("modules can't be null.", modules);
148 assertNotNull("Composite node can't be null", compositeNode);
150 StructuredDataToJsonProvider structuredDataToJsonProvider = StructuredDataToJsonProvider.INSTANCE;
151 for (Module module : modules) {
152 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
153 for (DataSchemaNode dataSchemaNode : module.getChildNodes()) {
154 StructuredData structuredData = new StructuredData(compositeNode, dataSchemaNode);
156 structuredDataToJsonProvider.writeTo(structuredData, null, null, null, null, null, byteArrayOS);
157 } catch (WebApplicationException | IOException e) {
161 "Returning JSON string can't be empty for node " + dataSchemaNode.getQName().getLocalName(),
162 byteArrayOS.toString().isEmpty());
164 jsonResult = byteArrayOS.toString();
166 outputToFile(byteArrayOS, outputPath);
167 } catch (IOException e) {
168 System.out.println("Output file wasn't cloased sucessfuly.");
175 static CompositeNode loadCompositeNode(String xmlDataPath) {
176 InputStream xmlStream = ToJsonBasicDataTypesTest.class.getResourceAsStream(xmlDataPath);
177 CompositeNode compositeNode = null;
179 compositeNode = TestUtils.loadCompositeNode(xmlStream);
180 } catch (FileNotFoundException e) {
183 return compositeNode;
186 static void outputToFile(ByteArrayOutputStream outputStream, String outputDir) throws IOException {
187 FileOutputStream fileOS = null;
189 String path = ToJsonBasicDataTypesTest.class.getResource(outputDir).getPath();
190 File outFile = new File(path + "/data.json");
191 fileOS = new FileOutputStream(outFile);
193 fileOS.write(outputStream.toByteArray());
194 } catch (IOException e) {
198 } catch (FileNotFoundException e1) {
199 e1.printStackTrace();
203 static String readJsonFromFile(String path, boolean removeWhiteChars) {
204 FileReader fileReader = getFileReader(path);
206 StringBuilder strBuilder = new StringBuilder();
207 char[] buffer = new char[1000];
212 loadedCharNum = fileReader.read(buffer);
213 } catch (IOException e) {
216 if (loadedCharNum == -1) {
219 strBuilder.append(buffer, 0, loadedCharNum);
223 } catch (IOException e) {
224 System.out.println("The file wasn't closed");
226 String rawStr = strBuilder.toString();
227 if (removeWhiteChars) {
228 rawStr = rawStr.replace("\n", "");
229 rawStr = rawStr.replace("\r", "");
230 rawStr = rawStr.replace("\t", "");
231 rawStr = removeSpaces(rawStr);
237 private static FileReader getFileReader(String path) {
238 String fullPath = ToJsonBasicDataTypesTest.class.getResource(path).getPath();
239 assertNotNull("Path to file can't be null.", fullPath);
240 File file = new File(fullPath);
241 assertNotNull("File can't be null", file);
242 FileReader fileReader = null;
244 fileReader = new FileReader(file);
245 } catch (FileNotFoundException e) {
248 assertNotNull("File reader can't be null.", fileReader);
252 private static String removeSpaces(String rawStr) {
253 StringBuilder strBuilder = new StringBuilder();
256 while (i < rawStr.length()) {
257 if (rawStr.substring(i, i + 1).equals("\"")) {
261 if (!rawStr.substring(i, i + 1).equals(" ") || (quoteCount % 2 == 1)) {
262 strBuilder.append(rawStr.charAt(i));
267 return strBuilder.toString();
270 static QName buildQName(String name, String uri, String date) {
272 URI u = new URI(uri);
275 dt = Date.valueOf(date);
277 return new QName(u, dt, name);
278 } catch (URISyntaxException e) {
283 static QName buildQName(String name) {
284 return buildQName(name, "", null);
287 static void supplementNamespace(DataSchemaNode dataSchemaNode, CompositeNode compositeNode) {
288 RestconfImpl restconf = RestconfImpl.getInstance();
290 InstanceIdWithSchemaNode instIdAndSchema = new InstanceIdWithSchemaNode(mock(InstanceIdentifier.class),
293 ControllerContext controllerContext = mock(ControllerContext.class);
294 BrokerFacade broker = mock(BrokerFacade.class);
296 RpcResult<TransactionStatus> rpcResult = DummyRpcResult.builder().result(TransactionStatus.COMMITED).build();
297 Future<RpcResult<TransactionStatus>> future = DummyFuture.builder().rpcResult(rpcResult).build();
298 when(controllerContext.toInstanceIdentifier(any(String.class))).thenReturn(instIdAndSchema);
299 when(broker.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class))).thenReturn(future);
301 restconf.setControllerContext(controllerContext);
302 restconf.setBroker(broker);
304 // method is called only because it contains call of method which
305 // supplement namespaces to compositeNode
306 restconf.createConfigurationData("something", compositeNode);
309 static DataSchemaNode obtainSchemaFromYang(String yangFolder) throws FileNotFoundException {
310 return obtainSchemaFromYang(yangFolder, null);
313 static DataSchemaNode obtainSchemaFromYang(String yangFolder, String moduleName) throws FileNotFoundException {
314 Set<Module> modules = null;
315 modules = TestUtils.loadModules(ToJsonBasicDataTypesTest.class.getResource(yangFolder).getPath());
317 if (modules == null) {
320 if (modules.size() < 1) {
324 Module moduleRes = null;
325 if (modules.size() > 1) {
326 if (moduleName == null) {
329 for (Module module: modules) {
330 if (module.getName().equals(moduleName)) {
334 if (moduleRes == null) {
339 moduleRes = modules.iterator().next();
342 if (moduleRes.getChildNodes() == null) {
346 if (moduleRes.getChildNodes().size() != 1) {
349 DataSchemaNode dataSchemaNode = moduleRes.getChildNodes().iterator().next();
350 return dataSchemaNode;
354 static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
355 wrappedNode.setNamespace(new URI(""));
356 if (wrappedNode instanceof CompositeNodeWrapper) {
357 for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
358 addDummyNamespaceToAllNodes(childNodeWrapper);