Rename restconf-nb-rfc8040 to restconf-nb
[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.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
53 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
54 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
57 import org.opendaylight.yangtools.yang.model.api.Module;
58 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.w3c.dom.Document;
62 import org.xml.sax.SAXException;
63
64 public final class TestUtils {
65
66     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
67
68     private TestUtils() {
69
70     }
71
72     public static EffectiveModelContext loadSchemaContext(final String... yangPath)
73             throws FileNotFoundException {
74         final List<File> files = new ArrayList<>();
75         for (final String path : yangPath) {
76             final String pathToFile = TestUtils.class.getResource(path).getPath();
77             final File testDir = new File(pathToFile);
78             final String[] fileList = testDir.list();
79             if (fileList == null) {
80                 throw new FileNotFoundException(pathToFile);
81             }
82
83             for (final String fileName : fileList) {
84                 final File file = new File(testDir, fileName);
85                 if (file.isDirectory() == false) {
86                     files.add(file);
87                 }
88             }
89         }
90
91         return YangParserTestUtils.parseYangFiles(files);
92     }
93
94     public static Module findModule(final Set<Module> modules, final String moduleName) {
95         for (final Module module : modules) {
96             if (module.getName().equals(moduleName)) {
97                 return module;
98             }
99         }
100         return null;
101     }
102
103     public static Document loadDocumentFrom(final InputStream inputStream) {
104         try {
105             return UntrustedXML.newDocumentBuilder().parse(inputStream);
106         } catch (SAXException | IOException e) {
107             LOG.error("Error during loading Document from XML", e);
108             return null;
109         }
110     }
111
112     public static String getDocumentInPrintableForm(final Document doc) {
113         try {
114             final ByteArrayOutputStream out = new ByteArrayOutputStream();
115             final TransformerFactory tf = TransformerFactory.newInstance();
116             final Transformer transformer = tf.newTransformer();
117             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
118             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
119             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
120             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
121             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
122
123             transformer.transform(new DOMSource(requireNonNull(doc)), new StreamResult(new OutputStreamWriter(out,
124                 StandardCharsets.UTF_8)));
125             final byte[] charData = out.toByteArray();
126             return new String(charData, StandardCharsets.UTF_8);
127         } catch (final TransformerException e) {
128             final String msg = "Error during transformation of Document into String";
129             LOG.error(msg, e);
130             return msg;
131         }
132
133     }
134
135     /**
136      * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
137      * module set has only one element then this element is returned.
138      *
139      */
140     public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
141         assertNotNull("Modules can't be null.", modules);
142         if (searchedModuleName != null) {
143             for (final Module m : modules) {
144                 if (m.getName().equals(searchedModuleName)) {
145                     return m;
146                 }
147             }
148         } else if (modules.size() == 1) {
149             return modules.iterator().next();
150         }
151         return null;
152     }
153
154     public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
155         assertNotNull("Module can't be null", module);
156
157         if (searchedDataSchemaName != null) {
158             for (final DataSchemaNode dsn : module.getChildNodes()) {
159                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
160                     return dsn;
161                 }
162             }
163         } else if (module.getChildNodes().size() == 1) {
164             return module.getChildNodes().iterator().next();
165         }
166         return null;
167     }
168
169     public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
170         return QName.create(XMLNamespace.of(uri), Revision.ofNullable(date), name);
171     }
172
173     public static QName buildQName(final String name, final String uri, final String date) {
174         return buildQName(name, uri, date, null);
175     }
176
177     public static QName buildQName(final String name) {
178         return buildQName(name, "", null);
179     }
180
181     public static String loadTextFile(final String filePath) throws IOException {
182         final FileReader fileReader = new FileReader(filePath, StandardCharsets.UTF_8);
183         final BufferedReader bufReader = new BufferedReader(fileReader);
184
185         String line = null;
186         final StringBuilder result = new StringBuilder();
187         while ((line = bufReader.readLine()) != null) {
188             result.append(line);
189         }
190         bufReader.close();
191         return result.toString();
192     }
193
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*");
200         }
201         pattern.append(".*");
202         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
203     }
204
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();
209     }
210
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));
214     }
215
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));
221         }
222
223         return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
224     }
225
226     public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
227             final String namespace, final String revision, final String... keysAndValues) throws ParseException {
228         checkArgument(keysAndValues.length % 2 == 0, "number of keys argument have to be divisible by 2 (map)");
229         final Map<QName, Object> predicate = new HashMap<>();
230
231         int index = 0;
232         while (index < keysAndValues.length) {
233             predicate.put(QName.create(namespace, revision, keysAndValues[index++]), keysAndValues[index++]);
234         }
235
236         return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
237     }
238
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 DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode =
243                 ImmutableMapEntryNodeBuilder.create();
244
245         final Map<String, Object> predicates = new HashMap<>();
246         predicates.put("name", "eth0");
247
248         mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
249                 predicates));
250         mapEntryNode
251                 .withChild(new ImmutableLeafNodeBuilder<String>()
252                         .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
253                         .build());
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());
263
264         return mapEntryNode.build();
265     }
266
267     public static SchemaContextHandler newSchemaContextHandler(final EffectiveModelContext schemaContext) {
268         DOMDataBroker mockDataBroker = mock(DOMDataBroker.class);
269         DOMDataTreeWriteTransaction mockTx = mock(DOMDataTreeWriteTransaction.class);
270         doReturn(CommitInfo.emptyFluentFuture()).when(mockTx).commit();
271         doReturn(mockTx).when(mockDataBroker).newWriteOnlyTransaction();
272
273         SchemaContextHandler schemaContextHandler = new SchemaContextHandler(mockDataBroker,
274             mock(DOMSchemaService.class));
275         schemaContextHandler.onModelContextUpdated(schemaContext);
276         return schemaContextHandler;
277     }
278 }