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