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
151 * {@code compositeNode} according to {@code dataSchemaNode}. The method
152 * {@link RestconfImpl#createConfigurationData createConfigurationData} is
153 * used because it contains calling of method {code normalizeNode}
155 public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
156 RestconfImpl restconf = RestconfImpl.getInstance();
157 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
159 prepareMocksForRestconf(modules, restconf);
160 restconf.updateConfigurationData(schemaNodePath, compositeNode);
164 * Searches module with name {@code searchedModuleName} in {@code modules}.
165 * If module name isn't specified and module set has only one element then
166 * this element is returned.
169 public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
170 assertNotNull("Modules can't be null.", modules);
171 if (searchedModuleName != null) {
172 for (Module m : modules) {
173 if (m.getName().equals(searchedModuleName)) {
177 } else if (modules.size() == 1) {
178 return modules.iterator().next();
183 public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
184 assertNotNull("Module can't be null", module);
186 if (searchedDataSchemaName != null) {
187 for (DataSchemaNode dsn : module.getChildNodes()) {
188 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
192 } else if (module.getChildNodes().size() == 1) {
193 return module.getChildNodes().iterator().next();
198 public static QName buildQName(String name, String uri, String date, String prefix) {
200 URI u = new URI(uri);
203 dt = Date.valueOf(date);
205 return new QName(u, dt, prefix, name);
206 } catch (URISyntaxException e) {
211 public static QName buildQName(String name, String uri, String date) {
212 return buildQName(name, uri, date, null);
215 public static QName buildQName(String name) {
216 return buildQName(name, "", null);
219 private static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
220 wrappedNode.setNamespace(new URI(""));
221 if (wrappedNode instanceof CompositeNodeWrapper) {
222 for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
223 addDummyNamespaceToAllNodes(childNodeWrapper);
228 private static void prepareMocksForRestconf(Set<Module> modules, RestconfImpl restconf) {
229 ControllerContext controllerContext = ControllerContext.getInstance();
230 BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
232 controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
234 when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
236 new DummyFuture.Builder().rpcResult(
237 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
240 restconf.setControllerContext(controllerContext);
241 restconf.setBroker(mockedBrokerFacade);
244 public static CompositeNode readInputToCnSn(String path, boolean dummyNamespaces,
245 MessageBodyReader<CompositeNode> reader) throws WebApplicationException {
247 InputStream inputStream = TestUtils.class.getResourceAsStream(path);
249 CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, inputStream);
250 assertTrue(compositeNode instanceof CompositeNodeWrapper);
251 if (dummyNamespaces) {
253 TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
254 return ((CompositeNodeWrapper) compositeNode).unwrap();
255 } catch (URISyntaxException e) {
256 LOG.error(e.getMessage());
257 assertTrue(e.getMessage(), false);
260 return compositeNode;
261 } catch (IOException e) {
262 LOG.error(e.getMessage());
263 assertTrue(e.getMessage(), false);
268 public static CompositeNode readInputToCnSn(String path, MessageBodyReader<CompositeNode> reader) {
269 return readInputToCnSn(path, false, reader);
272 public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set<Module> modules,
273 DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
274 WebApplicationException {
276 assertNotNull(dataSchemaNode);
277 assertNotNull("Composite node can't be null", compositeNode);
278 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
280 ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
282 messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null, null,
285 return byteArrayOS.toString();
288 public static String loadTextFile(String filePath) throws IOException {
289 FileReader fileReader = new FileReader(filePath);
290 BufferedReader bufReader = new BufferedReader(fileReader);
293 StringBuilder result = new StringBuilder();
294 while ((line = bufReader.readLine()) != null) {
298 return result.toString();
301 private static Pattern patternForStringsSeparatedByWhiteChars(String ... substrings ) {
302 StringBuilder pattern = new StringBuilder();
303 pattern.append(".*");
304 for (String substring : substrings) {
305 pattern.append(substring);
306 pattern.append("\\s*");
308 pattern.append(".*");
309 return Pattern.compile(pattern.toString(), Pattern.DOTALL);
312 public static boolean containsStringData(String jsonOutput,String ...substrings ) {
313 Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
314 Matcher matcher = pattern.matcher(jsonOutput);
315 return matcher.matches();