Merge "Fixed for bug 1168 : Issue while update subnet"
[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.YangInstanceIdentifier;
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 {@code compositeNode} according to
151      * {@code dataSchemaNode}. The method {@link RestconfImpl#createConfigurationData createConfigurationData} is used
152      * because it contains calling of method {code normalizeNode}
153      */
154     public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
155         RestconfImpl restconf = RestconfImpl.getInstance();
156         ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
157
158         prepareMocksForRestconf(modules, restconf);
159         restconf.updateConfigurationData(schemaNodePath, compositeNode);
160     }
161
162     /**
163      * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
164      * module set has only one element then this element is returned.
165      *
166      */
167     public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
168         assertNotNull("Modules can't be null.", modules);
169         if (searchedModuleName != null) {
170             for (Module m : modules) {
171                 if (m.getName().equals(searchedModuleName)) {
172                     return m;
173                 }
174             }
175         } else if (modules.size() == 1) {
176             return modules.iterator().next();
177         }
178         return null;
179     }
180
181     public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
182         assertNotNull("Module can't be null", module);
183
184         if (searchedDataSchemaName != null) {
185             for (DataSchemaNode dsn : module.getChildNodes()) {
186                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
187                     return dsn;
188                 }
189             }
190         } else if (module.getChildNodes().size() == 1) {
191             return module.getChildNodes().iterator().next();
192         }
193         return null;
194     }
195
196     public static QName buildQName(String name, String uri, String date, String prefix) {
197         try {
198             URI u = new URI(uri);
199             Date dt = null;
200             if (date != null) {
201                 dt = Date.valueOf(date);
202             }
203             return new QName(u, dt, prefix, name);
204         } catch (URISyntaxException e) {
205             return null;
206         }
207     }
208
209     public static QName buildQName(String name, String uri, String date) {
210         return buildQName(name, uri, date, null);
211     }
212
213     public static QName buildQName(String name) {
214         return buildQName(name, "", null);
215     }
216
217     private static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
218         wrappedNode.setNamespace(new URI(""));
219         if (wrappedNode instanceof CompositeNodeWrapper) {
220             for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
221                 addDummyNamespaceToAllNodes(childNodeWrapper);
222             }
223         }
224     }
225
226     private static void prepareMocksForRestconf(Set<Module> modules, RestconfImpl restconf) {
227         ControllerContext controllerContext = ControllerContext.getInstance();
228         BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
229
230         controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
231
232         when(mockedBrokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(CompositeNode.class)))
233                 .thenReturn(
234                         new DummyFuture.Builder().rpcResult(
235                                 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
236                                         .build()).build());
237
238         restconf.setControllerContext(controllerContext);
239         restconf.setBroker(mockedBrokerFacade);
240     }
241
242     public static CompositeNode readInputToCnSn(String path, boolean dummyNamespaces,
243             MessageBodyReader<CompositeNode> reader) throws WebApplicationException {
244
245         InputStream inputStream = TestUtils.class.getResourceAsStream(path);
246         try {
247             CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, inputStream);
248             assertTrue(compositeNode instanceof CompositeNodeWrapper);
249             if (dummyNamespaces) {
250                 try {
251                     TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
252                     return ((CompositeNodeWrapper) compositeNode).unwrap();
253                 } catch (URISyntaxException e) {
254                     LOG.error(e.getMessage());
255                     assertTrue(e.getMessage(), false);
256                 }
257             }
258             return compositeNode;
259         } catch (IOException e) {
260             LOG.error(e.getMessage());
261             assertTrue(e.getMessage(), false);
262         }
263         return null;
264     }
265
266     public static CompositeNode readInputToCnSn(String path, MessageBodyReader<CompositeNode> reader) {
267         return readInputToCnSn(path, false, reader);
268     }
269
270     public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set<Module> modules,
271             DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
272             WebApplicationException {
273
274         assertNotNull(dataSchemaNode);
275         assertNotNull("Composite node can't be null", compositeNode);
276         ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
277
278         ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
279
280         messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null,
281                 null, byteArrayOS);
282
283         return byteArrayOS.toString();
284     }
285
286     public static String loadTextFile(String filePath) throws IOException {
287         FileReader fileReader = new FileReader(filePath);
288         BufferedReader bufReader = new BufferedReader(fileReader);
289
290         String line = null;
291         StringBuilder result = new StringBuilder();
292         while ((line = bufReader.readLine()) != null) {
293             result.append(line);
294         }
295         bufReader.close();
296         return result.toString();
297     }
298
299     private static Pattern patternForStringsSeparatedByWhiteChars(String... substrings) {
300         StringBuilder pattern = new StringBuilder();
301         pattern.append(".*");
302         for (String substring : substrings) {
303             pattern.append(substring);
304             pattern.append("\\s*");
305         }
306         pattern.append(".*");
307         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
308     }
309
310     public static boolean containsStringData(String jsonOutput, String... substrings) {
311         Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
312         Matcher matcher = pattern.matcher(jsonOutput);
313         return matcher.matches();
314     }
315 }