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.BufferedReader;
10 import java.io.ByteArrayOutputStream;
12 import java.io.FileNotFoundException;
13 import java.io.FileReader;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.OutputStreamWriter;
18 import java.net.URISyntaxException;
20 import java.util.ArrayList;
21 import java.util.List;
24 import javax.ws.rs.WebApplicationException;
25 import javax.ws.rs.ext.MessageBodyReader;
26 import javax.ws.rs.ext.MessageBodyWriter;
27 import javax.xml.parsers.DocumentBuilder;
28 import javax.xml.parsers.DocumentBuilderFactory;
29 import javax.xml.parsers.ParserConfigurationException;
30 import javax.xml.transform.OutputKeys;
31 import javax.xml.transform.Transformer;
32 import javax.xml.transform.TransformerException;
33 import javax.xml.transform.TransformerFactory;
34 import javax.xml.transform.dom.DOMSource;
35 import javax.xml.transform.stream.StreamResult;
37 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
38 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
39 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
40 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
41 import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
42 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
43 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
46 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.Module;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
51 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Document;
55 import org.xml.sax.SAXException;
57 import com.google.common.base.Preconditions;
59 public final class TestUtils {
61 private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
63 private final static YangModelParser parser = new YangParserImpl();
65 private static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
66 final File testDir = new File(resourceDirectory);
67 final String[] fileList = testDir.list();
68 final List<File> testFiles = new ArrayList<File>();
69 if (fileList == null) {
70 throw new FileNotFoundException(resourceDirectory);
72 for (int i = 0; i < fileList.length; i++) {
73 String fileName = fileList[i];
74 if (new File(testDir, fileName).isDirectory() == false) {
75 testFiles.add(new File(testDir, fileName));
78 return parser.parseYangModels(testFiles);
81 public static Set<Module> loadModulesFrom(String yangPath) {
83 return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
84 } catch (FileNotFoundException e) {
85 LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
91 public static SchemaContext loadSchemaContext(Set<Module> modules) {
92 return parser.resolveSchemaContext(modules);
95 public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
96 return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
99 public static Module findModule(Set<Module> modules, String moduleName) {
100 for (Module module : modules) {
101 if (module.getName().equals(moduleName)) {
108 public static Document loadDocumentFrom(InputStream inputStream) {
110 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
111 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
112 return docBuilder.parse(inputStream);
113 } catch (SAXException | IOException | ParserConfigurationException e) {
114 LOG.error("Error during loading Document from XML", e);
119 public static String getDocumentInPrintableForm(Document doc) {
120 Preconditions.checkNotNull(doc);
122 ByteArrayOutputStream out = new ByteArrayOutputStream();
123 TransformerFactory tf = TransformerFactory.newInstance();
124 Transformer transformer = tf.newTransformer();
125 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
126 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
127 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
128 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
129 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
131 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
132 byte[] charData = out.toByteArray();
133 return new String(charData, "UTF-8");
134 } catch (IOException | TransformerException e) {
135 String msg = "Error during transformation of Document into String";
144 * Fill missing data (namespaces) and build correct data type in
145 * {@code compositeNode} according to {@code dataSchemaNode}. The method
146 * {@link RestconfImpl#createConfigurationData createConfigurationData} is
147 * used because it contains calling of method {code normalizeNode}
149 public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
150 RestconfImpl restconf = RestconfImpl.getInstance();
151 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
153 prepareMocksForRestconf(modules, restconf);
154 restconf.updateConfigurationData(schemaNodePath, compositeNode);
158 * Searches module with name {@code searchedModuleName} in {@code modules}.
159 * If module name isn't specified and module set has only one element then
160 * this element is returned.
163 public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
164 assertNotNull("Modules can't be null.", modules);
165 if (searchedModuleName != null) {
166 for (Module m : modules) {
167 if (m.getName().equals(searchedModuleName)) {
171 } else if (modules.size() == 1) {
172 return modules.iterator().next();
177 public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
178 assertNotNull("Module can't be null", module);
180 if (searchedDataSchemaName != null) {
181 for (DataSchemaNode dsn : module.getChildNodes()) {
182 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
186 } else if (module.getChildNodes().size() == 1) {
187 return module.getChildNodes().iterator().next();
192 public static QName buildQName(String name, String uri, String date, String prefix) {
194 URI u = new URI(uri);
197 dt = Date.valueOf(date);
199 return new QName(u, dt, prefix, name);
200 } catch (URISyntaxException e) {
205 public static QName buildQName(String name, String uri, String date) {
206 return buildQName(name, uri, date, null);
209 public static QName buildQName(String name) {
210 return buildQName(name, "", null);
213 private static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
214 wrappedNode.setNamespace(new URI(""));
215 if (wrappedNode instanceof CompositeNodeWrapper) {
216 for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
217 addDummyNamespaceToAllNodes(childNodeWrapper);
222 private static void prepareMocksForRestconf(Set<Module> modules, RestconfImpl restconf) {
223 ControllerContext controllerContext = ControllerContext.getInstance();
224 BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
226 controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
228 when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
230 new DummyFuture.Builder().rpcResult(
231 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
234 restconf.setControllerContext(controllerContext);
235 restconf.setBroker(mockedBrokerFacade);
238 public static CompositeNode readInputToCnSn(String path, boolean dummyNamespaces,
239 MessageBodyReader<CompositeNode> reader) throws WebApplicationException {
241 InputStream inputStream = TestUtils.class.getResourceAsStream(path);
243 CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, inputStream);
244 assertTrue(compositeNode instanceof CompositeNodeWrapper);
245 if (dummyNamespaces) {
247 TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
248 return ((CompositeNodeWrapper) compositeNode).unwrap();
249 } catch (URISyntaxException e) {
250 LOG.error(e.getMessage());
251 assertTrue(e.getMessage(), false);
254 return compositeNode;
255 } catch (IOException e) {
256 LOG.error(e.getMessage());
257 assertTrue(e.getMessage(), false);
262 public static CompositeNode readInputToCnSn(String path, MessageBodyReader<CompositeNode> reader) {
263 return readInputToCnSn(path, false, reader);
266 public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set<Module> modules,
267 DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
268 WebApplicationException {
270 assertNotNull(dataSchemaNode);
271 assertNotNull("Composite node can't be null", compositeNode);
272 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
274 ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
276 messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode), null, null, null, null, null,
279 return byteArrayOS.toString();
282 public static String loadTextFile(String filePath) throws IOException {
283 FileReader fileReader = new FileReader(filePath);
284 BufferedReader bufReader = new BufferedReader(fileReader);
287 StringBuilder result = new StringBuilder();
288 while ((line = bufReader.readLine()) != null) {
292 return result.toString();