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;
23 import java.text.ParseException;
24 import java.util.HashMap;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import javax.xml.parsers.DocumentBuilder;
30 import javax.xml.parsers.DocumentBuilderFactory;
31 import javax.xml.parsers.ParserConfigurationException;
32 import javax.xml.transform.OutputKeys;
33 import javax.xml.transform.Transformer;
34 import javax.xml.transform.TransformerException;
35 import javax.xml.transform.TransformerFactory;
36 import javax.xml.transform.dom.DOMSource;
37 import javax.xml.transform.stream.StreamResult;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
43 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
49 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
50 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
51 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
52 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
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 public static SchemaContext loadSchemaContext(final String... yangPath)
63 throws FileNotFoundException, ReactorException {
64 final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
66 for (int i = 0; i < yangPath.length; i++) {
67 final String path = yangPath[i];
68 final String pathToFile = TestUtils.class.getResource(path).getPath();
69 final File testDir = new File(pathToFile);
70 final String[] fileList = testDir.list();
71 if (fileList == null) {
72 throw new FileNotFoundException(pathToFile);
74 for (int j = 0; j < fileList.length; j++) {
75 final String fileName = fileList[j];
76 final File file = new File(testDir, fileName);
77 if (file.isDirectory() == false) {
78 reactor.addSource(new YangStatementSourceImpl(new NamedFileInputStream(file, file.getPath())));
82 return reactor.buildEffective();
85 public static Module findModule(final Set<Module> modules, final String moduleName) {
86 for (final Module module : modules) {
87 if (module.getName().equals(moduleName)) {
94 public static Document loadDocumentFrom(final InputStream inputStream) {
96 final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
97 final DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
98 return docBuilder.parse(inputStream);
99 } catch (SAXException | IOException | ParserConfigurationException e) {
100 LOG.error("Error during loading Document from XML", e);
105 public static String getDocumentInPrintableForm(final Document doc) {
106 Preconditions.checkNotNull(doc);
108 final ByteArrayOutputStream out = new ByteArrayOutputStream();
109 final TransformerFactory tf = TransformerFactory.newInstance();
110 final Transformer transformer = tf.newTransformer();
111 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
112 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
113 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
114 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
115 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
117 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
118 final byte[] charData = out.toByteArray();
119 return new String(charData, "UTF-8");
120 } catch (IOException | TransformerException e) {
121 final String msg = "Error during transformation of Document into String";
129 * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
130 * module set has only one element then this element is returned.
133 public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
134 assertNotNull("Modules can't be null.", modules);
135 if (searchedModuleName != null) {
136 for (final Module m : modules) {
137 if (m.getName().equals(searchedModuleName)) {
141 } else if (modules.size() == 1) {
142 return modules.iterator().next();
147 public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
148 assertNotNull("Module can't be null", module);
150 if (searchedDataSchemaName != null) {
151 for (final DataSchemaNode dsn : module.getChildNodes()) {
152 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
156 } else if (module.getChildNodes().size() == 1) {
157 return module.getChildNodes().iterator().next();
162 public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
164 final URI u = new URI(uri);
167 dt = Date.valueOf(date);
169 return QName.create(u, dt, name);
170 } catch (final URISyntaxException e) {
175 public static QName buildQName(final String name, final String uri, final String date) {
176 return buildQName(name, uri, date, null);
179 public static QName buildQName(final String name) {
180 return buildQName(name, "", null);
183 public static String loadTextFile(final String filePath) throws IOException {
184 final FileReader fileReader = new FileReader(filePath);
185 final BufferedReader bufReader = new BufferedReader(fileReader);
188 final StringBuilder result = new StringBuilder();
189 while ((line = bufReader.readLine()) != null) {
193 return result.toString();
196 private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
197 final StringBuilder pattern = new StringBuilder();
198 pattern.append(".*");
199 for (final String substring : substrings) {
200 pattern.append(substring);
201 pattern.append("\\s*");
203 pattern.append(".*");
204 return Pattern.compile(pattern.toString(), Pattern.DOTALL);
207 public static boolean containsStringData(final String jsonOutput, final String... substrings) {
208 final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
209 final Matcher matcher = pattern.matcher(jsonOutput);
210 return matcher.matches();
213 public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
214 final String revision) throws ParseException {
215 return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName));
218 public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
219 final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
220 final Map<QName, Object> predicate = new HashMap<>();
221 for (final String key : keys.keySet()) {
222 predicate.put(QName.create(namespace, revision, key), keys.get(key));
225 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(
227 QName.create(namespace, revision, localName), predicate);
230 public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
231 final String namespace, final String revision, final String... keysAndValues) throws ParseException {
232 if ((keysAndValues.length % 2) != 0) {
233 new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)");
235 final Map<QName, Object> predicate = new HashMap<>();
238 while (i < keysAndValues.length) {
239 predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]);
242 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(namespace, revision, localName),
246 static NormalizedNode<?,?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
247 final String ietfInterfacesDate = "2013-07-04";
248 final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
249 final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode = ImmutableMapEntryNodeBuilder.create();
251 final Map<String, Object> predicates = new HashMap<>();
252 predicates.put("name", "eth0");
254 mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
257 .withChild(new ImmutableLeafNodeBuilder<String>()
258 .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
260 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
261 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
262 .withValue("ethernetCsmacd").build());
263 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
264 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
265 .withValue(Boolean.FALSE).build());
266 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
267 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
268 .withValue("some interface").build());
270 return mapEntryNode.build();