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 com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12 import static org.junit.Assert.assertNotNull;
13 import static org.mockito.Mockito.doReturn;
14 import static org.mockito.Mockito.mock;
16 import java.io.BufferedReader;
17 import java.io.ByteArrayOutputStream;
19 import java.io.FileNotFoundException;
20 import java.io.FileReader;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStreamWriter;
24 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.mdsal.common.api.CommitInfo;
40 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
42 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
43 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
44 import org.opendaylight.yangtools.util.xml.UntrustedXML;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.common.Revision;
47 import org.opendaylight.yangtools.yang.common.XMLNamespace;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
51 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
52 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
53 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Document;
60 import org.xml.sax.SAXException;
62 public final class TestUtils {
64 private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
70 public static EffectiveModelContext loadSchemaContext(final String... yangPath)
71 throws FileNotFoundException {
72 final List<File> files = new ArrayList<>();
73 for (final String path : yangPath) {
74 final String pathToFile = TestUtils.class.getResource(path).getPath();
75 final File testDir = new File(pathToFile);
76 final String[] fileList = testDir.list();
77 if (fileList == null) {
78 throw new FileNotFoundException(pathToFile);
81 for (final String fileName : fileList) {
82 final File file = new File(testDir, fileName);
83 if (file.isDirectory() == false) {
89 return YangParserTestUtils.parseYangFiles(files);
92 public static Module findModule(final Set<Module> modules, final String moduleName) {
93 for (final Module module : modules) {
94 if (module.getName().equals(moduleName)) {
101 public static Document loadDocumentFrom(final InputStream inputStream) {
103 return UntrustedXML.newDocumentBuilder().parse(inputStream);
104 } catch (SAXException | IOException e) {
105 LOG.error("Error during loading Document from XML", e);
110 public static String getDocumentInPrintableForm(final Document doc) {
112 final ByteArrayOutputStream out = new ByteArrayOutputStream();
113 final TransformerFactory tf = TransformerFactory.newInstance();
114 final Transformer transformer = tf.newTransformer();
115 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
116 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
117 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
118 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
119 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
121 transformer.transform(new DOMSource(requireNonNull(doc)), new StreamResult(new OutputStreamWriter(out,
122 StandardCharsets.UTF_8)));
123 final byte[] charData = out.toByteArray();
124 return new String(charData, StandardCharsets.UTF_8);
125 } catch (final TransformerException e) {
126 final String msg = "Error during transformation of Document into String";
134 * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
135 * module set has only one element then this element is returned.
138 public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
139 assertNotNull("Modules can't be null.", modules);
140 if (searchedModuleName != null) {
141 for (final Module m : modules) {
142 if (m.getName().equals(searchedModuleName)) {
146 } else if (modules.size() == 1) {
147 return modules.iterator().next();
152 public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
153 assertNotNull("Module can't be null", module);
155 if (searchedDataSchemaName != null) {
156 for (final DataSchemaNode dsn : module.getChildNodes()) {
157 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
161 } else if (module.getChildNodes().size() == 1) {
162 return module.getChildNodes().iterator().next();
167 public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
168 return QName.create(XMLNamespace.of(uri), Revision.ofNullable(date), name);
171 public static QName buildQName(final String name, final String uri, final String date) {
172 return buildQName(name, uri, date, null);
175 public static QName buildQName(final String name) {
176 return buildQName(name, "", null);
179 public static String loadTextFile(final String filePath) throws IOException {
180 final FileReader fileReader = new FileReader(filePath, StandardCharsets.UTF_8);
181 final BufferedReader bufReader = new BufferedReader(fileReader);
184 final StringBuilder result = new StringBuilder();
185 while ((line = bufReader.readLine()) != null) {
189 return result.toString();
192 private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
193 final StringBuilder pattern = new StringBuilder();
194 pattern.append(".*");
195 for (final String substring : substrings) {
196 pattern.append(substring);
197 pattern.append("\\s*");
199 pattern.append(".*");
200 return Pattern.compile(pattern.toString(), Pattern.DOTALL);
203 public static boolean containsStringData(final String jsonOutput, final String... substrings) {
204 final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
205 final Matcher matcher = pattern.matcher(jsonOutput);
206 return matcher.matches();
209 public static NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
210 final String revision) throws ParseException {
211 return new NodeIdentifier(QName.create(namespace, revision, localName));
214 public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
215 final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
216 final Map<QName, Object> predicate = new HashMap<>();
217 for (final String key : keys.keySet()) {
218 predicate.put(QName.create(namespace, revision, key), keys.get(key));
221 return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
224 public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
225 final String namespace, final String revision, final String... keysAndValues) throws ParseException {
226 checkArgument(keysAndValues.length % 2 == 0, "number of keys argument have to be divisible by 2 (map)");
227 final Map<QName, Object> predicate = new HashMap<>();
230 while (index < keysAndValues.length) {
231 predicate.put(QName.create(namespace, revision, keysAndValues[index++]), keysAndValues[index++]);
234 return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
237 public static MapEntryNode prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
238 final String ietfInterfacesDate = "2013-07-04";
239 final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
241 return Builders.mapEntryBuilder()
242 .withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
243 Map.of("name", "eth0")))
244 .withChild(ImmutableNodes.leafNode(getNodeIdentifier("name", namespace, ietfInterfacesDate), "eth0"))
245 .withChild(ImmutableNodes.leafNode(getNodeIdentifier("type", namespace, ietfInterfacesDate),
247 .withChild(ImmutableNodes.leafNode(getNodeIdentifier("enabled", namespace, ietfInterfacesDate),
249 .withChild(ImmutableNodes.leafNode(getNodeIdentifier("description", namespace, ietfInterfacesDate),
254 public static SchemaContextHandler newSchemaContextHandler(final EffectiveModelContext schemaContext) {
255 DOMDataBroker mockDataBroker = mock(DOMDataBroker.class);
256 DOMDataTreeWriteTransaction mockTx = mock(DOMDataTreeWriteTransaction.class);
257 doReturn(CommitInfo.emptyFluentFuture()).when(mockTx).commit();
258 doReturn(mockTx).when(mockDataBroker).newWriteOnlyTransaction();
260 SchemaContextHandler schemaContextHandler = new SchemaContextHandler(mockDataBroker,
261 mock(DOMSchemaService.class));
262 schemaContextHandler.onModelContextUpdated(schemaContext);
263 return schemaContextHandler;