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;
23 import java.nio.charset.StandardCharsets;
25 import java.text.ParseException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
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.util.xml.UntrustedXML;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
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.parser.spi.meta.ReactorException;
52 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
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 List<File> files = new ArrayList<>();
65 for (final String path : yangPath) {
66 final String pathToFile = TestUtils.class.getResource(path).getPath();
67 final File testDir = new File(pathToFile);
68 final String[] fileList = testDir.list();
69 if (fileList == null) {
70 throw new FileNotFoundException(pathToFile);
73 for (final String fileName : fileList) {
74 final File file = new File(testDir, fileName);
75 if (file.isDirectory() == false) {
81 return YangParserTestUtils.parseYangSources(files);
84 public static Module findModule(final Set<Module> modules, final String moduleName) {
85 for (final Module module : modules) {
86 if (module.getName().equals(moduleName)) {
93 public static Document loadDocumentFrom(final InputStream inputStream) {
95 return UntrustedXML.newDocumentBuilder().parse(inputStream);
96 } catch (SAXException | IOException e) {
97 LOG.error("Error during loading Document from XML", e);
102 public static String getDocumentInPrintableForm(final Document doc) {
103 Preconditions.checkNotNull(doc);
105 final ByteArrayOutputStream out = new ByteArrayOutputStream();
106 final TransformerFactory tf = TransformerFactory.newInstance();
107 final Transformer transformer = tf.newTransformer();
108 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
109 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
110 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
111 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
112 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
114 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out,
115 StandardCharsets.UTF_8)));
116 final byte[] charData = out.toByteArray();
117 return new String(charData, StandardCharsets.UTF_8);
118 } catch (final TransformerException e) {
119 final String msg = "Error during transformation of Document into String";
127 * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
128 * module set has only one element then this element is returned.
131 public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
132 assertNotNull("Modules can't be null.", modules);
133 if (searchedModuleName != null) {
134 for (final Module m : modules) {
135 if (m.getName().equals(searchedModuleName)) {
139 } else if (modules.size() == 1) {
140 return modules.iterator().next();
145 public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
146 assertNotNull("Module can't be null", module);
148 if (searchedDataSchemaName != null) {
149 for (final DataSchemaNode dsn : module.getChildNodes()) {
150 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
154 } else if (module.getChildNodes().size() == 1) {
155 return module.getChildNodes().iterator().next();
160 public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
162 final URI u = new URI(uri);
165 dt = Date.valueOf(date);
167 return QName.create(u, dt, name);
168 } catch (final URISyntaxException e) {
173 public static QName buildQName(final String name, final String uri, final String date) {
174 return buildQName(name, uri, date, null);
177 public static QName buildQName(final String name) {
178 return buildQName(name, "", null);
181 public static String loadTextFile(final String filePath) throws IOException {
182 final FileReader fileReader = new FileReader(filePath);
183 final BufferedReader bufReader = new BufferedReader(fileReader);
186 final StringBuilder result = new StringBuilder();
187 while ((line = bufReader.readLine()) != null) {
191 return result.toString();
194 private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
195 final StringBuilder pattern = new StringBuilder();
196 pattern.append(".*");
197 for (final String substring : substrings) {
198 pattern.append(substring);
199 pattern.append("\\s*");
201 pattern.append(".*");
202 return Pattern.compile(pattern.toString(), Pattern.DOTALL);
205 public static boolean containsStringData(final String jsonOutput, final String... substrings) {
206 final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
207 final Matcher matcher = pattern.matcher(jsonOutput);
208 return matcher.matches();
211 public static NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
212 final String revision) throws ParseException {
213 return new NodeIdentifier(QName.create(namespace, revision, localName));
216 public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
217 final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
218 final Map<QName, Object> predicate = new HashMap<>();
219 for (final String key : keys.keySet()) {
220 predicate.put(QName.create(namespace, revision, key), keys.get(key));
223 return new NodeIdentifierWithPredicates(QName.create(namespace, revision, localName), predicate);
226 public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
227 final String namespace, final String revision, final String... keysAndValues) throws ParseException {
228 Preconditions.checkArgument(keysAndValues.length % 2 == 0,
229 "number of keys argument have to be divisible by 2 (map)");
230 final Map<QName, Object> predicate = new HashMap<>();
233 while (index < keysAndValues.length) {
234 predicate.put(QName.create(namespace, revision, keysAndValues[index++]), keysAndValues[index++]);
237 return new NodeIdentifierWithPredicates(QName.create(namespace, revision, localName), predicate);
240 public static NormalizedNode<?, ?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
241 final String ietfInterfacesDate = "2013-07-04";
242 final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
243 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode =
244 ImmutableMapEntryNodeBuilder.create();
246 final Map<String, Object> predicates = new HashMap<>();
247 predicates.put("name", "eth0");
249 mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
252 .withChild(new ImmutableLeafNodeBuilder<String>()
253 .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
255 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
256 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
257 .withValue("ethernetCsmacd").build());
258 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
259 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
260 .withValue(Boolean.FALSE).build());
261 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
262 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
263 .withValue("some interface").build());
265 return mapEntryNode.build();