1 package org.opendaylight.controller.sal.restconf.impl.test;
3 import static org.junit.Assert.assertNotNull;
4 import static org.junit.Assert.assertTrue;
5 import static org.mockito.Matchers.any;
6 import static org.mockito.Mockito.mock;
7 import static org.mockito.Mockito.when;
11 import java.net.URISyntaxException;
15 import javax.ws.rs.WebApplicationException;
16 import javax.ws.rs.ext.MessageBodyReader;
17 import javax.ws.rs.ext.MessageBodyWriter;
18 import javax.xml.parsers.*;
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.UnsupportedFormatException;
26 import org.opendaylight.controller.sal.rest.impl.XmlReader;
27 import org.opendaylight.controller.sal.restconf.impl.*;
28 import org.opendaylight.controller.sal.restconf.impl.json.to.cnsn.test.JsonToCnSnTest;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
32 import org.opendaylight.yangtools.yang.model.api.*;
33 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
34 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.w3c.dom.Document;
38 import org.xml.sax.SAXException;
40 import com.google.common.base.Preconditions;
42 public final class TestUtils {
44 private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
46 private final static YangModelParser parser = new YangParserImpl();
48 public static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
49 final File testDir = new File(resourceDirectory);
50 final String[] fileList = testDir.list();
51 final List<File> testFiles = new ArrayList<File>();
52 if (fileList == null) {
53 throw new FileNotFoundException(resourceDirectory);
55 for (int i = 0; i < fileList.length; i++) {
56 String fileName = fileList[i];
57 if (new File(testDir, fileName).isDirectory() == false) {
58 testFiles.add(new File(testDir, fileName));
61 return parser.parseYangModels(testFiles);
64 public static SchemaContext loadSchemaContext(Set<Module> modules) {
65 return parser.resolveSchemaContext(modules);
68 public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
69 return parser.resolveSchemaContext(loadModules(resourceDirectory));
72 public static Module findModule(Set<Module> modules, String moduleName) {
74 for (Module module : modules) {
75 if (module.getName().equals(moduleName)) {
83 public static Document loadDocumentFrom(InputStream inputStream) {
85 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
86 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
87 return docBuilder.parse(inputStream);
88 } catch (SAXException | IOException | ParserConfigurationException e) {
89 LOG.error("Error during loading Document from XML", e);
94 public static String getDocumentInPrintableForm(Document doc) {
95 Preconditions.checkNotNull(doc);
97 ByteArrayOutputStream out = new ByteArrayOutputStream();
98 TransformerFactory tf = TransformerFactory.newInstance();
99 Transformer transformer = tf.newTransformer();
100 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
101 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
102 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
103 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
104 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
106 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
107 byte[] charData = out.toByteArray();
108 return new String(charData, "UTF-8");
109 } catch (IOException | TransformerException e) {
110 String msg = "Error during transformation of Document into String";
119 * Fill missing data (namespaces) and build correct data type in
120 * {@code compositeNode} according to {@code dataSchemaNode}. The method
121 * {@link RestconfImpl#createConfigurationData createConfigurationData} is
122 * used because it contains calling of method {code normalizeNode}
124 public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
125 RestconfImpl restconf = RestconfImpl.getInstance();
126 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
128 prepareMockForRestconfBeforeNormalization(modules, restconf);
129 restconf.createConfigurationData(schemaNodePath, compositeNode);
132 public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
133 assertNotNull("modules can't be null.", modules);
134 if (searchedModuleName != null) {
135 for (Module m : modules) {
136 if (m.getName().equals(searchedModuleName)) {
140 } else if (modules.size() == 1) {
141 return modules.iterator().next();
146 public static Set<Module> resolveModulesFrom(String yangPath) {
148 return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
149 } catch (FileNotFoundException e) {
150 LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
156 public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
157 assertNotNull("Module can't be null", module);
159 if (searchedDataSchemaName != null) {
160 for (DataSchemaNode dsn : module.getChildNodes()) {
161 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
165 } else if (module.getChildNodes().size() == 1) {
166 return module.getChildNodes().iterator().next();
171 public static CompositeNode loadCompositeNode(String xmlDataPath) {
172 return loadCompositeNode(xmlDataPath, false);
175 public static CompositeNode loadCompositeNode(String xmlDataPath, boolean addDumyNamespace) {
176 InputStream xmlStream = TestUtils.class.getResourceAsStream(xmlDataPath);
177 CompositeNode compositeNode = null;
179 XmlReader xmlReader = new XmlReader();
180 compositeNode = xmlReader.read(xmlStream);
181 } catch (UnsupportedFormatException | XMLStreamException e) {
182 LOG.error(e.getMessage());
184 if (addDumyNamespace) {
186 addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
187 } catch (URISyntaxException e) {
188 LOG.error(e.getMessage());
191 return compositeNode;
194 public static QName buildQName(String name, String uri, String date, String prefix) {
196 URI u = new URI(uri);
199 dt = Date.valueOf(date);
201 return new QName(u, dt, prefix, name);
202 } catch (URISyntaxException e) {
207 public static QName buildQName(String name, String uri, String date) {
208 return buildQName(name, uri, date, null);
211 public static QName buildQName(String name) {
212 return buildQName(name, "", null);
215 public static DataSchemaNode obtainSchemaFromYang(String yangFolder) throws FileNotFoundException {
216 return obtainSchemaFromYang(yangFolder, null);
219 public static DataSchemaNode obtainSchemaFromYang(String yangFolder, String moduleName)
220 throws FileNotFoundException {
221 Set<Module> modules = null;
222 modules = TestUtils.loadModules(TestUtils.class.getResource(yangFolder).getPath());
224 if (modules == null) {
227 if (modules.size() < 1) {
231 Module moduleRes = null;
232 if (modules.size() > 1) {
233 if (moduleName == null) {
236 for (Module module : modules) {
237 if (module.getName().equals(moduleName)) {
241 if (moduleRes == null) {
246 moduleRes = modules.iterator().next();
249 if (moduleRes.getChildNodes() == null) {
253 if (moduleRes.getChildNodes().size() != 1) {
256 DataSchemaNode dataSchemaNode = moduleRes.getChildNodes().iterator().next();
257 return dataSchemaNode;
260 public static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
261 wrappedNode.setNamespace(new URI(""));
262 if (wrappedNode instanceof CompositeNodeWrapper) {
263 for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
264 addDummyNamespaceToAllNodes(childNodeWrapper);
269 private static void prepareMockForRestconfBeforeNormalization(Set<Module> modules, RestconfImpl restconf) {
271 ControllerContext controllerContext = ControllerContext.getInstance();
272 BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
274 controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
276 when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
278 new DummyFuture.Builder().rpcResult(
279 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
282 restconf.setControllerContext(ControllerContext.getInstance());
283 restconf.setBroker(mockedBrokerFacade);
286 public static CompositeNode readInputToCnSn(String jsonPath, boolean dummyNamespaces,
287 MessageBodyReader<CompositeNode> reader) throws WebApplicationException {
289 InputStream jsonStream = JsonToCnSnTest.class.getResourceAsStream(jsonPath);
291 CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, jsonStream);
292 assertTrue(compositeNode instanceof CompositeNodeWrapper);
293 if (dummyNamespaces) {
295 TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
296 return ((CompositeNodeWrapper) compositeNode).unwrap();
297 } catch (URISyntaxException e) {
298 LOG.error(e.getMessage());
299 assertTrue(e.getMessage(), false);
302 return compositeNode;
303 } catch (IOException e) {
304 LOG.error(e.getMessage());
305 assertTrue(e.getMessage(), false);
310 public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set<Module> modules,
311 DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
312 WebApplicationException {
314 assertNotNull(dataSchemaNode);
315 assertNotNull("Composite node can't be null", compositeNode);
316 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
318 ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
320 messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode), null, null, null, null, null,
323 return byteArrayOS.toString();