Merge "Removed `which` dependency, now using proper shell builtin."
[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 java.io.BufferedReader;
17 import java.io.ByteArrayOutputStream;
18 import java.io.File;
19 import java.io.FileNotFoundException;
20 import java.io.FileReader;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStreamWriter;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.sql.Date;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Set;
30
31 import javax.ws.rs.WebApplicationException;
32 import javax.ws.rs.ext.MessageBodyReader;
33 import javax.ws.rs.ext.MessageBodyWriter;
34 import javax.xml.parsers.DocumentBuilder;
35 import javax.xml.parsers.DocumentBuilderFactory;
36 import javax.xml.parsers.ParserConfigurationException;
37 import javax.xml.transform.OutputKeys;
38 import javax.xml.transform.Transformer;
39 import javax.xml.transform.TransformerException;
40 import javax.xml.transform.TransformerFactory;
41 import javax.xml.transform.dom.DOMSource;
42 import javax.xml.transform.stream.StreamResult;
43
44 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
45 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
46 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
47 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
48 import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
49 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
50 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
53 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
54 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
58 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.w3c.dom.Document;
62 import org.xml.sax.SAXException;
63
64 import com.google.common.base.Preconditions;
65
66 public final class TestUtils {
67
68     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
69
70     private final static YangModelParser parser = new YangParserImpl();
71
72     private static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
73         final File testDir = new File(resourceDirectory);
74         final String[] fileList = testDir.list();
75         final List<File> testFiles = new ArrayList<File>();
76         if (fileList == null) {
77             throw new FileNotFoundException(resourceDirectory);
78         }
79         for (int i = 0; i < fileList.length; i++) {
80             String fileName = fileList[i];
81             if (new File(testDir, fileName).isDirectory() == false) {
82                 testFiles.add(new File(testDir, fileName));
83             }
84         }
85         return parser.parseYangModels(testFiles);
86     }
87
88     public static Set<Module> loadModulesFrom(String yangPath) {
89         try {
90             return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
91         } catch (FileNotFoundException e) {
92             LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
93         }
94
95         return null;
96     }
97
98     public static SchemaContext loadSchemaContext(Set<Module> modules) {
99         return parser.resolveSchemaContext(modules);
100     }
101
102     public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
103         return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
104     }
105
106     public static Module findModule(Set<Module> modules, String moduleName) {
107         for (Module module : modules) {
108             if (module.getName().equals(moduleName)) {
109                 return module;
110             }
111         }
112         return null;
113     }
114
115     public static Document loadDocumentFrom(InputStream inputStream) {
116         try {
117             DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
118             DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
119             return docBuilder.parse(inputStream);
120         } catch (SAXException | IOException | ParserConfigurationException e) {
121             LOG.error("Error during loading Document from XML", e);
122             return null;
123         }
124     }
125
126     public static String getDocumentInPrintableForm(Document doc) {
127         Preconditions.checkNotNull(doc);
128         try {
129             ByteArrayOutputStream out = new ByteArrayOutputStream();
130             TransformerFactory tf = TransformerFactory.newInstance();
131             Transformer transformer = tf.newTransformer();
132             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
133             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
134             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
135             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
136             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
137
138             transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
139             byte[] charData = out.toByteArray();
140             return new String(charData, "UTF-8");
141         } catch (IOException | TransformerException e) {
142             String msg = "Error during transformation of Document into String";
143             LOG.error(msg, e);
144             return msg;
145         }
146
147     }
148
149     /**
150      *
151      * Fill missing data (namespaces) and build correct data type in
152      * {@code compositeNode} according to {@code dataSchemaNode}. The method
153      * {@link RestconfImpl#createConfigurationData createConfigurationData} is
154      * used because it contains calling of method {code normalizeNode}
155      */
156     public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
157         RestconfImpl restconf = RestconfImpl.getInstance();
158         ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
159
160         prepareMocksForRestconf(modules, restconf);
161         restconf.updateConfigurationData(schemaNodePath, compositeNode);
162     }
163
164     /**
165      * Searches module with name {@code searchedModuleName} in {@code modules}.
166      * If module name isn't specified and module set has only one element then
167      * this element is returned.
168      *
169      */
170     public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
171         assertNotNull("Modules can't be null.", modules);
172         if (searchedModuleName != null) {
173             for (Module m : modules) {
174                 if (m.getName().equals(searchedModuleName)) {
175                     return m;
176                 }
177             }
178         } else if (modules.size() == 1) {
179             return modules.iterator().next();
180         }
181         return null;
182     }
183
184     public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
185         assertNotNull("Module can't be null", module);
186
187         if (searchedDataSchemaName != null) {
188             for (DataSchemaNode dsn : module.getChildNodes()) {
189                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
190                     return dsn;
191                 }
192             }
193         } else if (module.getChildNodes().size() == 1) {
194             return module.getChildNodes().iterator().next();
195         }
196         return null;
197     }
198
199     public static QName buildQName(String name, String uri, String date, String prefix) {
200         try {
201             URI u = new URI(uri);
202             Date dt = null;
203             if (date != null) {
204                 dt = Date.valueOf(date);
205             }
206             return new QName(u, dt, prefix, name);
207         } catch (URISyntaxException e) {
208             return null;
209         }
210     }
211
212     public static QName buildQName(String name, String uri, String date) {
213         return buildQName(name, uri, date, null);
214     }
215
216     public static QName buildQName(String name) {
217         return buildQName(name, "", null);
218     }
219
220     private static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
221         wrappedNode.setNamespace(new URI(""));
222         if (wrappedNode instanceof CompositeNodeWrapper) {
223             for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
224                 addDummyNamespaceToAllNodes(childNodeWrapper);
225             }
226         }
227     }
228
229     private static void prepareMocksForRestconf(Set<Module> modules, RestconfImpl restconf) {
230         ControllerContext controllerContext = ControllerContext.getInstance();
231         BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
232
233         controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
234
235         when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
236                 .thenReturn(
237                         new DummyFuture.Builder().rpcResult(
238                                 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
239                                         .build()).build());
240
241         restconf.setControllerContext(controllerContext);
242         restconf.setBroker(mockedBrokerFacade);
243     }
244
245     public static CompositeNode readInputToCnSn(String path, boolean dummyNamespaces,
246             MessageBodyReader<CompositeNode> reader) throws WebApplicationException {
247
248         InputStream inputStream = TestUtils.class.getResourceAsStream(path);
249         try {
250             CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, inputStream);
251             assertTrue(compositeNode instanceof CompositeNodeWrapper);
252             if (dummyNamespaces) {
253                 try {
254                     TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
255                     return ((CompositeNodeWrapper) compositeNode).unwrap();
256                 } catch (URISyntaxException e) {
257                     LOG.error(e.getMessage());
258                     assertTrue(e.getMessage(), false);
259                 }
260             }
261             return compositeNode;
262         } catch (IOException e) {
263             LOG.error(e.getMessage());
264             assertTrue(e.getMessage(), false);
265         }
266         return null;
267     }
268
269     public static CompositeNode readInputToCnSn(String path, MessageBodyReader<CompositeNode> reader) {
270         return readInputToCnSn(path, false, reader);
271     }
272
273     public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set<Module> modules,
274             DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
275             WebApplicationException {
276
277         assertNotNull(dataSchemaNode);
278         assertNotNull("Composite node can't be null", compositeNode);
279         ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
280
281         ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
282
283         messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null, null,
284                 byteArrayOS);
285
286         return byteArrayOS.toString();
287     }
288
289     public static String loadTextFile(String filePath) throws IOException {
290         FileReader fileReader = new FileReader(filePath);
291         BufferedReader bufReader = new BufferedReader(fileReader);
292
293         String line = null;
294         StringBuilder result = new StringBuilder();
295         while ((line = bufReader.readLine()) != null) {
296             result.append(line);
297         }
298         bufReader.close();
299         return result.toString();
300
301     }
302 }