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.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertNull;
14 import static org.junit.Assert.assertTrue;
15 import static org.junit.Assert.fail;
16 import static org.mockito.Matchers.any;
17 import static org.mockito.Matchers.eq;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.when;
21 import com.google.common.base.Optional;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Maps;
24 import java.io.FileNotFoundException;
25 import java.io.UnsupportedEncodingException;
27 import java.net.URISyntaxException;
28 import java.text.ParseException;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.Date;
32 import java.util.HashSet;
33 import java.util.List;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38 import javax.ws.rs.core.Application;
39 import javax.ws.rs.core.MediaType;
40 import javax.ws.rs.core.MultivaluedHashMap;
41 import javax.ws.rs.core.MultivaluedMap;
42 import javax.ws.rs.core.Response;
43 import javax.ws.rs.core.UriInfo;
44 import org.glassfish.jersey.server.ResourceConfig;
45 import org.glassfish.jersey.test.JerseyTest;
46 import org.junit.BeforeClass;
47 import org.junit.Test;
48 import org.mockito.invocation.InvocationOnMock;
49 import org.mockito.stubbing.Answer;
50 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
51 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
52 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
53 import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper;
54 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
55 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
56 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
57 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
58 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
59 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
60 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
61 import org.opendaylight.yangtools.yang.common.QName;
62 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
65 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
70 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
71 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
72 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
73 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
74 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
75 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
76 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
77 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.Module;
79 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
80 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
81 import org.w3c.dom.Document;
82 import org.w3c.dom.Element;
83 import org.w3c.dom.NodeList;
85 public class RestGetOperationTest extends JerseyTest {
87 static class NodeData {
89 Object data; // List for a CompositeNode, value Object for a SimpleNode
91 NodeData(final Object key, final Object data) {
97 private static BrokerFacade brokerFacade;
98 private static RestconfImpl restconfImpl;
99 private static SchemaContext schemaContextYangsIetf;
100 private static SchemaContext schemaContextTestModule;
101 private static NormalizedNode answerFromGet;
103 private static SchemaContext schemaContextModules;
104 private static SchemaContext schemaContextBehindMountPoint;
106 private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf";
109 public static void init() throws FileNotFoundException, ParseException {
110 schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
111 schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
112 ControllerContext controllerContext = ControllerContext.getInstance();
113 controllerContext.setSchemas(schemaContextYangsIetf);
114 brokerFacade = mock(BrokerFacade.class);
115 restconfImpl = RestconfImpl.getInstance();
116 restconfImpl.setBroker(brokerFacade);
117 restconfImpl.setControllerContext(controllerContext);
118 answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
120 schemaContextModules = TestUtils.loadSchemaContext("/modules");
121 schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
125 protected Application configure() {
126 /* enable/disable Jersey logs to console */
127 // enable(TestProperties.LOG_TRAFFIC);
128 // enable(TestProperties.DUMP_ENTITY);
129 // enable(TestProperties.RECORD_LOG_LEVEL);
130 // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
131 ResourceConfig resourceConfig = new ResourceConfig();
132 resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
133 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
134 JsonToCompositeNodeProvider.INSTANCE);
135 resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
136 return resourceConfig;
140 * Tests of status codes for "/operational/{identifier}".
143 public void getOperationalStatusCodes() throws UnsupportedEncodingException {
144 mockReadOperationalDataMethod();
145 String uri = "/operational/ietf-interfaces:interfaces/interface/eth0";
146 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
148 uri = "/operational/wrong-module:interfaces/interface/eth0";
149 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
153 * Tests of status codes for "/config/{identifier}".
156 public void getConfigStatusCodes() throws UnsupportedEncodingException {
157 mockReadConfigurationDataMethod();
158 String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
159 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
161 uri = "/config/wrong-module:interfaces/interface/eth0";
162 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
166 * MountPoint test. URI represents mount point.
169 public void getDataWithUrlMountPoint() throws UnsupportedEncodingException, URISyntaxException, ParseException {
170 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
171 prepareCnDataForMountPointTest(false));
172 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
173 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
174 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
175 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
177 ControllerContext.getInstance().setMountService(mockMountService);
179 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/cont1";
180 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
182 uri = "/config/ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
183 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
187 * MountPoint test. URI represents mount point.
189 * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
190 * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
191 * InstanceIdentifier parameter in method
192 * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, YangInstanceIdentifier)} which is called in
193 * method {@link RestconfImpl#readConfigurationData}
195 * @throws ParseException
198 public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException,
200 YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
201 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier))).thenReturn(
202 prepareCnDataForSlashesBehindMountPointTest());
203 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
204 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
205 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
206 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
208 ControllerContext.getInstance().setMountService(mockMountService);
210 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
211 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
214 private YangInstanceIdentifier prepareInstanceIdentifierForList() throws URISyntaxException, ParseException {
215 List<PathArgument> parameters = new ArrayList<>();
217 Date revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-01-09");
218 URI uri = new URI("test:module");
219 QName qNameCont = QName.create(uri, revision, "cont");
220 QName qNameList = QName.create(uri, revision, "lst1");
221 QName qNameKeyList = QName.create(uri, revision, "lf11");
223 parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameCont));
224 parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameList));
225 parameters.add(new YangInstanceIdentifier.NodeIdentifierWithPredicates(qNameList, qNameKeyList,
226 "GigabitEthernet0/0/0/0"));
227 return YangInstanceIdentifier.create(parameters);
231 public void getDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException,
233 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
234 prepareCnDataForMountPointTest(true));
235 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
236 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
237 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
238 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
240 ControllerContext.getInstance().setMountService(mockMountService);
242 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
243 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
248 public void getModulesTest() throws UnsupportedEncodingException, FileNotFoundException {
249 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
251 String uri = "/modules";
253 Response response = target(uri).request("application/yang.api+json").get();
254 validateModulesResponseJson(response);
256 response = target(uri).request("application/yang.api+xml").get();
257 validateModulesResponseXml(response,schemaContextModules);
262 public void getStreamsTest() throws UnsupportedEncodingException, FileNotFoundException {
263 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
265 String uri = "/streams";
267 Response response = target(uri).request("application/yang.api+json").get();
268 String responseBody = response.readEntity(String.class);
269 assertNotNull(responseBody);
270 assertTrue(responseBody.contains("streams"));
272 response = target(uri).request("application/yang.api+xml").get();
273 Document responseXmlBody = response.readEntity(Document.class);
274 assertNotNull(responseXmlBody);
275 Element rootNode = responseXmlBody.getDocumentElement();
277 assertEquals("streams", rootNode.getLocalName());
278 assertEquals(RESTCONF_NS, rootNode.getNamespaceURI());
283 public void getModuleTest() throws FileNotFoundException, UnsupportedEncodingException {
284 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
286 String uri = "/modules/module/module2/2014-01-02";
288 Response response = target(uri).request("application/yang.api+xml").get();
289 assertEquals(200, response.getStatus());
290 Document responseXml = response.readEntity(Document.class);
294 QName qname = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
295 assertNotNull(qname);
297 assertEquals("module2", qname.getLocalName());
298 assertEquals("module:2", qname.getNamespace().toString());
299 assertEquals("2014-01-02", qname.getFormattedRevision());
301 response = target(uri).request("application/yang.api+json").get();
302 assertEquals(200, response.getStatus());
303 String responseBody = response.readEntity(String.class);
304 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
306 String[] split = responseBody.split("\"module\"");
307 assertEquals("\"module\" element is returned more then once", 2, split.length);
313 public void getOperationsTest() throws FileNotFoundException, UnsupportedEncodingException {
314 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
316 String uri = "/operations";
318 Response response = target(uri).request("application/yang.api+xml").get();
319 assertEquals(200, response.getStatus());
320 Document responseDoc = response.readEntity(Document.class);
321 validateOperationsResponseXml(responseDoc, schemaContextModules);
323 response = target(uri).request("application/yang.api+json").get();
324 assertEquals(200, response.getStatus());
325 String responseBody = response.readEntity(String.class);
326 assertTrue("Json response for /operations dummy-rpc1-module1 is incorrect",
327 validateOperationsResponseJson(responseBody, "dummy-rpc1-module1", "module1").find());
328 assertTrue("Json response for /operations dummy-rpc2-module1 is incorrect",
329 validateOperationsResponseJson(responseBody, "dummy-rpc2-module1", "module1").find());
330 assertTrue("Json response for /operations dummy-rpc1-module2 is incorrect",
331 validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
332 assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
333 validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
337 private void validateOperationsResponseXml(final Document responseDoc, final SchemaContext schemaContext) {
338 Element operationsElem = responseDoc.getDocumentElement();
339 assertEquals(RESTCONF_NS, operationsElem.getNamespaceURI());
340 assertEquals("operations", operationsElem.getLocalName());
343 HashSet<QName> foundOperations = new HashSet<>();
345 NodeList operationsList = operationsElem.getChildNodes();
346 for(int i = 0;i < operationsList.getLength();i++) {
347 org.w3c.dom.Node operation = operationsList.item(i);
349 String namespace = operation.getNamespaceURI();
350 String name = operation.getLocalName();
351 QName opQName = QName.create(URI.create(namespace), null, name);
352 foundOperations.add(opQName);
355 for(RpcDefinition schemaOp : schemaContext.getOperations()) {
356 assertTrue(foundOperations.contains(schemaOp.getQName().withoutRevision()));
361 // /operations/pathToMountPoint/yang-ext:mount
363 public void getOperationsBehindMountPointTest() throws FileNotFoundException, UnsupportedEncodingException {
364 ControllerContext controllerContext = ControllerContext.getInstance();
365 controllerContext.setGlobalSchema(schemaContextModules);
367 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
368 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
369 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
370 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
372 controllerContext.setMountService(mockMountService);
374 String uri = "/operations/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
376 Response response = target(uri).request("application/yang.api+xml").get();
377 assertEquals(200, response.getStatus());
379 Document responseDoc = response.readEntity(Document.class);
380 validateOperationsResponseXml(responseDoc, schemaContextBehindMountPoint);
382 response = target(uri).request("application/yang.api+json").get();
383 assertEquals(200, response.getStatus());
384 String responseBody = response.readEntity(String.class);
385 assertTrue("Json response for /operations/mount_point rpc-behind-module1 is incorrect",
386 validateOperationsResponseJson(responseBody, "rpc-behind-module1", "module1-behind-mount-point").find());
387 assertTrue("Json response for /operations/mount_point rpc-behind-module2 is incorrect",
388 validateOperationsResponseJson(responseBody, "rpc-behind-module2", "module2-behind-mount-point").find());
392 private Matcher validateOperationsResponseJson(final String searchIn, final String rpcName, final String moduleName) {
393 StringBuilder regex = new StringBuilder();
396 regex.append(".*\\{");
397 regex.append(".*\"");
399 // operations prefix optional
401 regex.append("ietf-restconf:");
403 // :operations prefix optional
405 regex.append("operations\"");
407 regex.append(".*\\{");
409 regex.append(".*\"" + moduleName);
411 regex.append(rpcName + "\"");
412 regex.append(".*\\[");
413 regex.append(".*null");
414 regex.append(".*\\]");
416 regex.append(".*\\}");
417 regex.append(".*\\}");
421 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
422 return ptrn.matcher(searchIn);
426 private Matcher validateOperationsResponseXml(final String searchIn, final String rpcName, final String namespace) {
427 StringBuilder regex = new StringBuilder();
431 regex.append(".*<operations");
432 regex.append(".*xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"");
436 regex.append(".*" + rpcName);
437 regex.append(".*" + namespace);
441 regex.append(".*</operations.*");
446 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
447 return ptrn.matcher(searchIn);
450 // /restconf/modules/pathToMountPoint/yang-ext:mount
452 public void getModulesBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
453 ControllerContext controllerContext = ControllerContext.getInstance();
454 controllerContext.setGlobalSchema(schemaContextModules);
456 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
457 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
458 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
459 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
461 controllerContext.setMountService(mockMountService);
463 String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
465 Response response = target(uri).request("application/yang.api+json").get();
466 assertEquals(200, response.getStatus());
467 String responseBody = response.readEntity(String.class);
470 "module1-behind-mount-point in json wasn't found",
471 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
472 responseBody).find());
474 "module2-behind-mount-point in json wasn't found",
475 prepareJsonRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point",
476 responseBody).find());
478 response = target(uri).request("application/yang.api+xml").get();
479 assertEquals(200, response.getStatus());
480 validateModulesResponseXml(response, schemaContextBehindMountPoint);
484 // /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
486 public void getModuleBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
487 ControllerContext controllerContext = ControllerContext.getInstance();
488 controllerContext.setGlobalSchema(schemaContextModules);
490 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
491 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
492 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
493 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
495 controllerContext.setMountService(mockMountService);
497 String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/module1-behind-mount-point/2014-02-03";
499 Response response = target(uri).request("application/yang.api+json").get();
500 assertEquals(200, response.getStatus());
501 String responseBody = response.readEntity(String.class);
504 "module1-behind-mount-point in json wasn't found",
505 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
506 responseBody).find());
507 String[] split = responseBody.split("\"module\"");
508 assertEquals("\"module\" element is returned more then once", 2, split.length);
510 response = target(uri).request("application/yang.api+xml").get();
511 assertEquals(200, response.getStatus());
512 Document responseXml = response.readEntity(Document.class);
514 QName module = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
516 assertEquals("module1-behind-mount-point", module.getLocalName());
517 assertEquals("2014-02-03", module.getFormattedRevision());
518 assertEquals("module:1:behind:mount:point", module.getNamespace().toString());
523 private void validateModulesResponseXml(final Response response, final SchemaContext schemaContext) {
524 assertEquals(200, response.getStatus());
525 Document responseBody = response.readEntity(Document.class);
526 NodeList moduleNodes = responseBody.getDocumentElement().getElementsByTagNameNS(RESTCONF_NS, "module");
528 assertTrue(moduleNodes.getLength() > 0);
530 HashSet<QName> foundModules = new HashSet<>();
532 for(int i=0;i < moduleNodes.getLength();i++) {
533 org.w3c.dom.Node module = moduleNodes.item(i);
535 QName name = assertedModuleXmlToModuleQName(module);
536 foundModules.add(name);
539 assertAllModules(foundModules,schemaContext);
542 private void assertAllModules(final Set<QName> foundModules, final SchemaContext schemaContext) {
543 for(Module module : schemaContext.getModules()) {
544 QName current = QName.create(module.getQNameModule(),module.getName());
545 assertTrue("Module not found in response.",foundModules.contains(current));
550 private QName assertedModuleXmlToModuleQName(final org.w3c.dom.Node module) {
551 assertEquals("module", module.getLocalName());
552 assertEquals(RESTCONF_NS, module.getNamespaceURI());
553 String revision = null;
554 String namespace = null;
558 NodeList childNodes = module.getChildNodes();
560 for(int i =0;i < childNodes.getLength(); i++) {
561 org.w3c.dom.Node child = childNodes.item(i);
562 assertEquals(RESTCONF_NS, child.getNamespaceURI());
564 switch(child.getLocalName()) {
566 assertNull("Name element appeared multiple times",name);
567 name = child.getTextContent().trim();
570 assertNull("Revision element appeared multiple times",revision);
571 revision = child.getTextContent().trim();
575 assertNull("Namespace element appeared multiple times",namespace);
576 namespace = child.getTextContent().trim();
581 assertNotNull("Revision was not part of xml",revision);
582 assertNotNull("Module namespace was not part of xml",namespace);
583 assertNotNull("Module identiffier was not part of xml",name);
586 // TODO Auto-generated method stub
588 return QName.create(namespace,revision,name);
591 private void validateModulesResponseJson(final Response response) {
592 assertEquals(200, response.getStatus());
593 String responseBody = response.readEntity(String.class);
595 assertTrue("Module1 in json wasn't found", prepareJsonRegex("module1", "2014-01-01", "module:1", responseBody)
597 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
599 assertTrue("Module3 in json wasn't found", prepareJsonRegex("module3", "2014-01-03", "module:3", responseBody)
603 private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
604 final String searchIn) {
605 StringBuilder regex = new StringBuilder();
608 regex.append(".*\\{");
609 regex.append(".*\"name\"");
611 regex.append(".*\"" + module + "\",");
613 regex.append(".*\"revision\"");
615 regex.append(".*\"" + revision + "\",");
617 regex.append(".*\"namespace\"");
619 regex.append(".*\"" + namespace + "\"");
621 regex.append(".*\\}");
625 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
626 return ptrn.matcher(searchIn);
631 private void prepareMockForModulesTest(final ControllerContext mockedControllerContext)
632 throws FileNotFoundException {
633 SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
634 mockedControllerContext.setGlobalSchema(schemaContext);
635 // when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
638 private int get(final String uri, final String mediaType) {
639 return target(uri).request(mediaType).get().getStatus();
649 private NormalizedNode prepareCnDataForMountPointTest(boolean wrapToCont) throws URISyntaxException, ParseException {
650 String testModuleDate = "2014-01-09";
651 ContainerNode contChild = Builders
653 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont1", "test:module", testModuleDate))
655 Builders.leafBuilder()
656 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", testModuleDate))
657 .withValue("lf11 value").build()).build();
660 return Builders.containerBuilder()
661 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont", "test:module", testModuleDate))
662 .withChild(contChild).build();
668 private void mockReadOperationalDataMethod() {
669 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
672 private void mockReadConfigurationDataMethod() {
673 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
676 private NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws ParseException {
677 CollectionNodeBuilder<MapEntryNode, MapNode> lst1 = ImmutableMapNodeBuilder.create();
678 lst1.withNodeIdentifier(TestUtils.getNodeIdentifier("lst1", "test:module", "2014-01-09"));
679 lst1.withChild(ImmutableMapEntryNodeBuilder
682 TestUtils.getNodeIdentifierPredicate("lst1", "test:module", "2014-01-09", "lf11",
683 "GigabitEthernet0/0/0/0"))
685 ImmutableLeafNodeBuilder.create()
686 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", "2014-01-09"))
687 .withValue("GigabitEthernet0/0/0/0").build()).build());
693 * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
695 * @throws UnsupportedEncodingException
698 public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
699 getDataWithUriIncludeWhiteCharsParameter("config");
700 getDataWithUriIncludeWhiteCharsParameter("operational");
703 private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws UnsupportedEncodingException {
704 mockReadConfigurationDataMethod();
705 mockReadOperationalDataMethod();
706 String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
707 Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
708 String xmlData = response.readEntity(String.class);
710 Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
711 Matcher matcher = pattern.matcher(xmlData);
712 // XML element can't surrounded with white character (e.g "> " or
714 assertFalse(matcher.matches());
716 response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
717 String jsonData = response.readEntity(String.class);
718 pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
719 matcher = pattern.matcher(jsonData);
720 // JSON element can't surrounded with white character (e.g "} ", " {",
721 // "] ", " [", " :" or ": ")
722 assertFalse(matcher.matches());
726 public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
728 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
730 CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
731 toNestedQName("depth1-cont"),
733 toNestedQName("depth2-cont1"),
735 toNestedQName("depth3-cont1"),
736 toCompositeNodeData(toNestedQName("depth4-cont1"),
737 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
738 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
739 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
741 toNestedQName("depth2-cont2"),
743 toNestedQName("depth3-cont2"),
744 toCompositeNodeData(toNestedQName("depth4-cont2"),
745 toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
746 toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
747 toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
748 toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
750 Module module = TestUtils.findModule(schemaContextModules.getModules(), "nested-module");
751 assertNotNull(module);
753 DataSchemaNode dataSchemaNode = TestUtils.resolveDataSchemaNode("depth1-cont", module);
754 assertNotNull(dataSchemaNode);
756 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(
757 TestUtils.compositeNodeToDatastoreNormalizedNode(depth1Cont, dataSchemaNode));
759 // Test config with depth 1
761 Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
762 .request("application/xml").get();
764 verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
766 // Test config with depth 2
768 response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
772 // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
773 // Response mr=mock(Response.class);
774 // when(mr.getEntity()).thenReturn( new
775 // java.io.StringBufferInputStream(xml) );
779 expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
780 expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
782 // Test config with depth 3
784 response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
791 expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
792 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
793 expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
794 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
795 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
797 // Test config with depth 4
799 response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
808 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
809 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
810 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
813 expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
814 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
815 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
816 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
818 // Test config with depth 5
820 response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
831 expectContainer("depth4-cont1",
832 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
833 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
834 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
839 expectContainer("depth4-cont2",
840 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
841 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
842 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
843 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
845 // Test config with depth unbounded
847 response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
848 .request("application/xml").get();
858 expectContainer("depth4-cont1",
859 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
860 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
861 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
866 expectContainer("depth4-cont2",
867 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
868 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
869 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
870 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
874 CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
875 toNestedQName("depth2-cont1"),
877 toNestedQName("depth3-cont1"),
878 toCompositeNodeData(toNestedQName("depth4-cont1"),
879 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
880 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
881 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
883 assertTrue(dataSchemaNode instanceof DataNodeContainer);
884 DataSchemaNode depth2cont1Schema = null;
885 for (DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
886 if (childNode.getQName().getLocalName().equals("depth2-cont1")) {
887 depth2cont1Schema = childNode;
891 assertNotNull(depth2Cont1);
893 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(
894 TestUtils.compositeNodeToDatastoreNormalizedNode(depth2Cont1, depth2cont1Schema));
896 response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
897 .request("application/xml").get();
903 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
904 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
905 expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
909 public void getDataWithInvalidDepthParameterTest() {
911 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
913 final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
914 paramMap.putSingle("depth", "1o");
915 UriInfo mockInfo = mock(UriInfo.class);
916 when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
918 public MultivaluedMap<String, String> answer(InvocationOnMock invocation) {
923 getDataWithInvalidDepthParameterTest(mockInfo);
925 paramMap.putSingle("depth", "0");
926 getDataWithInvalidDepthParameterTest(mockInfo);
928 paramMap.putSingle("depth", "-1");
929 getDataWithInvalidDepthParameterTest(mockInfo);
932 private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
934 restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
935 fail("Expected RestconfDocumentedException");
936 } catch (RestconfDocumentedException e) {
937 assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
938 .getErrorMessage().contains("depth"));
942 private void verifyXMLResponse(final Response response, final NodeData nodeData) {
943 Document doc = response.readEntity(Document.class);
944 // Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
945 // System.out.println();
946 assertNotNull("Could not parse XML document", doc);
948 // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
950 verifyContainerElement(doc.getDocumentElement(), nodeData);
953 @SuppressWarnings("unchecked")
954 private void verifyContainerElement(final Element element, final NodeData nodeData) {
956 assertEquals("Element local name", nodeData.key, element.getLocalName());
958 NodeList childNodes = element.getChildNodes();
959 if (nodeData.data == null) { // empty container
960 assertTrue("Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
964 Map<String, NodeData> expChildMap = Maps.newHashMap();
965 for (NodeData expChild : (List<NodeData>) nodeData.data) {
966 expChildMap.put(expChild.key.toString(), expChild);
969 for (int i = 0; i < childNodes.getLength(); i++) {
970 org.w3c.dom.Node actualChild = childNodes.item(i);
971 if (!(actualChild instanceof Element)) {
975 Element actualElement = (Element) actualChild;
976 NodeData expChild = expChildMap.remove(actualElement.getLocalName());
978 "Unexpected child element for parent \"" + element.getLocalName() + "\": "
979 + actualElement.getLocalName(), expChild);
981 if (expChild.data == null || expChild.data instanceof List) {
982 verifyContainerElement(actualElement, expChild);
984 assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data,
985 actualElement.getTextContent());
989 if (!expChildMap.isEmpty()) {
990 fail("Missing elements for parent \"" + element.getLocalName() + "\": " + expChildMap.keySet());
994 private NodeData expectContainer(final String name, final NodeData... childData) {
995 return new NodeData(name, Lists.newArrayList(childData));
998 private NodeData expectEmptyContainer(final String name) {
999 return new NodeData(name, null);
1002 private NodeData expectLeaf(final String name, final Object value) {
1003 return new NodeData(name, value);
1006 private QName toNestedQName(final String localName) {
1007 return QName.create("urn:nested:module", "2014-06-3", localName);
1010 @SuppressWarnings("unchecked")
1011 private CompositeNode toCompositeNode(final NodeData nodeData) {
1012 CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
1013 builder.setQName((QName) nodeData.key);
1015 for (NodeData child : (List<NodeData>) nodeData.data) {
1016 if (child.data instanceof List) {
1017 builder.add(toCompositeNode(child));
1019 builder.addLeaf((QName) child.key, child.data);
1023 return builder.toInstance();
1026 private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
1027 return new NodeData(key, Lists.newArrayList(childData));
1030 private NodeData toSimpleNodeData(final QName key, final Object value) {
1031 return new NodeData(key, value);