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 com.google.common.base.Preconditions;
12 import java.io.BufferedReader;
13 import java.io.ByteArrayOutputStream;
15 import java.io.FileNotFoundException;
16 import java.io.FileReader;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.OutputStreamWriter;
21 import java.net.URISyntaxException;
22 import java.nio.charset.StandardCharsets;
24 import java.text.ParseException;
25 import java.util.HashMap;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30 import javax.xml.parsers.DocumentBuilder;
31 import javax.xml.parsers.DocumentBuilderFactory;
32 import javax.xml.parsers.ParserConfigurationException;
33 import javax.xml.transform.OutputKeys;
34 import javax.xml.transform.Transformer;
35 import javax.xml.transform.TransformerException;
36 import javax.xml.transform.TransformerFactory;
37 import javax.xml.transform.dom.DOMSource;
38 import javax.xml.transform.stream.StreamResult;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
45 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.Module;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
50 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
51 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
52 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
53 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.w3c.dom.Document;
57 import org.xml.sax.SAXException;
59 public final class TestUtils {
61 private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
63 public static SchemaContext loadSchemaContext(final String... yangPath)
64 throws FileNotFoundException, ReactorException {
65 final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
67 for (int i = 0; i < yangPath.length; i++) {
68 final String path = yangPath[i];
69 final String pathToFile = TestUtils.class.getResource(path).getPath();
70 final File testDir = new File(pathToFile);
71 final String[] fileList = testDir.list();
72 if (fileList == null) {
73 throw new FileNotFoundException(pathToFile);
75 for (int j = 0; j < fileList.length; j++) {
76 final String fileName = fileList[j];
77 final File file = new File(testDir, fileName);
78 if (file.isDirectory() == false) {
79 reactor.addSource(new YangStatementSourceImpl(new NamedFileInputStream(file, file.getPath())));
83 return reactor.buildEffective();
86 public static Module findModule(final Set<Module> modules, final String moduleName) {
87 for (final Module module : modules) {
88 if (module.getName().equals(moduleName)) {
95 public static Document loadDocumentFrom(final InputStream inputStream) {
97 final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
98 final DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
99 return docBuilder.parse(inputStream);
100 } catch (SAXException | IOException | ParserConfigurationException e) {
101 LOG.error("Error during loading Document from XML", e);
106 public static String getDocumentInPrintableForm(final Document doc) {
107 Preconditions.checkNotNull(doc);
109 final ByteArrayOutputStream out = new ByteArrayOutputStream();
110 final TransformerFactory tf = TransformerFactory.newInstance();
111 final Transformer transformer = tf.newTransformer();
112 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
113 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
114 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
115 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
116 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
118 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out,
119 StandardCharsets.UTF_8)));
120 final byte[] charData = out.toByteArray();
121 return new String(charData, StandardCharsets.UTF_8);
122 } catch (TransformerException e) {
123 final String msg = "Error during transformation of Document into String";
131 * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
132 * module set has only one element then this element is returned.
135 public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
136 assertNotNull("Modules can't be null.", modules);
137 if (searchedModuleName != null) {
138 for (final Module m : modules) {
139 if (m.getName().equals(searchedModuleName)) {
143 } else if (modules.size() == 1) {
144 return modules.iterator().next();
149 public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
150 assertNotNull("Module can't be null", module);
152 if (searchedDataSchemaName != null) {
153 for (final DataSchemaNode dsn : module.getChildNodes()) {
154 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
158 } else if (module.getChildNodes().size() == 1) {
159 return module.getChildNodes().iterator().next();
164 public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
166 final URI u = new URI(uri);
169 dt = Date.valueOf(date);
171 return QName.create(u, dt, name);
172 } catch (final URISyntaxException e) {
177 public static QName buildQName(final String name, final String uri, final String date) {
178 return buildQName(name, uri, date, null);
181 public static QName buildQName(final String name) {
182 return buildQName(name, "", null);
185 public static String loadTextFile(final String filePath) throws IOException {
186 final FileReader fileReader = new FileReader(filePath);
187 final BufferedReader bufReader = new BufferedReader(fileReader);
190 final StringBuilder result = new StringBuilder();
191 while ((line = bufReader.readLine()) != null) {
195 return result.toString();
198 private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
199 final StringBuilder pattern = new StringBuilder();
200 pattern.append(".*");
201 for (final String substring : substrings) {
202 pattern.append(substring);
203 pattern.append("\\s*");
205 pattern.append(".*");
206 return Pattern.compile(pattern.toString(), Pattern.DOTALL);
209 public static boolean containsStringData(final String jsonOutput, final String... substrings) {
210 final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
211 final Matcher matcher = pattern.matcher(jsonOutput);
212 return matcher.matches();
215 public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
216 final String revision) throws ParseException {
217 return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName));
220 public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
221 final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
222 final Map<QName, Object> predicate = new HashMap<>();
223 for (final String key : keys.keySet()) {
224 predicate.put(QName.create(namespace, revision, key), keys.get(key));
227 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(
229 QName.create(namespace, revision, localName), predicate);
232 public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
233 final String namespace, final String revision, final String... keysAndValues) throws ParseException {
234 if ((keysAndValues.length % 2) != 0) {
235 new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)");
237 final Map<QName, Object> predicate = new HashMap<>();
240 while (i < keysAndValues.length) {
241 predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]);
244 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(namespace, revision, localName),
248 static NormalizedNode<?,?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
249 final String ietfInterfacesDate = "2013-07-04";
250 final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
251 final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode = ImmutableMapEntryNodeBuilder.create();
253 final Map<String, Object> predicates = new HashMap<>();
254 predicates.put("name", "eth0");
256 mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
259 .withChild(new ImmutableLeafNodeBuilder<String>()
260 .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
262 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
263 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
264 .withValue("ethernetCsmacd").build());
265 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
266 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
267 .withValue(Boolean.FALSE).build());
268 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
269 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
270 .withValue("some interface").build());
272 return mapEntryNode.build();