Enable modernizer in restconf-nb-bierman02
[netconf.git] / restconf / restconf-nb-bierman02 / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / 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.controller.sal.restconf.impl.test;
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
14 import java.io.BufferedReader;
15 import java.io.ByteArrayOutputStream;
16 import java.io.File;
17 import java.io.FileNotFoundException;
18 import java.io.FileReader;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStreamWriter;
22 import java.net.URI;
23 import java.net.URISyntaxException;
24 import java.nio.charset.StandardCharsets;
25 import java.text.ParseException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
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.yangtools.util.xml.UntrustedXML;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.common.Revision;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
47 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
48 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
51 import org.opendaylight.yangtools.yang.model.api.Module;
52 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Document;
56 import org.xml.sax.SAXException;
57
58 public final class TestUtils {
59
60     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
61
62     private TestUtils() {
63
64     }
65
66     public static EffectiveModelContext loadSchemaContext(final String... yangPath) 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 Collection<? extends 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         try {
107             final ByteArrayOutputStream out = new ByteArrayOutputStream();
108             final TransformerFactory tf = TransformerFactory.newInstance();
109             final Transformer transformer = tf.newTransformer();
110             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
111             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
112             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
113             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
114             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
115
116             transformer.transform(new DOMSource(requireNonNull(doc)), new StreamResult(new OutputStreamWriter(out,
117                 StandardCharsets.UTF_8)));
118             final byte[] charData = out.toByteArray();
119             return new String(charData, StandardCharsets.UTF_8);
120         } catch (final TransformerException e) {
121             final String msg = "Error during transformation of Document into String";
122             LOG.error(msg, e);
123             return msg;
124         }
125
126     }
127
128     /**
129      * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
130      * module set has only one element then this element is returned.
131      *
132      */
133     public static Module resolveModule(final String searchedModuleName, final Collection<? extends Module> modules) {
134         assertNotNull("Modules can't be null.", modules);
135         if (searchedModuleName != null) {
136             for (final Module m : modules) {
137                 if (m.getName().equals(searchedModuleName)) {
138                     return m;
139                 }
140             }
141         } else if (modules.size() == 1) {
142             return modules.iterator().next();
143         }
144         return null;
145     }
146
147     public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
148         assertNotNull("Module can't be null", module);
149
150         if (searchedDataSchemaName != null) {
151             for (final DataSchemaNode dsn : module.getChildNodes()) {
152                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
153                     return dsn;
154                 }
155             }
156         } else if (module.getChildNodes().size() == 1) {
157             return module.getChildNodes().iterator().next();
158         }
159         return null;
160     }
161
162     public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
163         try {
164             return QName.create(new URI(uri), Revision.ofNullable(date), name);
165         } catch (final URISyntaxException e) {
166             return null;
167         }
168     }
169
170     public static QName buildQName(final String name, final String uri, final String date) {
171         return buildQName(name, uri, date, null);
172     }
173
174     public static QName buildQName(final String name) {
175         return buildQName(name, "", null);
176     }
177
178     public static String loadTextFile(final String filePath) throws IOException {
179         final FileReader fileReader = new FileReader(filePath, StandardCharsets.UTF_8);
180         final BufferedReader bufReader = new BufferedReader(fileReader);
181
182         String line = null;
183         final StringBuilder result = new StringBuilder();
184         while ((line = bufReader.readLine()) != null) {
185             result.append(line);
186         }
187         bufReader.close();
188         return result.toString();
189     }
190
191     private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
192         final StringBuilder pattern = new StringBuilder();
193         pattern.append(".*");
194         for (final String substring : substrings) {
195             pattern.append(substring);
196             pattern.append("\\s*");
197         }
198         pattern.append(".*");
199         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
200     }
201
202     public static boolean containsStringData(final String jsonOutput, final String... substrings) {
203         final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
204         final Matcher matcher = pattern.matcher(jsonOutput);
205         return matcher.matches();
206     }
207
208     public static NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
209             final String revision) throws ParseException {
210         return new NodeIdentifier(QName.create(namespace, revision, localName));
211     }
212
213     public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
214             final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
215         final Map<QName, Object> predicate = new HashMap<>();
216         for (final String key : keys.keySet()) {
217             predicate.put(QName.create(namespace, revision, key), keys.get(key));
218         }
219
220         return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
221     }
222
223     public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
224             final String namespace, final String revision, final String... keysAndValues) throws ParseException {
225         checkArgument(keysAndValues.length % 2 == 0, "number of keys argument have to be divisible by 2 (map)");
226         final Map<QName, Object> predicate = new HashMap<>();
227
228         int index = 0;
229         while (index < keysAndValues.length) {
230             predicate.put(QName.create(namespace, revision, keysAndValues[index++]), keysAndValues[index++]);
231         }
232
233         return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
234     }
235
236     public static NormalizedNode<?, ?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
237         final String ietfInterfacesDate = "2013-07-04";
238         final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
239         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode =
240                 ImmutableMapEntryNodeBuilder.create();
241
242         final Map<String, Object> predicates = new HashMap<>();
243         predicates.put("name", "eth0");
244
245         mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
246                 predicates));
247         mapEntryNode
248                 .withChild(new ImmutableLeafNodeBuilder<String>()
249                         .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
250                         .build());
251         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
252                 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
253                 .withValue("ethernetCsmacd").build());
254         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
255                 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
256                 .withValue(Boolean.FALSE).build());
257         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
258                 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
259                 .withValue("some interface").build());
260
261         return mapEntryNode.build();
262     }
263 }