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;
9 import java.io.ByteArrayOutputStream;
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.OutputStreamWriter;
16 import java.net.URISyntaxException;
18 import java.util.ArrayList;
19 import java.util.List;
22 import javax.ws.rs.WebApplicationException;
23 import javax.ws.rs.ext.MessageBodyReader;
24 import javax.ws.rs.ext.MessageBodyWriter;
25 import javax.xml.parsers.DocumentBuilder;
26 import javax.xml.parsers.DocumentBuilderFactory;
27 import javax.xml.parsers.ParserConfigurationException;
28 import javax.xml.transform.OutputKeys;
29 import javax.xml.transform.Transformer;
30 import javax.xml.transform.TransformerException;
31 import javax.xml.transform.TransformerFactory;
32 import javax.xml.transform.dom.DOMSource;
33 import javax.xml.transform.stream.StreamResult;
35 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
36 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
37 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
38 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
39 import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
40 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
41 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
44 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
49 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.w3c.dom.Document;
53 import org.xml.sax.SAXException;
55 import com.google.common.base.Preconditions;
57 public final class TestUtils {
59 private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
61 private final static YangModelParser parser = new YangParserImpl();
63 private static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
64 final File testDir = new File(resourceDirectory);
65 final String[] fileList = testDir.list();
66 final List<File> testFiles = new ArrayList<File>();
67 if (fileList == null) {
68 throw new FileNotFoundException(resourceDirectory);
70 for (int i = 0; i < fileList.length; i++) {
71 String fileName = fileList[i];
72 if (new File(testDir, fileName).isDirectory() == false) {
73 testFiles.add(new File(testDir, fileName));
76 return parser.parseYangModels(testFiles);
79 public static Set<Module> loadModulesFrom(String yangPath) {
81 return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
82 } catch (FileNotFoundException e) {
83 LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
89 public static SchemaContext loadSchemaContext(Set<Module> modules) {
90 return parser.resolveSchemaContext(modules);
93 public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
94 return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
97 public static Module findModule(Set<Module> modules, String moduleName) {
98 for (Module module : modules) {
99 if (module.getName().equals(moduleName)) {
106 public static Document loadDocumentFrom(InputStream inputStream) {
108 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
109 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
110 return docBuilder.parse(inputStream);
111 } catch (SAXException | IOException | ParserConfigurationException e) {
112 LOG.error("Error during loading Document from XML", e);
117 public static String getDocumentInPrintableForm(Document doc) {
118 Preconditions.checkNotNull(doc);
120 ByteArrayOutputStream out = new ByteArrayOutputStream();
121 TransformerFactory tf = TransformerFactory.newInstance();
122 Transformer transformer = tf.newTransformer();
123 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
124 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
125 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
126 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
127 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
129 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
130 byte[] charData = out.toByteArray();
131 return new String(charData, "UTF-8");
132 } catch (IOException | TransformerException e) {
133 String msg = "Error during transformation of Document into String";
142 * Fill missing data (namespaces) and build correct data type in
143 * {@code compositeNode} according to {@code dataSchemaNode}. The method
144 * {@link RestconfImpl#createConfigurationData createConfigurationData} is
145 * used because it contains calling of method {code normalizeNode}
147 public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
148 RestconfImpl restconf = RestconfImpl.getInstance();
149 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
151 prepareMocksForRestconf(modules, restconf);
152 restconf.updateConfigurationData(schemaNodePath, compositeNode);
156 * Searches module with name {@code searchedModuleName} in {@code modules}.
157 * If module name isn't specified and module set has only one element then
158 * this element is returned.
161 public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
162 assertNotNull("Modules can't be null.", modules);
163 if (searchedModuleName != null) {
164 for (Module m : modules) {
165 if (m.getName().equals(searchedModuleName)) {
169 } else if (modules.size() == 1) {
170 return modules.iterator().next();
175 public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
176 assertNotNull("Module can't be null", module);
178 if (searchedDataSchemaName != null) {
179 for (DataSchemaNode dsn : module.getChildNodes()) {
180 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
184 } else if (module.getChildNodes().size() == 1) {
185 return module.getChildNodes().iterator().next();
190 public static QName buildQName(String name, String uri, String date, String prefix) {
192 URI u = new URI(uri);
195 dt = Date.valueOf(date);
197 return new QName(u, dt, prefix, name);
198 } catch (URISyntaxException e) {
203 public static QName buildQName(String name, String uri, String date) {
204 return buildQName(name, uri, date, null);
207 public static QName buildQName(String name) {
208 return buildQName(name, "", null);
211 private static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
212 wrappedNode.setNamespace(new URI(""));
213 if (wrappedNode instanceof CompositeNodeWrapper) {
214 for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
215 addDummyNamespaceToAllNodes(childNodeWrapper);
220 private static void prepareMocksForRestconf(Set<Module> modules, RestconfImpl restconf) {
221 ControllerContext controllerContext = ControllerContext.getInstance();
222 BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
224 controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
226 when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
228 new DummyFuture.Builder().rpcResult(
229 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
232 restconf.setControllerContext(controllerContext);
233 restconf.setBroker(mockedBrokerFacade);
236 public static CompositeNode readInputToCnSn(String path, boolean dummyNamespaces,
237 MessageBodyReader<CompositeNode> reader) throws WebApplicationException {
239 InputStream inputStream = TestUtils.class.getResourceAsStream(path);
241 CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, inputStream);
242 assertTrue(compositeNode instanceof CompositeNodeWrapper);
243 if (dummyNamespaces) {
245 TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
246 return ((CompositeNodeWrapper) compositeNode).unwrap();
247 } catch (URISyntaxException e) {
248 LOG.error(e.getMessage());
249 assertTrue(e.getMessage(), false);
252 return compositeNode;
253 } catch (IOException e) {
254 LOG.error(e.getMessage());
255 assertTrue(e.getMessage(), false);
260 public static CompositeNode readInputToCnSn(String path, MessageBodyReader<CompositeNode> reader) {
261 return readInputToCnSn(path, false, reader);
264 public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set<Module> modules,
265 DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
266 WebApplicationException {
268 assertNotNull(dataSchemaNode);
269 assertNotNull("Composite node can't be null", compositeNode);
270 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
272 ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
274 messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode), null, null, null, null, null,
277 return byteArrayOS.toString();