Merge "BUG 1082 Migrate sal-rest-connector to Async Data Broker API"
[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 import static org.junit.Assert.assertTrue;
12 import static org.mockito.Matchers.any;
13 import static org.mockito.Mockito.mock;
14 import static org.mockito.Mockito.when;
15
16 import com.google.common.base.Preconditions;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import java.io.BufferedReader;
19 import java.io.ByteArrayOutputStream;
20 import java.io.File;
21 import java.io.FileNotFoundException;
22 import java.io.FileReader;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStreamWriter;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.sql.Date;
29 import java.text.ParseException;
30 import java.text.SimpleDateFormat;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38 import javax.ws.rs.WebApplicationException;
39 import javax.ws.rs.ext.MessageBodyReader;
40 import javax.ws.rs.ext.MessageBodyWriter;
41 import javax.xml.parsers.DocumentBuilder;
42 import javax.xml.parsers.DocumentBuilderFactory;
43 import javax.xml.parsers.ParserConfigurationException;
44 import javax.xml.transform.OutputKeys;
45 import javax.xml.transform.Transformer;
46 import javax.xml.transform.TransformerException;
47 import javax.xml.transform.TransformerFactory;
48 import javax.xml.transform.dom.DOMSource;
49 import javax.xml.transform.stream.StreamResult;
50 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
51 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
52 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
53 import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
54 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
55 import org.opendaylight.controller.sal.restconf.impl.RestconfError;
56 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
57 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
58 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
59 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
60 import org.opendaylight.yangtools.yang.common.QName;
61 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
62 import org.opendaylight.yangtools.yang.data.api.Node;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
68 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
69 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
70 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
71 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
72 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
73 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
74 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
75 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.Module;
79 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
80 import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
81 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import org.w3c.dom.Document;
85 import org.xml.sax.SAXException;
86
87 public final class TestUtils {
88
89     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
90
91     private final static YangContextParser parser = new YangParserImpl();
92
93     private static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
94         final File testDir = new File(resourceDirectory);
95         final String[] fileList = testDir.list();
96         final List<File> testFiles = new ArrayList<File>();
97         if (fileList == null) {
98             throw new FileNotFoundException(resourceDirectory);
99         }
100         for (int i = 0; i < fileList.length; i++) {
101             String fileName = fileList[i];
102             if (new File(testDir, fileName).isDirectory() == false) {
103                 testFiles.add(new File(testDir, fileName));
104             }
105         }
106         return parser.parseYangModels(testFiles);
107     }
108
109     public static Set<Module> loadModulesFrom(String yangPath) {
110         try {
111             return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
112         } catch (FileNotFoundException e) {
113             LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
114         }
115
116         return null;
117     }
118
119     public static SchemaContext loadSchemaContext(Set<Module> modules) {
120         return parser.resolveSchemaContext(modules);
121     }
122
123     public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
124         return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
125     }
126
127     public static Module findModule(Set<Module> modules, String moduleName) {
128         for (Module module : modules) {
129             if (module.getName().equals(moduleName)) {
130                 return module;
131             }
132         }
133         return null;
134     }
135
136     public static Document loadDocumentFrom(InputStream inputStream) {
137         try {
138             DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
139             DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
140             return docBuilder.parse(inputStream);
141         } catch (SAXException | IOException | ParserConfigurationException e) {
142             LOG.error("Error during loading Document from XML", e);
143             return null;
144         }
145     }
146
147     public static String getDocumentInPrintableForm(Document doc) {
148         Preconditions.checkNotNull(doc);
149         try {
150             ByteArrayOutputStream out = new ByteArrayOutputStream();
151             TransformerFactory tf = TransformerFactory.newInstance();
152             Transformer transformer = tf.newTransformer();
153             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
154             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
155             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
156             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
157             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
158
159             transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
160             byte[] charData = out.toByteArray();
161             return new String(charData, "UTF-8");
162         } catch (IOException | TransformerException e) {
163             String msg = "Error during transformation of Document into String";
164             LOG.error(msg, e);
165             return msg;
166         }
167
168     }
169
170     /**
171      *
172      * Fill missing data (namespaces) and build correct data type in {@code compositeNode} according to
173      * {@code dataSchemaNode}. The method {@link RestconfImpl#createConfigurationData createConfigurationData} is used
174      * because it contains calling of method {code normalizeNode}
175      */
176     public static void normalizeCompositeNode(Node<?> node, Set<Module> modules, String schemaNodePath) {
177         RestconfImpl restconf = RestconfImpl.getInstance();
178         ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
179
180         prepareMocksForRestconf(modules, restconf);
181         restconf.updateConfigurationData(schemaNodePath, node);
182     }
183
184     /**
185      * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
186      * module set has only one element then this element is returned.
187      *
188      */
189     public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
190         assertNotNull("Modules can't be null.", modules);
191         if (searchedModuleName != null) {
192             for (Module m : modules) {
193                 if (m.getName().equals(searchedModuleName)) {
194                     return m;
195                 }
196             }
197         } else if (modules.size() == 1) {
198             return modules.iterator().next();
199         }
200         return null;
201     }
202
203     public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
204         assertNotNull("Module can't be null", module);
205
206         if (searchedDataSchemaName != null) {
207             for (DataSchemaNode dsn : module.getChildNodes()) {
208                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
209                     return dsn;
210                 }
211             }
212         } else if (module.getChildNodes().size() == 1) {
213             return module.getChildNodes().iterator().next();
214         }
215         return null;
216     }
217
218     public static QName buildQName(String name, String uri, String date, String prefix) {
219         try {
220             URI u = new URI(uri);
221             Date dt = null;
222             if (date != null) {
223                 dt = Date.valueOf(date);
224             }
225             return new QName(u, dt, prefix, name);
226         } catch (URISyntaxException e) {
227             return null;
228         }
229     }
230
231     public static QName buildQName(String name, String uri, String date) {
232         return buildQName(name, uri, date, null);
233     }
234
235     public static QName buildQName(String name) {
236         return buildQName(name, "", null);
237     }
238
239     private static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
240         wrappedNode.setNamespace(new URI(""));
241         if (wrappedNode instanceof CompositeNodeWrapper) {
242             for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
243                 addDummyNamespaceToAllNodes(childNodeWrapper);
244             }
245         }
246     }
247
248     private static void prepareMocksForRestconf(Set<Module> modules, RestconfImpl restconf) {
249         ControllerContext controllerContext = ControllerContext.getInstance();
250         BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
251
252         controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
253
254         when(mockedBrokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(NormalizedNode.class)))
255                 .thenReturn(mock(CheckedFuture.class));
256
257         restconf.setControllerContext(controllerContext);
258         restconf.setBroker(mockedBrokerFacade);
259     }
260
261     public static Node<?> readInputToCnSn(String path, boolean dummyNamespaces,
262             MessageBodyReader<Node<?>> reader) throws WebApplicationException {
263
264         InputStream inputStream = TestUtils.class.getResourceAsStream(path);
265         try {
266             final Node<?> node = reader.readFrom(null, null, null, null, null, inputStream);
267             assertTrue(node instanceof CompositeNodeWrapper);
268             if (dummyNamespaces) {
269                 try {
270                     TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) node);
271                     return ((CompositeNodeWrapper) node).unwrap();
272                 } catch (URISyntaxException e) {
273                     LOG.error(e.getMessage());
274                     assertTrue(e.getMessage(), false);
275                 }
276             }
277             return node;
278         } catch (IOException e) {
279             LOG.error(e.getMessage());
280             assertTrue(e.getMessage(), false);
281         }
282         return null;
283     }
284
285 //    public static Node<?> readInputToCnSnNew(String path, MessageBodyReader<Node<?>> reader) throws WebApplicationException {
286 //        InputStream inputStream = TestUtils.class.getResourceAsStream(path);
287 //        try {
288 //            return reader.readFrom(null, null, null, null, null, inputStream);
289 //        } catch (IOException e) {
290 //            LOG.error(e.getMessage());
291 //            assertTrue(e.getMessage(), false);
292 //        }
293 //        return null;
294 //    }
295
296     public static Node<?> readInputToCnSn(String path, MessageBodyReader<Node<?>> reader) {
297         return readInputToCnSn(path, false, reader);
298     }
299
300     public static String writeCompNodeWithSchemaContextToOutput(Node<?> node, Set<Module> modules,
301             DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
302             WebApplicationException {
303
304         assertNotNull(dataSchemaNode);
305         assertNotNull("Composite node can't be null", node);
306         ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
307
308         ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
309
310         assertTrue(node instanceof CompositeNode);
311         messageBodyWriter.writeTo(new StructuredData((CompositeNode)node, dataSchemaNode, null), null, null, null, null,
312                 null, byteArrayOS);
313
314         return byteArrayOS.toString();
315     }
316
317     public static String loadTextFile(String filePath) throws IOException {
318         FileReader fileReader = new FileReader(filePath);
319         BufferedReader bufReader = new BufferedReader(fileReader);
320
321         String line = null;
322         StringBuilder result = new StringBuilder();
323         while ((line = bufReader.readLine()) != null) {
324             result.append(line);
325         }
326         bufReader.close();
327         return result.toString();
328     }
329
330     private static Pattern patternForStringsSeparatedByWhiteChars(String... substrings) {
331         StringBuilder pattern = new StringBuilder();
332         pattern.append(".*");
333         for (String substring : substrings) {
334             pattern.append(substring);
335             pattern.append("\\s*");
336         }
337         pattern.append(".*");
338         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
339     }
340
341     public static boolean containsStringData(String jsonOutput, String... substrings) {
342         Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
343         Matcher matcher = pattern.matcher(jsonOutput);
344         return matcher.matches();
345     }
346
347     public static NormalizedNode compositeNodeToDatastoreNormalizedNode(final CompositeNode compositeNode,
348             final DataSchemaNode schema) {
349         List<Node<?>> lst = new ArrayList<Node<?>>();
350         lst.add(compositeNode);
351         if (schema instanceof ContainerSchemaNode) {
352             return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
353                     .parse(lst, (ContainerSchemaNode) schema);
354         } else if (schema instanceof ListSchemaNode) {
355             return CnSnToNormalizedNodeParserFactory.getInstance().getMapNodeParser()
356                     .parse(lst, (ListSchemaNode) schema);
357         }
358
359         LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
360
361         throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
362                 "It wasn't possible to translate specified data to datastore readable form."));
363     }
364
365     public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(String localName, String namespace,
366             String revision) throws ParseException {
367         return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName));
368     }
369
370     public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(String localName,
371             String namespace, String revision, Map<String, Object> keys) throws ParseException {
372         Map<QName, Object> predicate = new HashMap<>();
373         for (String key : keys.keySet()) {
374             predicate.put(QName.create(namespace, revision, key), keys.get(key));
375         }
376
377         return new YangInstanceIdentifier.NodeIdentifierWithPredicates(
378
379         QName.create(namespace, revision, localName), predicate);
380     }
381
382     public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(String localName,
383             String namespace, String revision, String... keysAndValues) throws ParseException {
384         java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(revision);
385         if (keysAndValues.length % 2 != 0) {
386             new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)");
387         }
388         Map<QName, Object> predicate = new HashMap<>();
389
390         int i = 0;
391         while (i < keysAndValues.length) {
392             predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]);
393         }
394
395         return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(namespace, revision, localName),
396                 predicate);
397     }
398
399     public static CompositeNode prepareCompositeNodeWithIetfInterfacesInterfacesData() {
400         CompositeNodeBuilder<ImmutableCompositeNode> interfaceBuilder = ImmutableCompositeNode.builder();
401         interfaceBuilder.addLeaf(buildQName("name", "dummy", "2014-07-29"), "eth0");
402         interfaceBuilder.addLeaf(buildQName("type", "dummy", "2014-07-29"), "ethernetCsmacd");
403         interfaceBuilder.addLeaf(buildQName("enabled", "dummy", "2014-07-29"), "false");
404         interfaceBuilder.addLeaf(buildQName("description", "dummy", "2014-07-29"), "some interface");
405         return interfaceBuilder.toInstance();
406     }
407
408     static NormalizedNode prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
409         String ietfInterfacesDate = "2013-07-04";
410         CollectionNodeBuilder<MapEntryNode, MapNode> intface = ImmutableMapNodeBuilder.create();
411         String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
412         intface.withNodeIdentifier(getNodeIdentifier("interface", namespace, ietfInterfacesDate));
413         DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode = ImmutableMapEntryNodeBuilder.create();
414
415         Map<String, Object> predicates = new HashMap<>();
416         predicates.put("name", "eth0");
417
418         mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
419                 predicates));
420         mapEntryNode
421                 .withChild(new ImmutableLeafNodeBuilder<String>()
422                         .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
423                         .build());
424         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
425                 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
426                 .withValue("ethernetCsmacd").build());
427         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
428                 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
429                 .withValue(Boolean.FALSE).build());
430         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
431                 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
432                 .withValue("some interface").build());
433
434         intface.withChild(mapEntryNode.build());
435
436         return intface.build();
437     }
438 }