2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.sal.restconf.impl.test;
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;
16 import com.google.common.base.Preconditions;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import java.io.BufferedReader;
19 import java.io.ByteArrayOutputStream;
21 import java.io.FileNotFoundException;
22 import java.io.FileReader;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStreamWriter;
27 import java.net.URISyntaxException;
29 import java.text.ParseException;
30 import java.text.SimpleDateFormat;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38 import javax.ws.rs.WebApplicationException;
39 import javax.ws.rs.ext.MessageBodyReader;
40 import javax.ws.rs.ext.MessageBodyWriter;
41 import javax.xml.parsers.DocumentBuilder;
42 import javax.xml.parsers.DocumentBuilderFactory;
43 import javax.xml.parsers.ParserConfigurationException;
44 import javax.xml.transform.OutputKeys;
45 import javax.xml.transform.Transformer;
46 import javax.xml.transform.TransformerException;
47 import javax.xml.transform.TransformerFactory;
48 import javax.xml.transform.dom.DOMSource;
49 import javax.xml.transform.stream.StreamResult;
50 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
51 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
52 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
53 import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
54 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
55 import org.opendaylight.controller.sal.restconf.impl.RestconfError;
56 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
57 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
58 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
59 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
60 import org.opendaylight.yangtools.yang.common.QName;
61 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
62 import org.opendaylight.yangtools.yang.data.api.Node;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
68 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
69 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
70 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
71 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
72 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
73 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
74 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
75 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.Module;
79 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
80 import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
81 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import org.w3c.dom.Document;
85 import org.xml.sax.SAXException;
87 public final class TestUtils {
89 private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
91 private final static YangContextParser parser = new YangParserImpl();
93 private static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
94 final File testDir = new File(resourceDirectory);
95 final String[] fileList = testDir.list();
96 final List<File> testFiles = new ArrayList<File>();
97 if (fileList == null) {
98 throw new FileNotFoundException(resourceDirectory);
100 for (int i = 0; i < fileList.length; i++) {
101 String fileName = fileList[i];
102 if (new File(testDir, fileName).isDirectory() == false) {
103 testFiles.add(new File(testDir, fileName));
106 return parser.parseYangModels(testFiles);
109 public static Set<Module> loadModulesFrom(String yangPath) {
111 return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
112 } catch (FileNotFoundException e) {
113 LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
119 public static SchemaContext loadSchemaContext(Set<Module> modules) {
120 return parser.resolveSchemaContext(modules);
123 public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
124 return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
127 public static Module findModule(Set<Module> modules, String moduleName) {
128 for (Module module : modules) {
129 if (module.getName().equals(moduleName)) {
136 public static Document loadDocumentFrom(InputStream inputStream) {
138 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
139 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
140 return docBuilder.parse(inputStream);
141 } catch (SAXException | IOException | ParserConfigurationException e) {
142 LOG.error("Error during loading Document from XML", e);
147 public static String getDocumentInPrintableForm(Document doc) {
148 Preconditions.checkNotNull(doc);
150 ByteArrayOutputStream out = new ByteArrayOutputStream();
151 TransformerFactory tf = TransformerFactory.newInstance();
152 Transformer transformer = tf.newTransformer();
153 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
154 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
155 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
156 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
157 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
159 transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
160 byte[] charData = out.toByteArray();
161 return new String(charData, "UTF-8");
162 } catch (IOException | TransformerException e) {
163 String msg = "Error during transformation of Document into String";
172 * Fill missing data (namespaces) and build correct data type in {@code compositeNode} according to
173 * {@code dataSchemaNode}. The method {@link RestconfImpl#createConfigurationData createConfigurationData} is used
174 * because it contains calling of method {code normalizeNode}
176 public static void normalizeCompositeNode(Node<?> node, Set<Module> modules, String schemaNodePath) {
177 RestconfImpl restconf = RestconfImpl.getInstance();
178 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
180 prepareMocksForRestconf(modules, restconf);
181 restconf.updateConfigurationData(schemaNodePath, node);
185 * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
186 * module set has only one element then this element is returned.
189 public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
190 assertNotNull("Modules can't be null.", modules);
191 if (searchedModuleName != null) {
192 for (Module m : modules) {
193 if (m.getName().equals(searchedModuleName)) {
197 } else if (modules.size() == 1) {
198 return modules.iterator().next();
203 public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
204 assertNotNull("Module can't be null", module);
206 if (searchedDataSchemaName != null) {
207 for (DataSchemaNode dsn : module.getChildNodes()) {
208 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
212 } else if (module.getChildNodes().size() == 1) {
213 return module.getChildNodes().iterator().next();
218 public static QName buildQName(String name, String uri, String date, String prefix) {
220 URI u = new URI(uri);
223 dt = Date.valueOf(date);
225 return new QName(u, dt, prefix, name);
226 } catch (URISyntaxException e) {
231 public static QName buildQName(String name, String uri, String date) {
232 return buildQName(name, uri, date, null);
235 public static QName buildQName(String name) {
236 return buildQName(name, "", null);
239 private static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
240 wrappedNode.setNamespace(new URI(""));
241 if (wrappedNode instanceof CompositeNodeWrapper) {
242 for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
243 addDummyNamespaceToAllNodes(childNodeWrapper);
248 private static void prepareMocksForRestconf(Set<Module> modules, RestconfImpl restconf) {
249 ControllerContext controllerContext = ControllerContext.getInstance();
250 BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
252 controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
254 when(mockedBrokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(NormalizedNode.class)))
255 .thenReturn(mock(CheckedFuture.class));
257 restconf.setControllerContext(controllerContext);
258 restconf.setBroker(mockedBrokerFacade);
261 public static Node<?> readInputToCnSn(String path, boolean dummyNamespaces,
262 MessageBodyReader<Node<?>> reader) throws WebApplicationException {
264 InputStream inputStream = TestUtils.class.getResourceAsStream(path);
266 final Node<?> node = reader.readFrom(null, null, null, null, null, inputStream);
267 assertTrue(node instanceof CompositeNodeWrapper);
268 if (dummyNamespaces) {
270 TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) node);
271 return ((CompositeNodeWrapper) node).unwrap();
272 } catch (URISyntaxException e) {
273 LOG.error(e.getMessage());
274 assertTrue(e.getMessage(), false);
278 } catch (IOException e) {
279 LOG.error(e.getMessage());
280 assertTrue(e.getMessage(), false);
285 // public static Node<?> readInputToCnSnNew(String path, MessageBodyReader<Node<?>> reader) throws WebApplicationException {
286 // InputStream inputStream = TestUtils.class.getResourceAsStream(path);
288 // return reader.readFrom(null, null, null, null, null, inputStream);
289 // } catch (IOException e) {
290 // LOG.error(e.getMessage());
291 // assertTrue(e.getMessage(), false);
296 public static Node<?> readInputToCnSn(String path, MessageBodyReader<Node<?>> reader) {
297 return readInputToCnSn(path, false, reader);
300 public static String writeCompNodeWithSchemaContextToOutput(Node<?> node, Set<Module> modules,
301 DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
302 WebApplicationException {
304 assertNotNull(dataSchemaNode);
305 assertNotNull("Composite node can't be null", node);
306 ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
308 ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
310 assertTrue(node instanceof CompositeNode);
311 messageBodyWriter.writeTo(new StructuredData((CompositeNode)node, dataSchemaNode, null), null, null, null, null,
314 return byteArrayOS.toString();
317 public static String loadTextFile(String filePath) throws IOException {
318 FileReader fileReader = new FileReader(filePath);
319 BufferedReader bufReader = new BufferedReader(fileReader);
322 StringBuilder result = new StringBuilder();
323 while ((line = bufReader.readLine()) != null) {
327 return result.toString();
330 private static Pattern patternForStringsSeparatedByWhiteChars(String... substrings) {
331 StringBuilder pattern = new StringBuilder();
332 pattern.append(".*");
333 for (String substring : substrings) {
334 pattern.append(substring);
335 pattern.append("\\s*");
337 pattern.append(".*");
338 return Pattern.compile(pattern.toString(), Pattern.DOTALL);
341 public static boolean containsStringData(String jsonOutput, String... substrings) {
342 Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
343 Matcher matcher = pattern.matcher(jsonOutput);
344 return matcher.matches();
347 public static NormalizedNode compositeNodeToDatastoreNormalizedNode(final CompositeNode compositeNode,
348 final DataSchemaNode schema) {
349 List<Node<?>> lst = new ArrayList<Node<?>>();
350 lst.add(compositeNode);
351 if (schema instanceof ContainerSchemaNode) {
352 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
353 .parse(lst, (ContainerSchemaNode) schema);
354 } else if (schema instanceof ListSchemaNode) {
355 return CnSnToNormalizedNodeParserFactory.getInstance().getMapNodeParser()
356 .parse(lst, (ListSchemaNode) schema);
359 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
361 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
362 "It wasn't possible to translate specified data to datastore readable form."));
365 public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(String localName, String namespace,
366 String revision) throws ParseException {
367 return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName));
370 public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(String localName,
371 String namespace, String revision, Map<String, Object> keys) throws ParseException {
372 Map<QName, Object> predicate = new HashMap<>();
373 for (String key : keys.keySet()) {
374 predicate.put(QName.create(namespace, revision, key), keys.get(key));
377 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(
379 QName.create(namespace, revision, localName), predicate);
382 public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(String localName,
383 String namespace, String revision, String... keysAndValues) throws ParseException {
384 java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(revision);
385 if (keysAndValues.length % 2 != 0) {
386 new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)");
388 Map<QName, Object> predicate = new HashMap<>();
391 while (i < keysAndValues.length) {
392 predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]);
395 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(namespace, revision, localName),
399 public static CompositeNode prepareCompositeNodeWithIetfInterfacesInterfacesData() {
400 CompositeNodeBuilder<ImmutableCompositeNode> interfaceBuilder = ImmutableCompositeNode.builder();
401 interfaceBuilder.addLeaf(buildQName("name", "dummy", "2014-07-29"), "eth0");
402 interfaceBuilder.addLeaf(buildQName("type", "dummy", "2014-07-29"), "ethernetCsmacd");
403 interfaceBuilder.addLeaf(buildQName("enabled", "dummy", "2014-07-29"), "false");
404 interfaceBuilder.addLeaf(buildQName("description", "dummy", "2014-07-29"), "some interface");
405 return interfaceBuilder.toInstance();
408 static NormalizedNode prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
409 String ietfInterfacesDate = "2013-07-04";
410 CollectionNodeBuilder<MapEntryNode, MapNode> intface = ImmutableMapNodeBuilder.create();
411 String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
412 intface.withNodeIdentifier(getNodeIdentifier("interface", namespace, ietfInterfacesDate));
413 DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode = ImmutableMapEntryNodeBuilder.create();
415 Map<String, Object> predicates = new HashMap<>();
416 predicates.put("name", "eth0");
418 mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
421 .withChild(new ImmutableLeafNodeBuilder<String>()
422 .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
424 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
425 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
426 .withValue("ethernetCsmacd").build());
427 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
428 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
429 .withValue(Boolean.FALSE).build());
430 mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
431 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
432 .withValue("some interface").build());
434 intface.withChild(mapEntryNode.build());
436 return intface.build();