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