Use free-standing transaction in SubscribeToStreamUtil
[netconf.git] / restconf / restconf-nb-rfc8040 / 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.ArgumentMatchers.any;
14 import static org.mockito.Mockito.doReturn;
15 import static org.mockito.Mockito.mock;
16
17 import java.io.BufferedReader;
18 import java.io.ByteArrayOutputStream;
19 import java.io.File;
20 import java.io.FileNotFoundException;
21 import java.io.FileReader;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStreamWriter;
25 import java.nio.charset.StandardCharsets;
26 import java.text.ParseException;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Set;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import javax.xml.transform.OutputKeys;
35 import javax.xml.transform.Transformer;
36 import javax.xml.transform.TransformerException;
37 import javax.xml.transform.TransformerFactory;
38 import javax.xml.transform.dom.DOMSource;
39 import javax.xml.transform.stream.StreamResult;
40 import org.opendaylight.mdsal.common.api.CommitInfo;
41 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
43 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
44 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
45 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
46 import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
47 import org.opendaylight.yangtools.util.xml.UntrustedXML;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.common.Revision;
50 import org.opendaylight.yangtools.yang.common.XMLNamespace;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
53 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
56 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
57 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64 import org.w3c.dom.Document;
65 import org.xml.sax.SAXException;
66
67 public final class TestUtils {
68
69     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
70
71     private TestUtils() {
72
73     }
74
75     public static EffectiveModelContext loadSchemaContext(final String... yangPath)
76             throws FileNotFoundException {
77         final List<File> files = new ArrayList<>();
78         for (final String path : yangPath) {
79             final String pathToFile = TestUtils.class.getResource(path).getPath();
80             final File testDir = new File(pathToFile);
81             final String[] fileList = testDir.list();
82             if (fileList == null) {
83                 throw new FileNotFoundException(pathToFile);
84             }
85
86             for (final String fileName : fileList) {
87                 final File file = new File(testDir, fileName);
88                 if (file.isDirectory() == false) {
89                     files.add(file);
90                 }
91             }
92         }
93
94         return YangParserTestUtils.parseYangFiles(files);
95     }
96
97     public static Module findModule(final Set<Module> modules, final String moduleName) {
98         for (final Module module : modules) {
99             if (module.getName().equals(moduleName)) {
100                 return module;
101             }
102         }
103         return null;
104     }
105
106     public static Document loadDocumentFrom(final InputStream inputStream) {
107         try {
108             return UntrustedXML.newDocumentBuilder().parse(inputStream);
109         } catch (SAXException | IOException e) {
110             LOG.error("Error during loading Document from XML", e);
111             return null;
112         }
113     }
114
115     public static String getDocumentInPrintableForm(final Document doc) {
116         try {
117             final ByteArrayOutputStream out = new ByteArrayOutputStream();
118             final TransformerFactory tf = TransformerFactory.newInstance();
119             final Transformer transformer = tf.newTransformer();
120             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
121             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
122             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
123             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
124             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
125
126             transformer.transform(new DOMSource(requireNonNull(doc)), new StreamResult(new OutputStreamWriter(out,
127                 StandardCharsets.UTF_8)));
128             final byte[] charData = out.toByteArray();
129             return new String(charData, StandardCharsets.UTF_8);
130         } catch (final TransformerException e) {
131             final String msg = "Error during transformation of Document into String";
132             LOG.error(msg, e);
133             return msg;
134         }
135
136     }
137
138     /**
139      * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
140      * module set has only one element then this element is returned.
141      *
142      */
143     public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
144         assertNotNull("Modules can't be null.", modules);
145         if (searchedModuleName != null) {
146             for (final Module m : modules) {
147                 if (m.getName().equals(searchedModuleName)) {
148                     return m;
149                 }
150             }
151         } else if (modules.size() == 1) {
152             return modules.iterator().next();
153         }
154         return null;
155     }
156
157     public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
158         assertNotNull("Module can't be null", module);
159
160         if (searchedDataSchemaName != null) {
161             for (final DataSchemaNode dsn : module.getChildNodes()) {
162                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
163                     return dsn;
164                 }
165             }
166         } else if (module.getChildNodes().size() == 1) {
167             return module.getChildNodes().iterator().next();
168         }
169         return null;
170     }
171
172     public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
173         return QName.create(XMLNamespace.of(uri), Revision.ofNullable(date), name);
174     }
175
176     public static QName buildQName(final String name, final String uri, final String date) {
177         return buildQName(name, uri, date, null);
178     }
179
180     public static QName buildQName(final String name) {
181         return buildQName(name, "", null);
182     }
183
184     public static String loadTextFile(final String filePath) throws IOException {
185         final FileReader fileReader = new FileReader(filePath, StandardCharsets.UTF_8);
186         final BufferedReader bufReader = new BufferedReader(fileReader);
187
188         String line = null;
189         final StringBuilder result = new StringBuilder();
190         while ((line = bufReader.readLine()) != null) {
191             result.append(line);
192         }
193         bufReader.close();
194         return result.toString();
195     }
196
197     private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
198         final StringBuilder pattern = new StringBuilder();
199         pattern.append(".*");
200         for (final String substring : substrings) {
201             pattern.append(substring);
202             pattern.append("\\s*");
203         }
204         pattern.append(".*");
205         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
206     }
207
208     public static boolean containsStringData(final String jsonOutput, final String... substrings) {
209         final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
210         final Matcher matcher = pattern.matcher(jsonOutput);
211         return matcher.matches();
212     }
213
214     public static NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
215             final String revision) throws ParseException {
216         return new NodeIdentifier(QName.create(namespace, revision, localName));
217     }
218
219     public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
220             final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
221         final Map<QName, Object> predicate = new HashMap<>();
222         for (final String key : keys.keySet()) {
223             predicate.put(QName.create(namespace, revision, key), keys.get(key));
224         }
225
226         return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
227     }
228
229     public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
230             final String namespace, final String revision, final String... keysAndValues) throws ParseException {
231         checkArgument(keysAndValues.length % 2 == 0, "number of keys argument have to be divisible by 2 (map)");
232         final Map<QName, Object> predicate = new HashMap<>();
233
234         int index = 0;
235         while (index < keysAndValues.length) {
236             predicate.put(QName.create(namespace, revision, keysAndValues[index++]), keysAndValues[index++]);
237         }
238
239         return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
240     }
241
242     public static NormalizedNode prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
243         final String ietfInterfacesDate = "2013-07-04";
244         final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
245         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode =
246                 ImmutableMapEntryNodeBuilder.create();
247
248         final Map<String, Object> predicates = new HashMap<>();
249         predicates.put("name", "eth0");
250
251         mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
252                 predicates));
253         mapEntryNode
254                 .withChild(new ImmutableLeafNodeBuilder<String>()
255                         .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
256                         .build());
257         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
258                 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
259                 .withValue("ethernetCsmacd").build());
260         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
261                 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
262                 .withValue(Boolean.FALSE).build());
263         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
264                 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
265                 .withValue("some interface").build());
266
267         return mapEntryNode.build();
268     }
269
270     public static SchemaContextHandler newSchemaContextHandler(final EffectiveModelContext schemaContext) {
271         DOMDataBroker mockDataBroker = mock(DOMDataBroker.class);
272         DOMTransactionChain mockChain = mock(DOMTransactionChain.class);
273         DOMDataTreeWriteTransaction mockTx = mock(DOMDataTreeWriteTransaction.class);
274         doReturn(CommitInfo.emptyFluentFuture()).when(mockTx).commit();
275         doReturn(mockTx).when(mockChain).newWriteOnlyTransaction();
276
277         doReturn(mockChain).when(mockDataBroker).createTransactionChain(any());
278         SchemaContextHandler schemaContextHandler = new SchemaContextHandler(
279                 new TransactionChainHandler(mockDataBroker), mock(DOMSchemaService.class));
280         schemaContextHandler.onModelContextUpdated(schemaContext);
281         return schemaContextHandler;
282     }
283 }