1fe3692b49e39a653c30acff57a5a00494acf2ca
[netconf.git] / restconf / restconf-nb / src / test / java / org / opendaylight / restconf / nb / rfc8040 / TestUtils.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.nb.rfc8040;
9
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;
15
16 import java.io.BufferedReader;
17 import java.io.ByteArrayOutputStream;
18 import java.io.File;
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;
29 import java.util.Map;
30 import java.util.Set;
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;
61
62 public final class TestUtils {
63
64     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
65
66     private TestUtils() {
67
68     }
69
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);
79             }
80
81             for (final String fileName : fileList) {
82                 final File file = new File(testDir, fileName);
83                 if (file.isDirectory() == false) {
84                     files.add(file);
85                 }
86             }
87         }
88
89         return YangParserTestUtils.parseYangFiles(files);
90     }
91
92     public static Module findModule(final Set<Module> modules, final String moduleName) {
93         for (final Module module : modules) {
94             if (module.getName().equals(moduleName)) {
95                 return module;
96             }
97         }
98         return null;
99     }
100
101     public static Document loadDocumentFrom(final InputStream inputStream) {
102         try {
103             return UntrustedXML.newDocumentBuilder().parse(inputStream);
104         } catch (SAXException | IOException e) {
105             LOG.error("Error during loading Document from XML", e);
106             return null;
107         }
108     }
109
110     public static String getDocumentInPrintableForm(final Document doc) {
111         try {
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");
120
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";
127             LOG.error(msg, e);
128             return msg;
129         }
130
131     }
132
133     /**
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.
136      *
137      */
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)) {
143                     return m;
144                 }
145             }
146         } else if (modules.size() == 1) {
147             return modules.iterator().next();
148         }
149         return null;
150     }
151
152     public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
153         assertNotNull("Module can't be null", module);
154
155         if (searchedDataSchemaName != null) {
156             for (final DataSchemaNode dsn : module.getChildNodes()) {
157                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
158                     return dsn;
159                 }
160             }
161         } else if (module.getChildNodes().size() == 1) {
162             return module.getChildNodes().iterator().next();
163         }
164         return null;
165     }
166
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);
169     }
170
171     public static QName buildQName(final String name, final String uri, final String date) {
172         return buildQName(name, uri, date, null);
173     }
174
175     public static QName buildQName(final String name) {
176         return buildQName(name, "", null);
177     }
178
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);
182
183         String line = null;
184         final StringBuilder result = new StringBuilder();
185         while ((line = bufReader.readLine()) != null) {
186             result.append(line);
187         }
188         bufReader.close();
189         return result.toString();
190     }
191
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*");
198         }
199         pattern.append(".*");
200         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
201     }
202
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();
207     }
208
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));
212     }
213
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));
219         }
220
221         return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
222     }
223
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<>();
228
229         int index = 0;
230         while (index < keysAndValues.length) {
231             predicate.put(QName.create(namespace, revision, keysAndValues[index++]), keysAndValues[index++]);
232         }
233
234         return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
235     }
236
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";
240
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),
246                 "ethernetCsmacd"))
247             .withChild(ImmutableNodes.leafNode(getNodeIdentifier("enabled", namespace, ietfInterfacesDate),
248                 Boolean.FALSE))
249             .withChild(ImmutableNodes.leafNode(getNodeIdentifier("description", namespace, ietfInterfacesDate),
250                 "some interface"))
251             .build();
252     }
253
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();
259
260         SchemaContextHandler schemaContextHandler = new SchemaContextHandler(mockDataBroker,
261             mock(DOMSchemaService.class));
262         schemaContextHandler.onModelContextUpdated(schemaContext);
263         return schemaContextHandler;
264     }
265 }