Fix XML parser condition in XmlPatchBodyReader
[netconf.git] / restconf / restconf-nb / src / test / java / org / opendaylight / restconf / nb / rfc8040 / 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.restconf.nb.rfc8040;
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.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
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.impl.schema.Builders;
45 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
48 import org.opendaylight.yangtools.yang.model.api.Module;
49 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.w3c.dom.Document;
53 import org.xml.sax.SAXException;
54
55 public final class TestUtils {
56
57     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
58
59     private TestUtils() {
60
61     }
62
63     public static EffectiveModelContext loadSchemaContext(final String... yangPath)
64             throws FileNotFoundException {
65         final List<File> files = new ArrayList<>();
66         for (final String path : yangPath) {
67             final String pathToFile = TestUtils.class.getResource(path).getPath();
68             final File testDir = new File(pathToFile);
69             final String[] fileList = testDir.list();
70             if (fileList == null) {
71                 throw new FileNotFoundException(pathToFile);
72             }
73
74             for (final String fileName : fileList) {
75                 final File file = new File(testDir, fileName);
76                 if (file.isDirectory() == false) {
77                     files.add(file);
78                 }
79             }
80         }
81
82         return YangParserTestUtils.parseYangFiles(files);
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             return UntrustedXML.newDocumentBuilder().parse(inputStream);
97         } catch (SAXException | IOException e) {
98             LOG.error("Error during loading Document from XML", e);
99             return null;
100         }
101     }
102
103     public static String getDocumentInPrintableForm(final Document 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(requireNonNull(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         return QName.create(XMLNamespace.of(uri), Revision.ofNullable(date), name);
162     }
163
164     public static QName buildQName(final String name, final String uri, final String date) {
165         return buildQName(name, uri, date, null);
166     }
167
168     public static QName buildQName(final String name) {
169         return buildQName(name, "", null);
170     }
171
172     public static String loadTextFile(final String filePath) throws IOException {
173         final FileReader fileReader = new FileReader(filePath, StandardCharsets.UTF_8);
174         final BufferedReader bufReader = new BufferedReader(fileReader);
175
176         String line = null;
177         final StringBuilder result = new StringBuilder();
178         while ((line = bufReader.readLine()) != null) {
179             result.append(line);
180         }
181         bufReader.close();
182         return result.toString();
183     }
184
185     private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
186         final StringBuilder pattern = new StringBuilder();
187         pattern.append(".*");
188         for (final String substring : substrings) {
189             pattern.append(substring);
190             pattern.append("\\s*");
191         }
192         pattern.append(".*");
193         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
194     }
195
196     public static boolean containsStringData(final String jsonOutput, final String... substrings) {
197         final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
198         final Matcher matcher = pattern.matcher(jsonOutput);
199         return matcher.matches();
200     }
201
202     public static NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
203             final String revision) throws ParseException {
204         return new NodeIdentifier(QName.create(namespace, revision, localName));
205     }
206
207     public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
208             final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
209         final Map<QName, Object> predicate = new HashMap<>();
210         for (final String key : keys.keySet()) {
211             predicate.put(QName.create(namespace, revision, key), keys.get(key));
212         }
213
214         return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
215     }
216
217     public static NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
218             final String namespace, final String revision, final String... keysAndValues) throws ParseException {
219         checkArgument(keysAndValues.length % 2 == 0, "number of keys argument have to be divisible by 2 (map)");
220         final Map<QName, Object> predicate = new HashMap<>();
221
222         int index = 0;
223         while (index < keysAndValues.length) {
224             predicate.put(QName.create(namespace, revision, keysAndValues[index++]), keysAndValues[index++]);
225         }
226
227         return NodeIdentifierWithPredicates.of(QName.create(namespace, revision, localName), predicate);
228     }
229
230     public static MapEntryNode prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
231         final String ietfInterfacesDate = "2013-07-04";
232         final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
233
234         return Builders.mapEntryBuilder()
235             .withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
236                 Map.of("name", "eth0")))
237             .withChild(ImmutableNodes.leafNode(getNodeIdentifier("name", namespace, ietfInterfacesDate), "eth0"))
238             .withChild(ImmutableNodes.leafNode(getNodeIdentifier("type", namespace, ietfInterfacesDate),
239                 "ethernetCsmacd"))
240             .withChild(ImmutableNodes.leafNode(getNodeIdentifier("enabled", namespace, ietfInterfacesDate),
241                 Boolean.FALSE))
242             .withChild(ImmutableNodes.leafNode(getNodeIdentifier("description", namespace, ietfInterfacesDate),
243                 "some interface"))
244             .build();
245     }
246 }