ab7ad9bf87acdff984bf85995e8e00e461ef86bc
[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 org.junit.Assert.assertNotNull;
11
12 import com.google.common.base.Preconditions;
13 import java.io.BufferedReader;
14 import java.io.ByteArrayOutputStream;
15 import java.io.File;
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;
21 import java.net.URI;
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;
28 import java.util.Map;
29 import java.util.Set;
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;
56
57 public final class TestUtils {
58
59     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
60
61     private TestUtils() {
62
63     }
64
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);
74             }
75
76             for (final String fileName : fileList) {
77                 final File file = new File(testDir, fileName);
78                 if (file.isDirectory() == false) {
79                     files.add(file);
80                 }
81             }
82         }
83
84         return YangParserTestUtils.parseYangFiles(files);
85     }
86
87     public static Module findModule(final Set<Module> modules, final String moduleName) {
88         for (final Module module : modules) {
89             if (module.getName().equals(moduleName)) {
90                 return module;
91             }
92         }
93         return null;
94     }
95
96     public static Document loadDocumentFrom(final InputStream inputStream) {
97         try {
98             return UntrustedXML.newDocumentBuilder().parse(inputStream);
99         } catch (SAXException | IOException e) {
100             LOG.error("Error during loading Document from XML", e);
101             return null;
102         }
103     }
104
105     public static String getDocumentInPrintableForm(final Document doc) {
106         Preconditions.checkNotNull(doc);
107         try {
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");
116
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";
123             LOG.error(msg, e);
124             return msg;
125         }
126
127     }
128
129     /**
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.
132      *
133      */
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)) {
139                     return m;
140                 }
141             }
142         } else if (modules.size() == 1) {
143             return modules.iterator().next();
144         }
145         return null;
146     }
147
148     public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
149         assertNotNull("Module can't be null", module);
150
151         if (searchedDataSchemaName != null) {
152             for (final DataSchemaNode dsn : module.getChildNodes()) {
153                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
154                     return dsn;
155                 }
156             }
157         } else if (module.getChildNodes().size() == 1) {
158             return module.getChildNodes().iterator().next();
159         }
160         return null;
161     }
162
163     public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
164         try {
165             final URI u = new URI(uri);
166             return QName.create(u, Revision.ofNullable(date), name);
167         } catch (final URISyntaxException e) {
168             return null;
169         }
170     }
171
172     public static QName buildQName(final String name, final String uri, final String date) {
173         return buildQName(name, uri, date, null);
174     }
175
176     public static QName buildQName(final String name) {
177         return buildQName(name, "", null);
178     }
179
180     public static String loadTextFile(final String filePath) throws IOException {
181         final FileReader fileReader = new FileReader(filePath);
182         final BufferedReader bufReader = new BufferedReader(fileReader);
183
184         String line = null;
185         final StringBuilder result = new StringBuilder();
186         while ((line = bufReader.readLine()) != null) {
187             result.append(line);
188         }
189         bufReader.close();
190         return result.toString();
191     }
192
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*");
199         }
200         pattern.append(".*");
201         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
202     }
203
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();
208     }
209
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));
213     }
214
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));
220         }
221
222         return new NodeIdentifierWithPredicates(QName.create(namespace, revision, localName), predicate);
223     }
224
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<>();
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 new NodeIdentifierWithPredicates(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 DataContainerNodeAttrBuilder<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 }