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