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