Split Restconf implementations (draft02 and RFC) - Prepare modules
[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 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.sql.Date;
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.yangtools.util.xml.UntrustedXML;
40 import org.opendaylight.yangtools.yang.common.QName;
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.parser.spi.meta.ReactorException;
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     public static SchemaContext loadSchemaContext(final String... yangPath)
63             throws FileNotFoundException, ReactorException {
64         final List<File> files = new ArrayList<>();
65         for (final String path : yangPath) {
66             final String pathToFile = TestUtils.class.getResource(path).getPath();
67             final File testDir = new File(pathToFile);
68             final String[] fileList = testDir.list();
69             if (fileList == null) {
70                 throw new FileNotFoundException(pathToFile);
71             }
72
73             for (final String fileName : fileList) {
74                 final File file = new File(testDir, fileName);
75                 if (file.isDirectory() == false) {
76                     files.add(file);
77                 }
78             }
79         }
80
81         return YangParserTestUtils.parseYangSources(files);
82     }
83
84     public static Module findModule(final Set<Module> modules, final String moduleName) {
85         for (final Module module : modules) {
86             if (module.getName().equals(moduleName)) {
87                 return module;
88             }
89         }
90         return null;
91     }
92
93     public static Document loadDocumentFrom(final InputStream inputStream) {
94         try {
95             return UntrustedXML.newDocumentBuilder().parse(inputStream);
96         } catch (SAXException | IOException e) {
97             LOG.error("Error during loading Document from XML", e);
98             return null;
99         }
100     }
101
102     public static String getDocumentInPrintableForm(final Document doc) {
103         Preconditions.checkNotNull(doc);
104         try {
105             final ByteArrayOutputStream out = new ByteArrayOutputStream();
106             final TransformerFactory tf = TransformerFactory.newInstance();
107             final Transformer transformer = tf.newTransformer();
108             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
109             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
110             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
111             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
112             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
113
114             transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out,
115                 StandardCharsets.UTF_8)));
116             final byte[] charData = out.toByteArray();
117             return new String(charData, StandardCharsets.UTF_8);
118         } catch (final TransformerException e) {
119             final String msg = "Error during transformation of Document into String";
120             LOG.error(msg, e);
121             return msg;
122         }
123
124     }
125
126     /**
127      * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
128      * module set has only one element then this element is returned.
129      *
130      */
131     public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
132         assertNotNull("Modules can't be null.", modules);
133         if (searchedModuleName != null) {
134             for (final Module m : modules) {
135                 if (m.getName().equals(searchedModuleName)) {
136                     return m;
137                 }
138             }
139         } else if (modules.size() == 1) {
140             return modules.iterator().next();
141         }
142         return null;
143     }
144
145     public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
146         assertNotNull("Module can't be null", module);
147
148         if (searchedDataSchemaName != null) {
149             for (final DataSchemaNode dsn : module.getChildNodes()) {
150                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
151                     return dsn;
152                 }
153             }
154         } else if (module.getChildNodes().size() == 1) {
155             return module.getChildNodes().iterator().next();
156         }
157         return null;
158     }
159
160     public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
161         try {
162             final URI u = new URI(uri);
163             Date dt = null;
164             if (date != null) {
165                 dt = Date.valueOf(date);
166             }
167             return QName.create(u, dt, name);
168         } catch (final URISyntaxException e) {
169             return null;
170         }
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);
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 new NodeIdentifierWithPredicates(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         Preconditions.checkArgument(keysAndValues.length % 2 == 0,
229                 "number of keys argument have to be divisible by 2 (map)");
230         final Map<QName, Object> predicate = new HashMap<>();
231
232         int index = 0;
233         while (index < keysAndValues.length) {
234             predicate.put(QName.create(namespace, revision, keysAndValues[index++]), keysAndValues[index++]);
235         }
236
237         return new NodeIdentifierWithPredicates(QName.create(namespace, revision, localName), predicate);
238     }
239
240     static NormalizedNode<?,?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
241         final String ietfInterfacesDate = "2013-07-04";
242         final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
243         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode =
244                 ImmutableMapEntryNodeBuilder.create();
245
246         final Map<String, Object> predicates = new HashMap<>();
247         predicates.put("name", "eth0");
248
249         mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
250                 predicates));
251         mapEntryNode
252                 .withChild(new ImmutableLeafNodeBuilder<String>()
253                         .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
254                         .build());
255         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
256                 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
257                 .withValue("ethernetCsmacd").build());
258         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
259                 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
260                 .withValue(Boolean.FALSE).build());
261         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
262                 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
263                 .withValue("some interface").build());
264
265         return mapEntryNode.build();
266     }
267 }