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 com.google.common.base.Preconditions;
17 import java.io.BufferedReader;
18 import java.io.ByteArrayOutputStream;
20 import java.io.FileNotFoundException;
21 import java.io.FileReader;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStreamWriter;
26 import java.net.URISyntaxException;
28 import java.util.ArrayList;
29 import java.util.List;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import javax.ws.rs.WebApplicationException;
34 import javax.ws.rs.ext.MessageBodyReader;
35 import javax.ws.rs.ext.MessageBodyWriter;
36 import javax.xml.parsers.DocumentBuilder;
37 import javax.xml.parsers.DocumentBuilderFactory;
38 import javax.xml.parsers.ParserConfigurationException;
39 import javax.xml.transform.OutputKeys;
40 import javax.xml.transform.Transformer;
41 import javax.xml.transform.TransformerException;
42 import javax.xml.transform.TransformerFactory;
43 import javax.xml.transform.dom.DOMSource;
44 import javax.xml.transform.stream.StreamResult;
45 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
46 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
47 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
48 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
49 import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
50 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
51 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
54 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.Module;
57 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
58 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
59 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.w3c.dom.Document;
63 import org.xml.sax.SAXException;
65 public final class TestUtils {
67 private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
69 private final static YangModelParser parser = new YangParserImpl();
71 private static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
72 final File testDir = new File(resourceDirectory);
73 final String[] fileList = testDir.list();
74 final List<File> testFiles = new ArrayList<File>();
75 if (fileList == null) {
76 throw new FileNotFoundException(resourceDirectory);
78 for (int i = 0; i < fileList.length; i++) {
79 String fileName = fileList[i];
80 if (new File(testDir, fileName).isDirectory() == false) {
81 testFiles.add(new File(testDir, fileName));
84 return parser.parseYangModels(testFiles);
87 public static Set<Module> loadModulesFrom(String yangPath) {
89 return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
90 } catch (FileNotFoundException e) {
91 LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
97 public static SchemaContext loadSchemaContext(Set<Module> modules) {
98 return parser.resolveSchemaContext(modules);
101 public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
102 return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
105 public static Module findModule(Set<Module> modules, String moduleName) {
106 for (Module module : modules) {
107 if (module.getName().equals(moduleName)) {
114 public static Document loadDocumentFrom(InputStream inputStream) {
116 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
117 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
118 return docBuilder.parse(inputStream);
119 } catch (SAXException | IOException | ParserConfigurationException e) {
120 LOG.error("Error during loading Document from XML", e);
125 public static String getDocumentInPrintableForm(Document doc) {
126 Preconditions.checkNotNull(doc);
128 ByteArrayOutputStream out = new ByteArrayOutputStream();
129 TransformerFactory tf = TransformerFactory.newInstance();
130 Transformer transformer = tf.newTransformer();
131 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
132 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
133 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
134 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
135 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
137 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
138 byte[] charData = out.toByteArray();
139 return new String(charData, "UTF-8");
140 } catch (IOException | TransformerException e) {
141 String msg = "Error during transformation of Document into String";
150 * Fill missing data (namespaces) and build correct data type in {@code compositeNode} according to
151 * {@code dataSchemaNode}. The method {@link RestconfImpl#createConfigurationData createConfigurationData} is used
152 * because it contains calling of method {code normalizeNode}
154 public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
155 RestconfImpl restconf = RestconfImpl.getInstance();
156 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
158 prepareMocksForRestconf(modules, restconf);
159 restconf.updateConfigurationData(schemaNodePath, compositeNode);
163 * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
164 * module set has only one element then this element is returned.
167 public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
168 assertNotNull("Modules can't be null.", modules);
169 if (searchedModuleName != null) {
170 for (Module m : modules) {
171 if (m.getName().equals(searchedModuleName)) {
175 } else if (modules.size() == 1) {
176 return modules.iterator().next();
181 public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
182 assertNotNull("Module can't be null", module);
184 if (searchedDataSchemaName != null) {
185 for (DataSchemaNode dsn : module.getChildNodes()) {
186 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
190 } else if (module.getChildNodes().size() == 1) {
191 return module.getChildNodes().iterator().next();
196 public static QName buildQName(String name, String uri, String date, String prefix) {
198 URI u = new URI(uri);
201 dt = Date.valueOf(date);
203 return new QName(u, dt, prefix, name);
204 } catch (URISyntaxException e) {
209 public static QName buildQName(String name, String uri, String date) {
210 return buildQName(name, uri, date, null);
213 public static QName buildQName(String name) {
214 return buildQName(name, "", null);
217 private static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
218 wrappedNode.setNamespace(new URI(""));
219 if (wrappedNode instanceof CompositeNodeWrapper) {
220 for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
221 addDummyNamespaceToAllNodes(childNodeWrapper);
226 private static void prepareMocksForRestconf(Set<Module> modules, RestconfImpl restconf) {
227 ControllerContext controllerContext = ControllerContext.getInstance();
228 BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
230 controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
232 when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
234 new DummyFuture.Builder().rpcResult(
235 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
238 restconf.setControllerContext(controllerContext);
239 restconf.setBroker(mockedBrokerFacade);
242 public static CompositeNode readInputToCnSn(String path, boolean dummyNamespaces,
243 MessageBodyReader<CompositeNode> reader) throws WebApplicationException {
245 InputStream inputStream = TestUtils.class.getResourceAsStream(path);
247 CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, inputStream);
248 assertTrue(compositeNode instanceof CompositeNodeWrapper);
249 if (dummyNamespaces) {
251 TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
252 return ((CompositeNodeWrapper) compositeNode).unwrap();
253 } catch (URISyntaxException e) {
254 LOG.error(e.getMessage());
255 assertTrue(e.getMessage(), false);
258 return compositeNode;
259 } catch (IOException e) {
260 LOG.error(e.getMessage());
261 assertTrue(e.getMessage(), false);
266 public static CompositeNode readInputToCnSn(String path, MessageBodyReader<CompositeNode> reader) {
267 return readInputToCnSn(path, false, reader);
270 public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set<Module> modules,
271 DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
272 WebApplicationException {
274 assertNotNull(dataSchemaNode);
275 assertNotNull("Composite node can't be null", compositeNode);
276 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
278 ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
280 messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null,
283 return byteArrayOS.toString();
286 public static String loadTextFile(String filePath) throws IOException {
287 FileReader fileReader = new FileReader(filePath);
288 BufferedReader bufReader = new BufferedReader(fileReader);
291 StringBuilder result = new StringBuilder();
292 while ((line = bufReader.readLine()) != null) {
296 return result.toString();
299 private static Pattern patternForStringsSeparatedByWhiteChars(String... substrings) {
300 StringBuilder pattern = new StringBuilder();
301 pattern.append(".*");
302 for (String substring : substrings) {
303 pattern.append(substring);
304 pattern.append("\\s*");
306 pattern.append(".*");
307 return Pattern.compile(pattern.toString(), Pattern.DOTALL);
310 public static boolean containsStringData(String jsonOutput, String... substrings) {
311 Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
312 Matcher matcher = pattern.matcher(jsonOutput);
313 return matcher.matches();