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