Replace old yang parser usages in restconf
[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.sql.Date;
23 import java.text.ParseException;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.Set;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import javax.xml.parsers.DocumentBuilder;
30 import javax.xml.parsers.DocumentBuilderFactory;
31 import javax.xml.parsers.ParserConfigurationException;
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.yang.common.QName;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
43 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
49 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
50 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
51 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
52 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
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     public static SchemaContext loadSchemaContext(final String... yangPath)
63             throws FileNotFoundException, ReactorException {
64         final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
65
66         for (int i = 0; i < yangPath.length; i++) {
67             final String path = yangPath[i];
68             final String pathToFile = TestUtils.class.getResource(path).getPath();
69             final File testDir = new File(pathToFile);
70             final String[] fileList = testDir.list();
71             if (fileList == null) {
72                 throw new FileNotFoundException(pathToFile);
73             }
74             for (int j = 0; j < fileList.length; j++) {
75                 final String fileName = fileList[j];
76                 final File file = new File(testDir, fileName);
77                 if (file.isDirectory() == false) {
78                     reactor.addSource(new YangStatementSourceImpl(new NamedFileInputStream(file, file.getPath())));
79                 }
80             }
81         }
82         return reactor.buildEffective();
83     }
84
85     public static Module findModule(final Set<Module> modules, final String moduleName) {
86         for (final Module module : modules) {
87             if (module.getName().equals(moduleName)) {
88                 return module;
89             }
90         }
91         return null;
92     }
93
94     public static Document loadDocumentFrom(final InputStream inputStream) {
95         try {
96             final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
97             final DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
98             return docBuilder.parse(inputStream);
99         } catch (SAXException | IOException | ParserConfigurationException 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, "UTF-8")));
118             final byte[] charData = out.toByteArray();
119             return new String(charData, "UTF-8");
120         } catch (IOException | 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 Set<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             final URI u = new URI(uri);
165             Date dt = null;
166             if (date != null) {
167                 dt = Date.valueOf(date);
168             }
169             return QName.create(u, dt, name);
170         } catch (final URISyntaxException e) {
171             return null;
172         }
173     }
174
175     public static QName buildQName(final String name, final String uri, final String date) {
176         return buildQName(name, uri, date, null);
177     }
178
179     public static QName buildQName(final String name) {
180         return buildQName(name, "", null);
181     }
182
183     public static String loadTextFile(final String filePath) throws IOException {
184         final FileReader fileReader = new FileReader(filePath);
185         final BufferedReader bufReader = new BufferedReader(fileReader);
186
187         String line = null;
188         final StringBuilder result = new StringBuilder();
189         while ((line = bufReader.readLine()) != null) {
190             result.append(line);
191         }
192         bufReader.close();
193         return result.toString();
194     }
195
196     private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
197         final StringBuilder pattern = new StringBuilder();
198         pattern.append(".*");
199         for (final String substring : substrings) {
200             pattern.append(substring);
201             pattern.append("\\s*");
202         }
203         pattern.append(".*");
204         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
205     }
206
207     public static boolean containsStringData(final String jsonOutput, final String... substrings) {
208         final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
209         final Matcher matcher = pattern.matcher(jsonOutput);
210         return matcher.matches();
211     }
212
213     public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
214             final String revision) throws ParseException {
215         return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName));
216     }
217
218     public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
219             final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
220         final Map<QName, Object> predicate = new HashMap<>();
221         for (final String key : keys.keySet()) {
222             predicate.put(QName.create(namespace, revision, key), keys.get(key));
223         }
224
225         return new YangInstanceIdentifier.NodeIdentifierWithPredicates(
226
227         QName.create(namespace, revision, localName), predicate);
228     }
229
230     public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
231             final String namespace, final String revision, final String... keysAndValues) throws ParseException {
232         if ((keysAndValues.length % 2) != 0) {
233             new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)");
234         }
235         final Map<QName, Object> predicate = new HashMap<>();
236
237         int i = 0;
238         while (i < keysAndValues.length) {
239             predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]);
240         }
241
242         return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(namespace, revision, localName),
243                 predicate);
244     }
245
246     static NormalizedNode<?,?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
247         final String ietfInterfacesDate = "2013-07-04";
248         final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
249         final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode = ImmutableMapEntryNodeBuilder.create();
250
251         final Map<String, Object> predicates = new HashMap<>();
252         predicates.put("name", "eth0");
253
254         mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
255                 predicates));
256         mapEntryNode
257                 .withChild(new ImmutableLeafNodeBuilder<String>()
258                         .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
259                         .build());
260         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
261                 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
262                 .withValue("ethernetCsmacd").build());
263         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
264                 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
265                 .withValue(Boolean.FALSE).build());
266         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
267                 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
268                 .withValue("some interface").build());
269
270         return mapEntryNode.build();
271     }
272 }