Bug 2358: Fixed warnings in Restconf
[controller.git] / opendaylight / md-sal / 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
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.sql.Date;
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.parsers.DocumentBuilder;
33 import javax.xml.parsers.DocumentBuilderFactory;
34 import javax.xml.parsers.ParserConfigurationException;
35 import javax.xml.transform.OutputKeys;
36 import javax.xml.transform.Transformer;
37 import javax.xml.transform.TransformerException;
38 import javax.xml.transform.TransformerFactory;
39 import javax.xml.transform.dom.DOMSource;
40 import javax.xml.transform.stream.StreamResult;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.model.parser.api.YangContextParser;
52 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
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 final static YangContextParser PARSER = new YangParserImpl();
63
64     private static Set<Module> loadModules(final String resourceDirectory) throws FileNotFoundException {
65         final File testDir = new File(resourceDirectory);
66         final String[] fileList = testDir.list();
67         final List<File> testFiles = new ArrayList<File>();
68         if (fileList == null) {
69             throw new FileNotFoundException(resourceDirectory);
70         }
71         for (int i = 0; i < fileList.length; i++) {
72             final String fileName = fileList[i];
73             if (new File(testDir, fileName).isDirectory() == false) {
74                 testFiles.add(new File(testDir, fileName));
75             }
76         }
77         return PARSER.parseYangModels(testFiles);
78     }
79
80     public static Set<Module> loadModulesFrom(final String yangPath) {
81         try {
82             return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
83         } catch (final FileNotFoundException e) {
84             LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
85         }
86
87         return null;
88     }
89
90     public static SchemaContext loadSchemaContext(final Set<Module> modules) {
91         return PARSER.resolveSchemaContext(modules);
92     }
93
94     public static SchemaContext loadSchemaContext(final String resourceDirectory) throws FileNotFoundException {
95         return PARSER.resolveSchemaContext(loadModulesFrom(resourceDirectory));
96     }
97
98     public static Module findModule(final Set<Module> modules, final String moduleName) {
99         for (final Module module : modules) {
100             if (module.getName().equals(moduleName)) {
101                 return module;
102             }
103         }
104         return null;
105     }
106
107     public static Document loadDocumentFrom(final InputStream inputStream) {
108         try {
109             final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
110             final DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
111             return docBuilder.parse(inputStream);
112         } catch (SAXException | IOException | ParserConfigurationException e) {
113             LOG.error("Error during loading Document from XML", e);
114             return null;
115         }
116     }
117
118     public static String getDocumentInPrintableForm(final Document doc) {
119         Preconditions.checkNotNull(doc);
120         try {
121             final ByteArrayOutputStream out = new ByteArrayOutputStream();
122             final TransformerFactory tf = TransformerFactory.newInstance();
123             final Transformer transformer = tf.newTransformer();
124             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
125             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
126             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
127             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
128             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
129
130             transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
131             final byte[] charData = out.toByteArray();
132             return new String(charData, "UTF-8");
133         } catch (IOException | TransformerException e) {
134             final String msg = "Error during transformation of Document into String";
135             LOG.error(msg, e);
136             return msg;
137         }
138
139     }
140
141     /**
142      * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
143      * module set has only one element then this element is returned.
144      *
145      */
146     public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
147         assertNotNull("Modules can't be null.", modules);
148         if (searchedModuleName != null) {
149             for (final Module m : modules) {
150                 if (m.getName().equals(searchedModuleName)) {
151                     return m;
152                 }
153             }
154         } else if (modules.size() == 1) {
155             return modules.iterator().next();
156         }
157         return null;
158     }
159
160     public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
161         assertNotNull("Module can't be null", module);
162
163         if (searchedDataSchemaName != null) {
164             for (final DataSchemaNode dsn : module.getChildNodes()) {
165                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
166                     return dsn;
167                 }
168             }
169         } else if (module.getChildNodes().size() == 1) {
170             return module.getChildNodes().iterator().next();
171         }
172         return null;
173     }
174
175     public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
176         try {
177             final URI u = new URI(uri);
178             Date dt = null;
179             if (date != null) {
180                 dt = Date.valueOf(date);
181             }
182             return QName.create(u, dt, name);
183         } catch (final URISyntaxException e) {
184             return null;
185         }
186     }
187
188     public static QName buildQName(final String name, final String uri, final String date) {
189         return buildQName(name, uri, date, null);
190     }
191
192     public static QName buildQName(final String name) {
193         return buildQName(name, "", null);
194     }
195
196     public static String loadTextFile(final String filePath) throws IOException {
197         final FileReader fileReader = new FileReader(filePath);
198         final BufferedReader bufReader = new BufferedReader(fileReader);
199
200         String line = null;
201         final StringBuilder result = new StringBuilder();
202         while ((line = bufReader.readLine()) != null) {
203             result.append(line);
204         }
205         bufReader.close();
206         return result.toString();
207     }
208
209     private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
210         final StringBuilder pattern = new StringBuilder();
211         pattern.append(".*");
212         for (final String substring : substrings) {
213             pattern.append(substring);
214             pattern.append("\\s*");
215         }
216         pattern.append(".*");
217         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
218     }
219
220     public static boolean containsStringData(final String jsonOutput, final String... substrings) {
221         final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
222         final Matcher matcher = pattern.matcher(jsonOutput);
223         return matcher.matches();
224     }
225
226     public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
227             final String revision) throws ParseException {
228         return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName));
229     }
230
231     public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
232             final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
233         final Map<QName, Object> predicate = new HashMap<>();
234         for (final String key : keys.keySet()) {
235             predicate.put(QName.create(namespace, revision, key), keys.get(key));
236         }
237
238         return new YangInstanceIdentifier.NodeIdentifierWithPredicates(
239
240         QName.create(namespace, revision, localName), predicate);
241     }
242
243     public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
244             final String namespace, final String revision, final String... keysAndValues) throws ParseException {
245         if (keysAndValues.length % 2 != 0) {
246             new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)");
247         }
248         final Map<QName, Object> predicate = new HashMap<>();
249
250         int i = 0;
251         while (i < keysAndValues.length) {
252             predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]);
253         }
254
255         return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(namespace, revision, localName),
256                 predicate);
257     }
258
259     static NormalizedNode<?,?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
260         final String ietfInterfacesDate = "2013-07-04";
261         final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
262         final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode = ImmutableMapEntryNodeBuilder.create();
263
264         final Map<String, Object> predicates = new HashMap<>();
265         predicates.put("name", "eth0");
266
267         mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
268                 predicates));
269         mapEntryNode
270                 .withChild(new ImmutableLeafNodeBuilder<String>()
271                         .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
272                         .build());
273         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
274                 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
275                 .withValue("ethernetCsmacd").build());
276         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
277                 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
278                 .withValue(Boolean.FALSE).build());
279         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
280                 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
281                 .withValue("some interface").build());
282
283         return mapEntryNode.build();
284     }
285 }