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;
12 import com.google.common.base.Preconditions;
13 import java.io.BufferedReader;
14 import java.io.ByteArrayOutputStream;
16 import java.io.FileNotFoundException;
17 import java.io.FileReader;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.OutputStreamWriter;
22 import java.net.URISyntaxException;
24 import java.text.ParseException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32 import javax.xml.parsers.DocumentBuilder;
33 import javax.xml.parsers.DocumentBuilderFactory;
34 import javax.xml.parsers.ParserConfigurationException;
35 import javax.xml.transform.OutputKeys;
36 import javax.xml.transform.Transformer;
37 import javax.xml.transform.TransformerException;
38 import javax.xml.transform.TransformerFactory;
39 import javax.xml.transform.dom.DOMSource;
40 import javax.xml.transform.stream.StreamResult;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
46 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
47 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.Module;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
52 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Document;
56 import org.xml.sax.SAXException;
58 public final class TestUtils {
60 private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
62 private final static YangContextParser PARSER = new YangParserImpl();
64 private static Set<Module> loadModules(final String resourceDirectory) throws FileNotFoundException {
65 final File testDir = new File(resourceDirectory);
66 final String[] fileList = testDir.list();
67 final List<File> testFiles = new ArrayList<File>();
68 if (fileList == null) {
69 throw new FileNotFoundException(resourceDirectory);
71 for (int i = 0; i < fileList.length; i++) {
72 final String fileName = fileList[i];
73 if (new File(testDir, fileName).isDirectory() == false) {
74 testFiles.add(new File(testDir, fileName));
77 return PARSER.parseYangModels(testFiles);
80 public static Set<Module> loadModulesFrom(final String yangPath) {
82 return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
83 } catch (final FileNotFoundException e) {
84 LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
90 public static SchemaContext loadSchemaContext(final Set<Module> modules) {
91 return PARSER.resolveSchemaContext(modules);
94 public static SchemaContext loadSchemaContext(final String resourceDirectory) throws FileNotFoundException {
95 return PARSER.resolveSchemaContext(loadModulesFrom(resourceDirectory));
98 public static Module findModule(final Set<Module> modules, final String moduleName) {
99 for (final Module module : modules) {
100 if (module.getName().equals(moduleName)) {
107 public static Document loadDocumentFrom(final InputStream inputStream) {
109 final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
110 final DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
111 return docBuilder.parse(inputStream);
112 } catch (SAXException | IOException | ParserConfigurationException e) {
113 LOG.error("Error during loading Document from XML", e);
118 public static String getDocumentInPrintableForm(final Document doc) {
119 Preconditions.checkNotNull(doc);
121 final ByteArrayOutputStream out = new ByteArrayOutputStream();
122 final TransformerFactory tf = TransformerFactory.newInstance();
123 final Transformer transformer = tf.newTransformer();
124 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
125 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
126 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
127 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
128 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
130 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
131 final byte[] charData = out.toByteArray();
132 return new String(charData, "UTF-8");
133 } catch (IOException | TransformerException e) {
134 final String msg = "Error during transformation of Document into String";
142 * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
143 * module set has only one element then this element is returned.
146 public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
147 assertNotNull("Modules can't be null.", modules);
148 if (searchedModuleName != null) {
149 for (final Module m : modules) {
150 if (m.getName().equals(searchedModuleName)) {
154 } else if (modules.size() == 1) {
155 return modules.iterator().next();
160 public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
161 assertNotNull("Module can't be null", module);
163 if (searchedDataSchemaName != null) {
164 for (final DataSchemaNode dsn : module.getChildNodes()) {
165 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
169 } else if (module.getChildNodes().size() == 1) {
170 return module.getChildNodes().iterator().next();
175 public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
177 final URI u = new URI(uri);
180 dt = Date.valueOf(date);
182 return QName.create(u, dt, name);
183 } catch (final URISyntaxException e) {
188 public static QName buildQName(final String name, final String uri, final String date) {
189 return buildQName(name, uri, date, null);
192 public static QName buildQName(final String name) {
193 return buildQName(name, "", null);
196 public static String loadTextFile(final String filePath) throws IOException {
197 final FileReader fileReader = new FileReader(filePath);
198 final BufferedReader bufReader = new BufferedReader(fileReader);
201 final StringBuilder result = new StringBuilder();
202 while ((line = bufReader.readLine()) != null) {
206 return result.toString();
209 private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
210 final StringBuilder pattern = new StringBuilder();
211 pattern.append(".*");
212 for (final String substring : substrings) {
213 pattern.append(substring);
214 pattern.append("\\s*");
216 pattern.append(".*");
217 return Pattern.compile(pattern.toString(), Pattern.DOTALL);
220 public static boolean containsStringData(final String jsonOutput, final String... substrings) {
221 final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
222 final Matcher matcher = pattern.matcher(jsonOutput);
223 return matcher.matches();
226 public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
227 final String revision) throws ParseException {
228 return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName));
231 public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
232 final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
233 final Map<QName, Object> predicate = new HashMap<>();
234 for (final String key : keys.keySet()) {
235 predicate.put(QName.create(namespace, revision, key), keys.get(key));
238 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(
240 QName.create(namespace, revision, localName), predicate);
243 public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
244 final String namespace, final String revision, final String... keysAndValues) throws ParseException {
245 if (keysAndValues.length % 2 != 0) {
246 new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)");
248 final Map<QName, Object> predicate = new HashMap<>();
251 while (i < keysAndValues.length) {
252 predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]);
255 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(namespace, revision, localName),
259 static NormalizedNode<?,?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
260 final String ietfInterfacesDate = "2013-07-04";
261 final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
262 final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode = ImmutableMapEntryNodeBuilder.create();
264 final Map<String, Object> predicates = new HashMap<>();
265 predicates.put("name", "eth0");
267 mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
270 .withChild(new ImmutableLeafNodeBuilder<String>()
271 .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
273 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
274 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
275 .withValue("ethernetCsmacd").build());
276 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
277 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
278 .withValue(Boolean.FALSE).build());
279 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
280 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
281 .withValue("some interface").build());
283 return mapEntryNode.build();