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.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.mockito.Matchers.any;
16 import static org.mockito.Matchers.eq;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.when;
20 import com.google.common.collect.Lists;
21 import com.google.common.collect.Maps;
22 import java.io.FileNotFoundException;
23 import java.io.InputStream;
24 import java.io.UnsupportedEncodingException;
26 import java.net.URISyntaxException;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.Date;
31 import java.util.List;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35 import javax.ws.rs.core.Application;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.MultivaluedHashMap;
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.UriInfo;
41 import org.glassfish.jersey.server.ResourceConfig;
42 import org.glassfish.jersey.test.JerseyTest;
43 import org.junit.BeforeClass;
44 import org.junit.Test;
45 import org.mockito.invocation.InvocationOnMock;
46 import org.mockito.stubbing.Answer;
47 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
48 import org.opendaylight.controller.sal.core.api.mount.MountService;
49 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
50 import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper;
51 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
52 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
53 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
54 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
55 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
56 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
57 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
58 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
59 import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
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.InstanceIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
64 import org.opendaylight.yangtools.yang.data.api.Node;
65 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
66 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.w3c.dom.Document;
69 import org.w3c.dom.Element;
70 import org.w3c.dom.NodeList;
72 public class RestGetOperationTest extends JerseyTest {
74 static class NodeData {
76 Object data; // List for a CompositeNode, value Object for a SimpleNode
78 NodeData(final Object key, final Object data) {
84 private static BrokerFacade brokerFacade;
85 private static RestconfImpl restconfImpl;
86 private static SchemaContext schemaContextYangsIetf;
87 private static SchemaContext schemaContextTestModule;
88 private static CompositeNode answerFromGet;
90 private static SchemaContext schemaContextModules;
91 private static SchemaContext schemaContextBehindMountPoint;
94 public static void init() throws FileNotFoundException {
95 schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
96 schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
97 ControllerContext controllerContext = ControllerContext.getInstance();
98 controllerContext.setSchemas(schemaContextYangsIetf);
99 brokerFacade = mock(BrokerFacade.class);
100 restconfImpl = RestconfImpl.getInstance();
101 restconfImpl.setBroker(brokerFacade);
102 restconfImpl.setControllerContext(controllerContext);
103 answerFromGet = prepareCompositeNodeWithIetfInterfacesInterfacesData();
105 schemaContextModules = TestUtils.loadSchemaContext("/modules");
106 schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
110 protected Application configure() {
111 /* enable/disable Jersey logs to console */
112 // enable(TestProperties.LOG_TRAFFIC);
113 // enable(TestProperties.DUMP_ENTITY);
114 // enable(TestProperties.RECORD_LOG_LEVEL);
115 // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
116 ResourceConfig resourceConfig = new ResourceConfig();
117 resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
118 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
119 JsonToCompositeNodeProvider.INSTANCE);
120 resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
121 return resourceConfig;
125 * Tests of status codes for "/operational/{identifier}".
128 public void getOperationalStatusCodes() throws UnsupportedEncodingException {
129 mockReadOperationalDataMethod();
130 String uri = "/operational/ietf-interfaces:interfaces/interface/eth0";
131 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
133 uri = "/operational/wrong-module:interfaces/interface/eth0";
134 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
138 * Tests of status codes for "/config/{identifier}".
141 public void getConfigStatusCodes() throws UnsupportedEncodingException {
142 mockReadConfigurationDataMethod();
143 String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
144 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
146 uri = "/config/wrong-module:interfaces/interface/eth0";
147 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
151 * MountPoint test. URI represents mount point.
154 public void getDataWithUrlMountPoint() throws UnsupportedEncodingException, URISyntaxException {
156 brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class),
157 any(InstanceIdentifier.class))).thenReturn(prepareCnDataForMountPointTest());
158 MountInstance mountInstance = mock(MountInstance.class);
159 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
160 MountService mockMountService = mock(MountService.class);
161 when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
163 ControllerContext.getInstance().setMountService(mockMountService);
165 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/cont1";
166 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
168 uri = "/config/ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
169 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
173 * MountPoint test. URI represents mount point.
175 * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
176 * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
177 * InstanceIdentifier parameter in method
178 * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, InstanceIdentifier)} which is called in
179 * method {@link RestconfImpl#readConfigurationData}
182 * @throws ParseException
185 public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException,
187 InstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
189 brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class),
190 eq(awaitedInstanceIdentifier))).thenReturn(prepareCnDataForMountPointTest());
191 MountInstance mountInstance = mock(MountInstance.class);
192 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
193 MountService mockMountService = mock(MountService.class);
194 when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
196 ControllerContext.getInstance().setMountService(mockMountService);
198 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
199 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
202 private InstanceIdentifier prepareInstanceIdentifierForList() throws URISyntaxException, ParseException {
203 List<PathArgument> parameters = new ArrayList<>();
205 Date revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-01-09");
206 URI uri = new URI("test:module");
207 QName qNameCont = QName.create(uri, revision, "cont");
208 QName qNameList = QName.create(uri, revision, "lst1");
209 QName qNameKeyList = QName.create(uri, revision, "lf11");
211 parameters.add(new InstanceIdentifier.NodeIdentifier(qNameCont));
212 parameters.add(new InstanceIdentifier.NodeIdentifierWithPredicates(qNameList, qNameKeyList,
213 "GigabitEthernet0/0/0/0"));
214 return InstanceIdentifier.create(parameters);
218 public void getDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException {
220 brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class),
221 any(InstanceIdentifier.class))).thenReturn(prepareCnDataForMountPointTest());
222 MountInstance mountInstance = mock(MountInstance.class);
223 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
224 MountService mockMountService = mock(MountService.class);
225 when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
227 ControllerContext.getInstance().setMountService(mockMountService);
229 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
230 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
235 public void getModulesTest() throws UnsupportedEncodingException, FileNotFoundException {
236 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
238 String uri = "/modules";
240 Response response = target(uri).request("application/yang.api+json").get();
241 validateModulesResponseJson(response);
243 response = target(uri).request("application/yang.api+xml").get();
244 validateModulesResponseXml(response);
249 public void getStreamsTest() throws UnsupportedEncodingException, FileNotFoundException {
250 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
252 String uri = "/streams";
254 Response response = target(uri).request("application/yang.api+json").get();
255 String responseBody = response.readEntity(String.class);
256 assertNotNull(responseBody);
257 assertTrue(responseBody.contains("streams"));
259 response = target(uri).request("application/yang.api+xml").get();
260 responseBody = response.readEntity(String.class);
261 assertNotNull(responseBody);
262 assertTrue(responseBody.contains("<streams xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\""));
267 public void getModuleTest() throws FileNotFoundException, UnsupportedEncodingException {
268 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
270 String uri = "/modules/module/module2/2014-01-02";
272 Response response = target(uri).request("application/yang.api+xml").get();
273 assertEquals(200, response.getStatus());
274 String responseBody = response.readEntity(String.class);
275 assertTrue("Module2 in xml wasn't found", prepareXmlRegex("module2", "2014-01-02", "module:2", responseBody)
277 String[] split = responseBody.split("<module");
278 assertEquals("<module element is returned more then once", 2, split.length);
280 response = target(uri).request("application/yang.api+json").get();
281 assertEquals(200, response.getStatus());
282 responseBody = response.readEntity(String.class);
283 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
285 split = responseBody.split("\"module\"");
286 assertEquals("\"module\" element is returned more then once", 2, split.length);
292 public void getOperationsTest() throws FileNotFoundException, UnsupportedEncodingException {
293 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
295 String uri = "/operations";
297 Response response = target(uri).request("application/yang.api+xml").get();
298 assertEquals(200, response.getStatus());
299 String responseBody = response.readEntity(String.class);
300 assertTrue("Xml response for /operations dummy-rpc1-module1 is incorrect",
301 validateOperationsResponseXml(responseBody, "dummy-rpc1-module1", "module:1").find());
302 assertTrue("Xml response for /operations dummy-rpc2-module1 is incorrect",
303 validateOperationsResponseXml(responseBody, "dummy-rpc2-module1", "module:1").find());
304 assertTrue("Xml response for /operations dummy-rpc1-module2 is incorrect",
305 validateOperationsResponseXml(responseBody, "dummy-rpc1-module2", "module:2").find());
306 assertTrue("Xml response for /operations dummy-rpc2-module2 is incorrect",
307 validateOperationsResponseXml(responseBody, "dummy-rpc2-module2", "module:2").find());
309 response = target(uri).request("application/yang.api+json").get();
310 assertEquals(200, response.getStatus());
311 responseBody = response.readEntity(String.class);
312 assertTrue("Json response for /operations dummy-rpc1-module1 is incorrect",
313 validateOperationsResponseJson(responseBody, "dummy-rpc1-module1", "module1").find());
314 assertTrue("Json response for /operations dummy-rpc2-module1 is incorrect",
315 validateOperationsResponseJson(responseBody, "dummy-rpc2-module1", "module1").find());
316 assertTrue("Json response for /operations dummy-rpc1-module2 is incorrect",
317 validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
318 assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
319 validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
323 // /operations/pathToMountPoint/yang-ext:mount
325 public void getOperationsBehindMountPointTest() throws FileNotFoundException, UnsupportedEncodingException {
326 ControllerContext controllerContext = ControllerContext.getInstance();
327 controllerContext.setGlobalSchema(schemaContextModules);
329 MountInstance mountInstance = mock(MountInstance.class);
330 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
331 MountService mockMountService = mock(MountService.class);
332 when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
334 controllerContext.setMountService(mockMountService);
336 String uri = "/operations/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
338 Response response = target(uri).request("application/yang.api+xml").get();
339 assertEquals(200, response.getStatus());
340 String responseBody = response.readEntity(String.class);
341 assertTrue("Xml response for /operations/mount_point rpc-behind-module1 is incorrect",
342 validateOperationsResponseXml(responseBody, "rpc-behind-module1", "module:1:behind:mount:point").find());
343 assertTrue("Xml response for /operations/mount_point rpc-behind-module2 is incorrect",
344 validateOperationsResponseXml(responseBody, "rpc-behind-module2", "module:2:behind:mount:point").find());
346 response = target(uri).request("application/yang.api+json").get();
347 assertEquals(200, response.getStatus());
348 responseBody = response.readEntity(String.class);
349 assertTrue("Json response for /operations/mount_point rpc-behind-module1 is incorrect",
350 validateOperationsResponseJson(responseBody, "rpc-behind-module1", "module1-behind-mount-point").find());
351 assertTrue("Json response for /operations/mount_point rpc-behind-module2 is incorrect",
352 validateOperationsResponseJson(responseBody, "rpc-behind-module2", "module2-behind-mount-point").find());
356 private Matcher validateOperationsResponseJson(final String searchIn, final String rpcName, final String moduleName) {
357 StringBuilder regex = new StringBuilder();
360 regex.append(".*\\{");
361 regex.append(".*\"");
363 // operations prefix optional
365 regex.append("ietf-restconf:");
367 // :operations prefix optional
369 regex.append("operations\"");
371 regex.append(".*\\{");
373 regex.append(".*\"" + moduleName);
375 regex.append(rpcName + "\"");
376 regex.append(".*\\[");
377 regex.append(".*null");
378 regex.append(".*\\]");
380 regex.append(".*\\}");
381 regex.append(".*\\}");
385 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
386 return ptrn.matcher(searchIn);
390 private Matcher validateOperationsResponseXml(final String searchIn, final String rpcName, final String namespace) {
391 StringBuilder regex = new StringBuilder();
395 regex.append(".*<operations");
396 regex.append(".*xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"");
400 regex.append(".*" + rpcName);
401 regex.append(".*" + namespace);
405 regex.append(".*</operations.*");
410 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
411 return ptrn.matcher(searchIn);
414 // /restconf/modules/pathToMountPoint/yang-ext:mount
416 public void getModulesBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
417 ControllerContext controllerContext = ControllerContext.getInstance();
418 controllerContext.setGlobalSchema(schemaContextModules);
420 MountInstance mountInstance = mock(MountInstance.class);
421 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
422 MountService mockMountService = mock(MountService.class);
423 when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
425 controllerContext.setMountService(mockMountService);
427 String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
429 Response response = target(uri).request("application/yang.api+json").get();
430 assertEquals(200, response.getStatus());
431 String responseBody = response.readEntity(String.class);
434 "module1-behind-mount-point in json wasn't found",
435 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
436 responseBody).find());
438 "module2-behind-mount-point in json wasn't found",
439 prepareJsonRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point",
440 responseBody).find());
442 response = target(uri).request("application/yang.api+xml").get();
443 assertEquals(200, response.getStatus());
444 responseBody = response.readEntity(String.class);
446 "module1-behind-mount-point in json wasn't found",
447 prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody)
450 "module2-behind-mount-point in json wasn't found",
451 prepareXmlRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point", responseBody)
456 // /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
458 public void getModuleBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
459 ControllerContext controllerContext = ControllerContext.getInstance();
460 controllerContext.setGlobalSchema(schemaContextModules);
462 MountInstance mountInstance = mock(MountInstance.class);
463 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
464 MountService mockMountService = mock(MountService.class);
465 when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
467 controllerContext.setMountService(mockMountService);
469 String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/module1-behind-mount-point/2014-02-03";
471 Response response = target(uri).request("application/yang.api+json").get();
472 assertEquals(200, response.getStatus());
473 String responseBody = response.readEntity(String.class);
476 "module1-behind-mount-point in json wasn't found",
477 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
478 responseBody).find());
479 String[] split = responseBody.split("\"module\"");
480 assertEquals("\"module\" element is returned more then once", 2, split.length);
482 response = target(uri).request("application/yang.api+xml").get();
483 assertEquals(200, response.getStatus());
484 responseBody = response.readEntity(String.class);
486 "module1-behind-mount-point in json wasn't found",
487 prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody)
489 split = responseBody.split("<module");
490 assertEquals("<module element is returned more then once", 2, split.length);
494 private void validateModulesResponseXml(final Response response) {
495 assertEquals(200, response.getStatus());
496 String responseBody = response.readEntity(String.class);
498 assertTrue("Module1 in xml wasn't found", prepareXmlRegex("module1", "2014-01-01", "module:1", responseBody)
500 assertTrue("Module2 in xml wasn't found", prepareXmlRegex("module2", "2014-01-02", "module:2", responseBody)
502 assertTrue("Module3 in xml wasn't found", prepareXmlRegex("module3", "2014-01-03", "module:3", responseBody)
506 private void validateModulesResponseJson(final Response response) {
507 assertEquals(200, response.getStatus());
508 String responseBody = response.readEntity(String.class);
510 assertTrue("Module1 in json wasn't found", prepareJsonRegex("module1", "2014-01-01", "module:1", responseBody)
512 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
514 assertTrue("Module3 in json wasn't found", prepareJsonRegex("module3", "2014-01-03", "module:3", responseBody)
518 private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
519 final String searchIn) {
520 StringBuilder regex = new StringBuilder();
523 regex.append(".*\\{");
524 regex.append(".*\"name\"");
526 regex.append(".*\"" + module + "\",");
528 regex.append(".*\"revision\"");
530 regex.append(".*\"" + revision + "\",");
532 regex.append(".*\"namespace\"");
534 regex.append(".*\"" + namespace + "\"");
536 regex.append(".*\\}");
540 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
541 return ptrn.matcher(searchIn);
545 private Matcher prepareXmlRegex(final String module, final String revision, final String namespace,
546 final String searchIn) {
547 StringBuilder regex = new StringBuilder();
550 regex.append(".*<module.*");
553 regex.append(".*<name>");
554 regex.append(".*" + module);
555 regex.append(".*<\\/name>");
557 regex.append(".*<revision>");
558 regex.append(".*" + revision);
559 regex.append(".*<\\/revision>");
561 regex.append(".*<namespace>");
562 regex.append(".*" + namespace);
563 regex.append(".*<\\/namespace>");
565 regex.append(".*<\\/module.*>");
570 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
571 return ptrn.matcher(searchIn);
574 private void prepareMockForModulesTest(final ControllerContext mockedControllerContext)
575 throws FileNotFoundException {
576 SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
577 mockedControllerContext.setGlobalSchema(schemaContext);
578 // when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
581 private int get(final String uri, final String mediaType) {
582 return target(uri).request(mediaType).get().getStatus();
585 private CompositeNode prepareCnDataForMountPointTest() throws URISyntaxException {
586 CompositeNodeWrapper cont1 = new CompositeNodeWrapper(new URI("test:module"), "cont1");
587 SimpleNodeWrapper lf11 = new SimpleNodeWrapper(new URI("test:module"), "lf11", "lf11 value");
588 cont1.addValue(lf11);
589 return cont1.unwrap();
592 private void mockReadOperationalDataMethod() {
593 when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(answerFromGet);
596 private void mockReadConfigurationDataMethod() {
597 when(brokerFacade.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(answerFromGet);
600 private static CompositeNode prepareCompositeNodeWithIetfInterfacesInterfacesData() {
601 CompositeNode intface;
603 intface = new CompositeNodeWrapper(new URI("interface"), "interface");
604 List<Node<?>> childs = new ArrayList<>();
606 childs.add(new SimpleNodeWrapper(new URI("name"), "name", "eth0"));
607 childs.add(new SimpleNodeWrapper(new URI("type"), "type", "ethernetCsmacd"));
608 childs.add(new SimpleNodeWrapper(new URI("enabled"), "enabled", Boolean.FALSE));
609 childs.add(new SimpleNodeWrapper(new URI("description"), "description", "some interface"));
610 intface.setValue(childs);
612 } catch (URISyntaxException e) {
619 * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
621 * @throws UnsupportedEncodingException
624 public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
625 getDataWithUriIncludeWhiteCharsParameter("config");
626 getDataWithUriIncludeWhiteCharsParameter("operational");
629 private void getDataWithUriIncludeWhiteCharsParameter(String target) throws UnsupportedEncodingException {
630 mockReadConfigurationDataMethod();
631 String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
632 Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
633 String xmlData = response.readEntity(String.class);
635 Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
636 Matcher matcher = pattern.matcher(xmlData);
637 // XML element can't surrounded with white character (e.g "> " or
639 assertFalse(matcher.matches());
641 response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
642 String jsonData = response.readEntity(String.class);
643 pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
644 matcher = pattern.matcher(jsonData);
645 // JSON element can't surrounded with white character (e.g "} ", " {",
646 // "] ", " [", " :" or ": ")
647 assertFalse(matcher.matches());
651 public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
653 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
655 CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
656 toNestedQName("depth1-cont"),
658 toNestedQName("depth2-cont1"),
660 toNestedQName("depth3-cont1"),
661 toCompositeNodeData(toNestedQName("depth4-cont1"),
662 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
663 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
664 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
666 toNestedQName("depth2-cont2"),
668 toNestedQName("depth3-cont2"),
669 toCompositeNodeData(toNestedQName("depth4-cont2"),
670 toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
671 toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
672 toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
673 toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
675 when(brokerFacade.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(depth1Cont);
677 // Test config with depth 1
679 Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
680 .request("application/xml").get();
682 verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
684 // Test config with depth 2
686 response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
690 // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
691 // Response mr=mock(Response.class);
692 // when(mr.getEntity()).thenReturn( new
693 // java.io.StringBufferInputStream(xml) );
697 expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
698 expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
700 // Test config with depth 3
702 response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
709 expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
710 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
711 expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
712 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
713 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
715 // Test config with depth 4
717 response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
726 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
727 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
728 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
731 expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
732 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
733 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
734 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
736 // Test config with depth 5
738 response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
749 expectContainer("depth4-cont1",
750 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
751 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
752 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
757 expectContainer("depth4-cont2",
758 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
759 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
760 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
761 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
763 // Test config with depth unbounded
765 response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
766 .request("application/xml").get();
776 expectContainer("depth4-cont1",
777 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
778 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
779 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
784 expectContainer("depth4-cont2",
785 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
786 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
787 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
788 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
792 CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
793 toNestedQName("depth2-cont1"),
795 toNestedQName("depth3-cont1"),
796 toCompositeNodeData(toNestedQName("depth4-cont1"),
797 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
798 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
799 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
801 when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(depth2Cont1);
803 response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
804 .request("application/xml").get();
810 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
811 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
812 expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
816 public void getDataWithInvalidDepthParameterTest() {
818 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
820 final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
821 paramMap.putSingle("depth", "1o");
822 UriInfo mockInfo = mock(UriInfo.class);
823 when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
825 public MultivaluedMap<String, String> answer(final InvocationOnMock invocation) {
830 getDataWithInvalidDepthParameterTest(mockInfo);
832 paramMap.putSingle("depth", "0");
833 getDataWithInvalidDepthParameterTest(mockInfo);
835 paramMap.putSingle("depth", "-1");
836 getDataWithInvalidDepthParameterTest(mockInfo);
839 private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
841 restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
842 fail("Expected RestconfDocumentedException");
843 } catch (RestconfDocumentedException e) {
844 assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
845 .getErrorMessage().contains("depth"));
849 private void verifyXMLResponse(final Response response, final NodeData nodeData) {
851 Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
852 assertNotNull("Could not parse XML document", doc);
854 // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
856 verifyContainerElement(doc.getDocumentElement(), nodeData);
859 @SuppressWarnings("unchecked")
860 private void verifyContainerElement(final Element element, final NodeData nodeData) {
862 assertEquals("Element local name", nodeData.key, element.getNodeName());
864 NodeList childNodes = element.getChildNodes();
865 if (nodeData.data == null) { // empty container
866 assertTrue("Expected no child elements for \"" + element.getNodeName() + "\"", childNodes.getLength() == 0);
870 Map<String, NodeData> expChildMap = Maps.newHashMap();
871 for (NodeData expChild : (List<NodeData>) nodeData.data) {
872 expChildMap.put(expChild.key.toString(), expChild);
875 for (int i = 0; i < childNodes.getLength(); i++) {
876 org.w3c.dom.Node actualChild = childNodes.item(i);
877 if (!(actualChild instanceof Element)) {
881 Element actualElement = (Element) actualChild;
882 NodeData expChild = expChildMap.remove(actualElement.getNodeName());
884 "Unexpected child element for parent \"" + element.getNodeName() + "\": "
885 + actualElement.getNodeName(), expChild);
887 if (expChild.data == null || expChild.data instanceof List) {
888 verifyContainerElement(actualElement, expChild);
890 assertEquals("Text content for element: " + actualElement.getNodeName(), expChild.data,
891 actualElement.getTextContent());
895 if (!expChildMap.isEmpty()) {
896 fail("Missing elements for parent \"" + element.getNodeName() + "\": " + expChildMap.keySet());
900 private NodeData expectContainer(final String name, final NodeData... childData) {
901 return new NodeData(name, Lists.newArrayList(childData));
904 private NodeData expectEmptyContainer(final String name) {
905 return new NodeData(name, null);
908 private NodeData expectLeaf(final String name, final Object value) {
909 return new NodeData(name, value);
912 private QName toNestedQName(final String localName) {
913 return QName.create("urn:nested:module", "2014-06-3", localName);
916 @SuppressWarnings("unchecked")
917 private CompositeNode toCompositeNode(final NodeData nodeData) {
918 CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
919 builder.setQName((QName) nodeData.key);
921 for (NodeData child : (List<NodeData>) nodeData.data) {
922 if (child.data instanceof List) {
923 builder.add(toCompositeNode(child));
925 builder.addLeaf((QName) child.key, child.data);
929 return builder.toInstance();
932 private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
933 return new NodeData(key, Lists.newArrayList(childData));
936 private NodeData toSimpleNodeData(final QName key, final Object value) {
937 return new NodeData(key, value);