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.restconf.nb.rfc8040;
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;
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.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.util.xml.UntrustedXML;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.common.Revision;
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.test.util.YangParserTestUtils;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Document;
55 import org.xml.sax.SAXException;
57 public final class TestUtils {
59 private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
65 public static SchemaContext loadSchemaContext(final String... yangPath)
66 throws FileNotFoundException {
67 final List<File> files = new ArrayList<>();
68 for (final String path : yangPath) {
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);
76 for (final String fileName : fileList) {
77 final File file = new File(testDir, fileName);
78 if (file.isDirectory() == false) {
84 return YangParserTestUtils.parseYangFiles(files);
87 public static Module findModule(final Set<Module> modules, final String moduleName) {
88 for (final Module module : modules) {
89 if (module.getName().equals(moduleName)) {
96 public static Document loadDocumentFrom(final InputStream inputStream) {
98 return UntrustedXML.newDocumentBuilder().parse(inputStream);
99 } catch (SAXException | IOException 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,
118 StandardCharsets.UTF_8)));
119 final byte[] charData = out.toByteArray();
120 return new String(charData, StandardCharsets.UTF_8);
121 } catch (final TransformerException e) {
122 final String msg = "Error during transformation of Document into String";
130 * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
131 * module set has only one element then this element is returned.
134 public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
135 assertNotNull("Modules can't be null.", modules);
136 if (searchedModuleName != null) {
137 for (final Module m : modules) {
138 if (m.getName().equals(searchedModuleName)) {
142 } else if (modules.size() == 1) {
143 return modules.iterator().next();
148 public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
149 assertNotNull("Module can't be null", module);
151 if (searchedDataSchemaName != null) {
152 for (final DataSchemaNode dsn : module.getChildNodes()) {
153 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
157 } else if (module.getChildNodes().size() == 1) {
158 return module.getChildNodes().iterator().next();
163 public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
165 final URI u = new URI(uri);
166 return QName.create(u, Revision.ofNullable(date), name);
167 } catch (final URISyntaxException e) {
172 public static QName buildQName(final String name, final String uri, final String date) {
173 return buildQName(name, uri, date, null);
176 public static QName buildQName(final String name) {
177 return buildQName(name, "", null);
180 public static String loadTextFile(final String filePath) throws IOException {
181 final FileReader fileReader = new FileReader(filePath);
182 final BufferedReader bufReader = new BufferedReader(fileReader);
185 final StringBuilder result = new StringBuilder();
186 while ((line = bufReader.readLine()) != null) {
190 return result.toString();
193 private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
194 final StringBuilder pattern = new StringBuilder();
195 pattern.append(".*");
196 for (final String substring : substrings) {
197 pattern.append(substring);
198 pattern.append("\\s*");
200 pattern.append(".*");
201 return Pattern.compile(pattern.toString(), Pattern.DOTALL);
204 public static boolean containsStringData(final String jsonOutput, final String... substrings) {
205 final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
206 final Matcher matcher = pattern.matcher(jsonOutput);
207 return matcher.matches();
210 public static NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
211 final String revision) throws ParseException {
212 return new NodeIdentifier(QName.create(namespace, revision, localName));
215 public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
216 final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
217 final Map<QName, Object> predicate = new HashMap<>();
218 for (final String key : keys.keySet()) {
219 predicate.put(QName.create(namespace, revision, key), keys.get(key));
222 return new NodeIdentifierWithPredicates(QName.create(namespace, revision, localName), predicate);
225 public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
226 final String namespace, final String revision, final String... keysAndValues) throws ParseException {
227 Preconditions.checkArgument(keysAndValues.length % 2 == 0,
228 "number of keys argument have to be divisible by 2 (map)");
229 final Map<QName, Object> predicate = new HashMap<>();
232 while (index < keysAndValues.length) {
233 predicate.put(QName.create(namespace, revision, keysAndValues[index++]), keysAndValues[index++]);
236 return new NodeIdentifierWithPredicates(QName.create(namespace, revision, localName), predicate);
239 public static NormalizedNode<?, ?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
240 final String ietfInterfacesDate = "2013-07-04";
241 final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
242 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode =
243 ImmutableMapEntryNodeBuilder.create();
245 final Map<String, Object> predicates = new HashMap<>();
246 predicates.put("name", "eth0");
248 mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
251 .withChild(new ImmutableLeafNodeBuilder<String>()
252 .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
254 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
255 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
256 .withValue("ethernetCsmacd").build());
257 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
258 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
259 .withValue(Boolean.FALSE).build());
260 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
261 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
262 .withValue("some interface").build());
264 return mapEntryNode.build();