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.mockito.Matchers.any;
12 import static org.mockito.Mockito.mock;
13 import static org.mockito.Mockito.when;
14 import com.google.common.base.Preconditions;
15 import com.google.common.util.concurrent.CheckedFuture;
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.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
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.sal.restconf.impl.BrokerFacade;
46 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
47 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
53 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
54 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
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.YangContextParser;
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 YangContextParser parser = new YangParserImpl();
71 private static Set<Module> loadModules(final 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 final 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(final String yangPath) {
89 return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
90 } catch (final FileNotFoundException e) {
91 LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
97 public static SchemaContext loadSchemaContext(final Set<Module> modules) {
98 return parser.resolveSchemaContext(modules);
101 public static SchemaContext loadSchemaContext(final String resourceDirectory) throws FileNotFoundException {
102 return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
105 public static Module findModule(final Set<Module> modules, final String moduleName) {
106 for (final Module module : modules) {
107 if (module.getName().equals(moduleName)) {
114 public static Document loadDocumentFrom(final InputStream inputStream) {
116 final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
117 final 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(final Document doc) {
126 Preconditions.checkNotNull(doc);
128 final ByteArrayOutputStream out = new ByteArrayOutputStream();
129 final TransformerFactory tf = TransformerFactory.newInstance();
130 final 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 final byte[] charData = out.toByteArray();
139 return new String(charData, "UTF-8");
140 } catch (IOException | TransformerException e) {
141 final String msg = "Error during transformation of Document into String";
149 * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
150 * module set has only one element then this element is returned.
153 public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
154 assertNotNull("Modules can't be null.", modules);
155 if (searchedModuleName != null) {
156 for (final Module m : modules) {
157 if (m.getName().equals(searchedModuleName)) {
161 } else if (modules.size() == 1) {
162 return modules.iterator().next();
167 public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
168 assertNotNull("Module can't be null", module);
170 if (searchedDataSchemaName != null) {
171 for (final DataSchemaNode dsn : module.getChildNodes()) {
172 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
176 } else if (module.getChildNodes().size() == 1) {
177 return module.getChildNodes().iterator().next();
182 public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
184 final URI u = new URI(uri);
187 dt = Date.valueOf(date);
189 return QName.create(u, dt, name);
190 } catch (final URISyntaxException e) {
195 public static QName buildQName(final String name, final String uri, final String date) {
196 return buildQName(name, uri, date, null);
199 public static QName buildQName(final String name) {
200 return buildQName(name, "", null);
203 private static void prepareMocksForRestconf(final Set<Module> modules, final RestconfImpl restconf) {
204 final ControllerContext controllerContext = ControllerContext.getInstance();
205 final BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
207 controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
209 when(mockedBrokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(NormalizedNode.class)))
210 .thenReturn(mock(CheckedFuture.class));
212 restconf.setControllerContext(controllerContext);
213 restconf.setBroker(mockedBrokerFacade);
216 public static String loadTextFile(final String filePath) throws IOException {
217 final FileReader fileReader = new FileReader(filePath);
218 final BufferedReader bufReader = new BufferedReader(fileReader);
221 final StringBuilder result = new StringBuilder();
222 while ((line = bufReader.readLine()) != null) {
226 return result.toString();
229 private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
230 final StringBuilder pattern = new StringBuilder();
231 pattern.append(".*");
232 for (final String substring : substrings) {
233 pattern.append(substring);
234 pattern.append("\\s*");
236 pattern.append(".*");
237 return Pattern.compile(pattern.toString(), Pattern.DOTALL);
240 public static boolean containsStringData(final String jsonOutput, final String... substrings) {
241 final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
242 final Matcher matcher = pattern.matcher(jsonOutput);
243 return matcher.matches();
246 public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
247 final String revision) throws ParseException {
248 return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName));
251 public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
252 final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
253 final Map<QName, Object> predicate = new HashMap<>();
254 for (final String key : keys.keySet()) {
255 predicate.put(QName.create(namespace, revision, key), keys.get(key));
258 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(
260 QName.create(namespace, revision, localName), predicate);
263 public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
264 final String namespace, final String revision, final String... keysAndValues) throws ParseException {
265 final java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(revision);
266 if (keysAndValues.length % 2 != 0) {
267 new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)");
269 final Map<QName, Object> predicate = new HashMap<>();
272 while (i < keysAndValues.length) {
273 predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]);
276 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(namespace, revision, localName),
280 static NormalizedNode<?,?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
281 final String ietfInterfacesDate = "2013-07-04";
282 final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
283 final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode = ImmutableMapEntryNodeBuilder.create();
285 final Map<String, Object> predicates = new HashMap<>();
286 predicates.put("name", "eth0");
288 mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
291 .withChild(new ImmutableLeafNodeBuilder<String>()
292 .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
294 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
295 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
296 .withValue("ethernetCsmacd").build());
297 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
298 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
299 .withValue(Boolean.FALSE).build());
300 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
301 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
302 .withValue("some interface").build());
304 return mapEntryNode.build();