2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.sal.restconf.impl.test;
10 import static org.junit.Assert.assertNotNull;
11 import static org.junit.Assert.assertTrue;
12 import static org.mockito.Matchers.any;
13 import static org.mockito.Mockito.mock;
14 import static org.mockito.Mockito.when;
16 import java.io.BufferedReader;
17 import java.io.ByteArrayOutputStream;
19 import java.io.FileNotFoundException;
20 import java.io.FileReader;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStreamWriter;
25 import java.net.URISyntaxException;
27 import java.util.ArrayList;
28 import java.util.List;
31 import javax.ws.rs.WebApplicationException;
32 import javax.ws.rs.ext.MessageBodyReader;
33 import javax.ws.rs.ext.MessageBodyWriter;
34 import javax.xml.parsers.DocumentBuilder;
35 import javax.xml.parsers.DocumentBuilderFactory;
36 import javax.xml.parsers.ParserConfigurationException;
37 import javax.xml.transform.OutputKeys;
38 import javax.xml.transform.Transformer;
39 import javax.xml.transform.TransformerException;
40 import javax.xml.transform.TransformerFactory;
41 import javax.xml.transform.dom.DOMSource;
42 import javax.xml.transform.stream.StreamResult;
44 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
45 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
46 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
47 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
48 import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
49 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
50 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
53 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
54 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
58 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.w3c.dom.Document;
62 import org.xml.sax.SAXException;
64 import com.google.common.base.Preconditions;
66 public final class TestUtils {
68 private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
70 private final static YangModelParser parser = new YangParserImpl();
72 private static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
73 final File testDir = new File(resourceDirectory);
74 final String[] fileList = testDir.list();
75 final List<File> testFiles = new ArrayList<File>();
76 if (fileList == null) {
77 throw new FileNotFoundException(resourceDirectory);
79 for (int i = 0; i < fileList.length; i++) {
80 String fileName = fileList[i];
81 if (new File(testDir, fileName).isDirectory() == false) {
82 testFiles.add(new File(testDir, fileName));
85 return parser.parseYangModels(testFiles);
88 public static Set<Module> loadModulesFrom(String yangPath) {
90 return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
91 } catch (FileNotFoundException e) {
92 LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
98 public static SchemaContext loadSchemaContext(Set<Module> modules) {
99 return parser.resolveSchemaContext(modules);
102 public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
103 return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
106 public static Module findModule(Set<Module> modules, String moduleName) {
107 for (Module module : modules) {
108 if (module.getName().equals(moduleName)) {
115 public static Document loadDocumentFrom(InputStream inputStream) {
117 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
118 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
119 return docBuilder.parse(inputStream);
120 } catch (SAXException | IOException | ParserConfigurationException e) {
121 LOG.error("Error during loading Document from XML", e);
126 public static String getDocumentInPrintableForm(Document doc) {
127 Preconditions.checkNotNull(doc);
129 ByteArrayOutputStream out = new ByteArrayOutputStream();
130 TransformerFactory tf = TransformerFactory.newInstance();
131 Transformer transformer = tf.newTransformer();
132 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
133 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
134 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
135 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
136 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
138 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
139 byte[] charData = out.toByteArray();
140 return new String(charData, "UTF-8");
141 } catch (IOException | TransformerException e) {
142 String msg = "Error during transformation of Document into String";
151 * Fill missing data (namespaces) and build correct data type in
152 * {@code compositeNode} according to {@code dataSchemaNode}. The method
153 * {@link RestconfImpl#createConfigurationData createConfigurationData} is
154 * used because it contains calling of method {code normalizeNode}
156 public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
157 RestconfImpl restconf = RestconfImpl.getInstance();
158 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
160 prepareMocksForRestconf(modules, restconf);
161 restconf.updateConfigurationData(schemaNodePath, compositeNode);
165 * Searches module with name {@code searchedModuleName} in {@code modules}.
166 * If module name isn't specified and module set has only one element then
167 * this element is returned.
170 public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
171 assertNotNull("Modules can't be null.", modules);
172 if (searchedModuleName != null) {
173 for (Module m : modules) {
174 if (m.getName().equals(searchedModuleName)) {
178 } else if (modules.size() == 1) {
179 return modules.iterator().next();
184 public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
185 assertNotNull("Module can't be null", module);
187 if (searchedDataSchemaName != null) {
188 for (DataSchemaNode dsn : module.getChildNodes()) {
189 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
193 } else if (module.getChildNodes().size() == 1) {
194 return module.getChildNodes().iterator().next();
199 public static QName buildQName(String name, String uri, String date, String prefix) {
201 URI u = new URI(uri);
204 dt = Date.valueOf(date);
206 return new QName(u, dt, prefix, name);
207 } catch (URISyntaxException e) {
212 public static QName buildQName(String name, String uri, String date) {
213 return buildQName(name, uri, date, null);
216 public static QName buildQName(String name) {
217 return buildQName(name, "", null);
220 private static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
221 wrappedNode.setNamespace(new URI(""));
222 if (wrappedNode instanceof CompositeNodeWrapper) {
223 for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
224 addDummyNamespaceToAllNodes(childNodeWrapper);
229 private static void prepareMocksForRestconf(Set<Module> modules, RestconfImpl restconf) {
230 ControllerContext controllerContext = ControllerContext.getInstance();
231 BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
233 controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
235 when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
237 new DummyFuture.Builder().rpcResult(
238 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
241 restconf.setControllerContext(controllerContext);
242 restconf.setBroker(mockedBrokerFacade);
245 public static CompositeNode readInputToCnSn(String path, boolean dummyNamespaces,
246 MessageBodyReader<CompositeNode> reader) throws WebApplicationException {
248 InputStream inputStream = TestUtils.class.getResourceAsStream(path);
250 CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, inputStream);
251 assertTrue(compositeNode instanceof CompositeNodeWrapper);
252 if (dummyNamespaces) {
254 TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
255 return ((CompositeNodeWrapper) compositeNode).unwrap();
256 } catch (URISyntaxException e) {
257 LOG.error(e.getMessage());
258 assertTrue(e.getMessage(), false);
261 return compositeNode;
262 } catch (IOException e) {
263 LOG.error(e.getMessage());
264 assertTrue(e.getMessage(), false);
269 public static CompositeNode readInputToCnSn(String path, MessageBodyReader<CompositeNode> reader) {
270 return readInputToCnSn(path, false, reader);
273 public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set<Module> modules,
274 DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
275 WebApplicationException {
277 assertNotNull(dataSchemaNode);
278 assertNotNull("Composite node can't be null", compositeNode);
279 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
281 ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
283 messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null, null,
286 return byteArrayOS.toString();
289 public static String loadTextFile(String filePath) throws IOException {
290 FileReader fileReader = new FileReader(filePath);
291 BufferedReader bufReader = new BufferedReader(fileReader);
294 StringBuilder result = new StringBuilder();
295 while ((line = bufReader.readLine()) != null) {
299 return result.toString();