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.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
66 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
68 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
69 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
70 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
71 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
72 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
73 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
74 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.Module;
76 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
77 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
78 import org.w3c.dom.Document;
79 import org.w3c.dom.Element;
80 import org.w3c.dom.NodeList;
82 public class RestGetOperationTest extends JerseyTest {
84 static class NodeData {
86 Object data; // List for a CompositeNode, value Object for a SimpleNode
88 NodeData(final Object key, final Object data) {
94 private static BrokerFacade brokerFacade;
95 private static RestconfImpl restconfImpl;
96 private static SchemaContext schemaContextYangsIetf;
97 private static SchemaContext schemaContextTestModule;
98 private static NormalizedNode answerFromGet;
100 private static SchemaContext schemaContextModules;
101 private static SchemaContext schemaContextBehindMountPoint;
103 private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf";
106 public static void init() throws FileNotFoundException, ParseException {
107 schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
108 schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
109 ControllerContext controllerContext = ControllerContext.getInstance();
110 controllerContext.setSchemas(schemaContextYangsIetf);
111 brokerFacade = mock(BrokerFacade.class);
112 restconfImpl = RestconfImpl.getInstance();
113 restconfImpl.setBroker(brokerFacade);
114 restconfImpl.setControllerContext(controllerContext);
115 answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
117 schemaContextModules = TestUtils.loadSchemaContext("/modules");
118 schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
122 protected Application configure() {
123 /* enable/disable Jersey logs to console */
124 // enable(TestProperties.LOG_TRAFFIC);
125 // enable(TestProperties.DUMP_ENTITY);
126 // enable(TestProperties.RECORD_LOG_LEVEL);
127 // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
128 ResourceConfig resourceConfig = new ResourceConfig();
129 resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
130 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
131 JsonToCompositeNodeProvider.INSTANCE);
132 resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
133 return resourceConfig;
137 * Tests of status codes for "/operational/{identifier}".
140 public void getOperationalStatusCodes() throws UnsupportedEncodingException {
141 mockReadOperationalDataMethod();
142 String uri = "/operational/ietf-interfaces:interfaces/interface/eth0";
143 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
145 uri = "/operational/wrong-module:interfaces/interface/eth0";
146 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
150 * Tests of status codes for "/config/{identifier}".
153 public void getConfigStatusCodes() throws UnsupportedEncodingException {
154 mockReadConfigurationDataMethod();
155 String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
156 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
158 uri = "/config/wrong-module:interfaces/interface/eth0";
159 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
163 * MountPoint test. URI represents mount point.
166 public void getDataWithUrlMountPoint() throws UnsupportedEncodingException, URISyntaxException, ParseException {
167 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
168 prepareCnDataForMountPointTest(false));
169 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
170 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
171 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
172 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
174 ControllerContext.getInstance().setMountService(mockMountService);
176 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/cont1";
177 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
179 uri = "/config/ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
180 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
184 * MountPoint test. URI represents mount point.
186 * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
187 * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
188 * InstanceIdentifier parameter in method
189 * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, YangInstanceIdentifier)} which is called in
190 * method {@link RestconfImpl#readConfigurationData}
192 * @throws ParseException
195 public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException,
197 YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
198 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier))).thenReturn(
199 prepareCnDataForSlashesBehindMountPointTest());
200 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
201 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
202 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
203 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
205 ControllerContext.getInstance().setMountService(mockMountService);
207 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
208 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
211 private YangInstanceIdentifier prepareInstanceIdentifierForList() throws URISyntaxException, ParseException {
212 List<PathArgument> parameters = new ArrayList<>();
214 Date revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-01-09");
215 URI uri = new URI("test:module");
216 QName qNameCont = QName.create(uri, revision, "cont");
217 QName qNameList = QName.create(uri, revision, "lst1");
218 QName qNameKeyList = QName.create(uri, revision, "lf11");
220 parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameCont));
221 parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameList));
222 parameters.add(new YangInstanceIdentifier.NodeIdentifierWithPredicates(qNameList, qNameKeyList,
223 "GigabitEthernet0/0/0/0"));
224 return YangInstanceIdentifier.create(parameters);
228 public void getDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException,
230 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
231 prepareCnDataForMountPointTest(true));
232 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
233 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
234 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
235 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
237 ControllerContext.getInstance().setMountService(mockMountService);
239 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
240 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
245 public void getModulesTest() throws UnsupportedEncodingException, FileNotFoundException {
246 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
248 String uri = "/modules";
250 Response response = target(uri).request("application/yang.api+json").get();
251 validateModulesResponseJson(response);
253 response = target(uri).request("application/yang.api+xml").get();
254 validateModulesResponseXml(response,schemaContextModules);
259 public void getStreamsTest() throws UnsupportedEncodingException, FileNotFoundException {
260 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
262 String uri = "/streams";
264 Response response = target(uri).request("application/yang.api+json").get();
265 String responseBody = response.readEntity(String.class);
266 assertNotNull(responseBody);
267 assertTrue(responseBody.contains("streams"));
269 response = target(uri).request("application/yang.api+xml").get();
270 Document responseXmlBody = response.readEntity(Document.class);
271 assertNotNull(responseXmlBody);
272 Element rootNode = responseXmlBody.getDocumentElement();
274 assertEquals("streams", rootNode.getLocalName());
275 assertEquals(RESTCONF_NS, rootNode.getNamespaceURI());
280 public void getModuleTest() throws FileNotFoundException, UnsupportedEncodingException {
281 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
283 String uri = "/modules/module/module2/2014-01-02";
285 Response response = target(uri).request("application/yang.api+xml").get();
286 assertEquals(200, response.getStatus());
287 Document responseXml = response.readEntity(Document.class);
291 QName qname = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
292 assertNotNull(qname);
294 assertEquals("module2", qname.getLocalName());
295 assertEquals("module:2", qname.getNamespace().toString());
296 assertEquals("2014-01-02", qname.getFormattedRevision());
298 response = target(uri).request("application/yang.api+json").get();
299 assertEquals(200, response.getStatus());
300 String responseBody = response.readEntity(String.class);
301 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
303 String[] split = responseBody.split("\"module\"");
304 assertEquals("\"module\" element is returned more then once", 2, split.length);
310 public void getOperationsTest() throws FileNotFoundException, UnsupportedEncodingException {
311 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
313 String uri = "/operations";
315 Response response = target(uri).request("application/yang.api+xml").get();
316 assertEquals(200, response.getStatus());
317 Document responseDoc = response.readEntity(Document.class);
318 validateOperationsResponseXml(responseDoc, schemaContextModules);
320 response = target(uri).request("application/yang.api+json").get();
321 assertEquals(200, response.getStatus());
322 String responseBody = response.readEntity(String.class);
323 assertTrue("Json response for /operations dummy-rpc1-module1 is incorrect",
324 validateOperationsResponseJson(responseBody, "dummy-rpc1-module1", "module1").find());
325 assertTrue("Json response for /operations dummy-rpc2-module1 is incorrect",
326 validateOperationsResponseJson(responseBody, "dummy-rpc2-module1", "module1").find());
327 assertTrue("Json response for /operations dummy-rpc1-module2 is incorrect",
328 validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
329 assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
330 validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
334 private void validateOperationsResponseXml(final Document responseDoc, final SchemaContext schemaContext) {
335 Element operationsElem = responseDoc.getDocumentElement();
336 assertEquals(RESTCONF_NS, operationsElem.getNamespaceURI());
337 assertEquals("operations", operationsElem.getLocalName());
340 HashSet<QName> foundOperations = new HashSet<>();
342 NodeList operationsList = operationsElem.getChildNodes();
343 for(int i = 0;i < operationsList.getLength();i++) {
344 org.w3c.dom.Node operation = operationsList.item(i);
346 String namespace = operation.getNamespaceURI();
347 String name = operation.getLocalName();
348 QName opQName = QName.create(URI.create(namespace), null, name);
349 foundOperations.add(opQName);
352 for(RpcDefinition schemaOp : schemaContext.getOperations()) {
353 assertTrue(foundOperations.contains(schemaOp.getQName().withoutRevision()));
358 // /operations/pathToMountPoint/yang-ext:mount
360 public void getOperationsBehindMountPointTest() throws FileNotFoundException, UnsupportedEncodingException {
361 ControllerContext controllerContext = ControllerContext.getInstance();
362 controllerContext.setGlobalSchema(schemaContextModules);
364 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
365 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
366 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
367 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
369 controllerContext.setMountService(mockMountService);
371 String uri = "/operations/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
373 Response response = target(uri).request("application/yang.api+xml").get();
374 assertEquals(200, response.getStatus());
376 Document responseDoc = response.readEntity(Document.class);
377 validateOperationsResponseXml(responseDoc, schemaContextBehindMountPoint);
379 response = target(uri).request("application/yang.api+json").get();
380 assertEquals(200, response.getStatus());
381 String responseBody = response.readEntity(String.class);
382 assertTrue("Json response for /operations/mount_point rpc-behind-module1 is incorrect",
383 validateOperationsResponseJson(responseBody, "rpc-behind-module1", "module1-behind-mount-point").find());
384 assertTrue("Json response for /operations/mount_point rpc-behind-module2 is incorrect",
385 validateOperationsResponseJson(responseBody, "rpc-behind-module2", "module2-behind-mount-point").find());
389 private Matcher validateOperationsResponseJson(final String searchIn, final String rpcName, final String moduleName) {
390 StringBuilder regex = new StringBuilder();
393 regex.append(".*\\{");
394 regex.append(".*\"");
396 // operations prefix optional
398 regex.append("ietf-restconf:");
400 // :operations prefix optional
402 regex.append("operations\"");
404 regex.append(".*\\{");
406 regex.append(".*\"" + moduleName);
408 regex.append(rpcName + "\"");
409 regex.append(".*\\[");
410 regex.append(".*null");
411 regex.append(".*\\]");
413 regex.append(".*\\}");
414 regex.append(".*\\}");
418 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
419 return ptrn.matcher(searchIn);
423 private Matcher validateOperationsResponseXml(final String searchIn, final String rpcName, final String namespace) {
424 StringBuilder regex = new StringBuilder();
428 regex.append(".*<operations");
429 regex.append(".*xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"");
433 regex.append(".*" + rpcName);
434 regex.append(".*" + namespace);
438 regex.append(".*</operations.*");
443 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
444 return ptrn.matcher(searchIn);
447 // /restconf/modules/pathToMountPoint/yang-ext:mount
449 public void getModulesBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
450 ControllerContext controllerContext = ControllerContext.getInstance();
451 controllerContext.setGlobalSchema(schemaContextModules);
453 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
454 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
455 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
456 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
458 controllerContext.setMountService(mockMountService);
460 String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
462 Response response = target(uri).request("application/yang.api+json").get();
463 assertEquals(200, response.getStatus());
464 String responseBody = response.readEntity(String.class);
467 "module1-behind-mount-point in json wasn't found",
468 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
469 responseBody).find());
471 "module2-behind-mount-point in json wasn't found",
472 prepareJsonRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point",
473 responseBody).find());
475 response = target(uri).request("application/yang.api+xml").get();
476 assertEquals(200, response.getStatus());
477 validateModulesResponseXml(response, schemaContextBehindMountPoint);
481 // /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
483 public void getModuleBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
484 ControllerContext controllerContext = ControllerContext.getInstance();
485 controllerContext.setGlobalSchema(schemaContextModules);
487 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
488 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
489 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
490 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
492 controllerContext.setMountService(mockMountService);
494 String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/module1-behind-mount-point/2014-02-03";
496 Response response = target(uri).request("application/yang.api+json").get();
497 assertEquals(200, response.getStatus());
498 String responseBody = response.readEntity(String.class);
501 "module1-behind-mount-point in json wasn't found",
502 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
503 responseBody).find());
504 String[] split = responseBody.split("\"module\"");
505 assertEquals("\"module\" element is returned more then once", 2, split.length);
507 response = target(uri).request("application/yang.api+xml").get();
508 assertEquals(200, response.getStatus());
509 Document responseXml = response.readEntity(Document.class);
511 QName module = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
513 assertEquals("module1-behind-mount-point", module.getLocalName());
514 assertEquals("2014-02-03", module.getFormattedRevision());
515 assertEquals("module:1:behind:mount:point", module.getNamespace().toString());
520 private void validateModulesResponseXml(final Response response, final SchemaContext schemaContext) {
521 assertEquals(200, response.getStatus());
522 Document responseBody = response.readEntity(Document.class);
523 NodeList moduleNodes = responseBody.getDocumentElement().getElementsByTagNameNS(RESTCONF_NS, "module");
525 assertTrue(moduleNodes.getLength() > 0);
527 HashSet<QName> foundModules = new HashSet<>();
529 for(int i=0;i < moduleNodes.getLength();i++) {
530 org.w3c.dom.Node module = moduleNodes.item(i);
532 QName name = assertedModuleXmlToModuleQName(module);
533 foundModules.add(name);
536 assertAllModules(foundModules,schemaContext);
539 private void assertAllModules(final Set<QName> foundModules, final SchemaContext schemaContext) {
540 for(Module module : schemaContext.getModules()) {
541 QName current = QName.create(module.getQNameModule(),module.getName());
542 assertTrue("Module not found in response.",foundModules.contains(current));
547 private QName assertedModuleXmlToModuleQName(final org.w3c.dom.Node module) {
548 assertEquals("module", module.getLocalName());
549 assertEquals(RESTCONF_NS, module.getNamespaceURI());
550 String revision = null;
551 String namespace = null;
555 NodeList childNodes = module.getChildNodes();
557 for(int i =0;i < childNodes.getLength(); i++) {
558 org.w3c.dom.Node child = childNodes.item(i);
559 assertEquals(RESTCONF_NS, child.getNamespaceURI());
561 switch(child.getLocalName()) {
563 assertNull("Name element appeared multiple times",name);
564 name = child.getTextContent().trim();
567 assertNull("Revision element appeared multiple times",revision);
568 revision = child.getTextContent().trim();
572 assertNull("Namespace element appeared multiple times",namespace);
573 namespace = child.getTextContent().trim();
578 assertNotNull("Revision was not part of xml",revision);
579 assertNotNull("Module namespace was not part of xml",namespace);
580 assertNotNull("Module identiffier was not part of xml",name);
583 // TODO Auto-generated method stub
585 return QName.create(namespace,revision,name);
588 private void validateModulesResponseJson(final Response response) {
589 assertEquals(200, response.getStatus());
590 String responseBody = response.readEntity(String.class);
592 assertTrue("Module1 in json wasn't found", prepareJsonRegex("module1", "2014-01-01", "module:1", responseBody)
594 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
596 assertTrue("Module3 in json wasn't found", prepareJsonRegex("module3", "2014-01-03", "module:3", responseBody)
600 private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
601 final String searchIn) {
602 StringBuilder regex = new StringBuilder();
605 regex.append(".*\\{");
606 regex.append(".*\"name\"");
608 regex.append(".*\"" + module + "\",");
610 regex.append(".*\"revision\"");
612 regex.append(".*\"" + revision + "\",");
614 regex.append(".*\"namespace\"");
616 regex.append(".*\"" + namespace + "\"");
618 regex.append(".*\\}");
622 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
623 return ptrn.matcher(searchIn);
628 private void prepareMockForModulesTest(final ControllerContext mockedControllerContext)
629 throws FileNotFoundException {
630 SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
631 mockedControllerContext.setGlobalSchema(schemaContext);
632 // when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
635 private int get(final String uri, final String mediaType) {
636 return target(uri).request(mediaType).get().getStatus();
646 private NormalizedNode prepareCnDataForMountPointTest(boolean wrapToCont) throws URISyntaxException, ParseException {
647 String testModuleDate = "2014-01-09";
648 ContainerNode contChild = Builders
650 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont1", "test:module", testModuleDate))
652 Builders.leafBuilder()
653 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", testModuleDate))
654 .withValue("lf11 value").build()).build();
657 return Builders.containerBuilder()
658 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont", "test:module", testModuleDate))
659 .withChild(contChild).build();
665 private void mockReadOperationalDataMethod() {
666 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
669 private void mockReadConfigurationDataMethod() {
670 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
673 private NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws ParseException {
674 return ImmutableMapEntryNodeBuilder
677 TestUtils.getNodeIdentifierPredicate("lst1", "test:module", "2014-01-09", "lf11",
678 "GigabitEthernet0/0/0/0"))
680 ImmutableLeafNodeBuilder.create()
681 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", "2014-01-09"))
682 .withValue("GigabitEthernet0/0/0/0").build()).build();
687 * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
689 * @throws UnsupportedEncodingException
692 public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
693 getDataWithUriIncludeWhiteCharsParameter("config");
694 getDataWithUriIncludeWhiteCharsParameter("operational");
697 private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws UnsupportedEncodingException {
698 mockReadConfigurationDataMethod();
699 mockReadOperationalDataMethod();
700 String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
701 Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
702 String xmlData = response.readEntity(String.class);
704 Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
705 Matcher matcher = pattern.matcher(xmlData);
706 // XML element can't surrounded with white character (e.g "> " or
708 assertFalse(matcher.matches());
710 response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
711 String jsonData = response.readEntity(String.class);
712 pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
713 matcher = pattern.matcher(jsonData);
714 // JSON element can't surrounded with white character (e.g "} ", " {",
715 // "] ", " [", " :" or ": ")
716 assertFalse(matcher.matches());
720 public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
722 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
724 CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
725 toNestedQName("depth1-cont"),
727 toNestedQName("depth2-cont1"),
729 toNestedQName("depth3-cont1"),
730 toCompositeNodeData(toNestedQName("depth4-cont1"),
731 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
732 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
733 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
735 toNestedQName("depth2-cont2"),
737 toNestedQName("depth3-cont2"),
738 toCompositeNodeData(toNestedQName("depth4-cont2"),
739 toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
740 toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
741 toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
742 toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
744 Module module = TestUtils.findModule(schemaContextModules.getModules(), "nested-module");
745 assertNotNull(module);
747 DataSchemaNode dataSchemaNode = TestUtils.resolveDataSchemaNode("depth1-cont", module);
748 assertNotNull(dataSchemaNode);
750 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(
751 TestUtils.compositeNodeToDatastoreNormalizedNode(depth1Cont, dataSchemaNode));
753 // Test config with depth 1
755 Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
756 .request("application/xml").get();
758 verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
760 // Test config with depth 2
762 response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
766 // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
767 // Response mr=mock(Response.class);
768 // when(mr.getEntity()).thenReturn( new
769 // java.io.StringBufferInputStream(xml) );
773 expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
774 expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
776 // Test config with depth 3
778 response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
785 expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
786 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
787 expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
788 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
789 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
791 // Test config with depth 4
793 response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
802 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
803 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
804 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
807 expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
808 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
809 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
810 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
812 // Test config with depth 5
814 response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
825 expectContainer("depth4-cont1",
826 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
827 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
828 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
833 expectContainer("depth4-cont2",
834 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
835 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
836 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
837 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
839 // Test config with depth unbounded
841 response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
842 .request("application/xml").get();
852 expectContainer("depth4-cont1",
853 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
854 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
855 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
860 expectContainer("depth4-cont2",
861 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
862 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
863 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
864 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
868 CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
869 toNestedQName("depth2-cont1"),
871 toNestedQName("depth3-cont1"),
872 toCompositeNodeData(toNestedQName("depth4-cont1"),
873 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
874 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
875 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
877 assertTrue(dataSchemaNode instanceof DataNodeContainer);
878 DataSchemaNode depth2cont1Schema = null;
879 for (DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
880 if (childNode.getQName().getLocalName().equals("depth2-cont1")) {
881 depth2cont1Schema = childNode;
885 assertNotNull(depth2Cont1);
887 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(
888 TestUtils.compositeNodeToDatastoreNormalizedNode(depth2Cont1, depth2cont1Schema));
890 response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
891 .request("application/xml").get();
897 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
898 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
899 expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
903 * Tests behavior when invalid value of depth URI parameter
906 public void getDataWithInvalidDepthParameterTest() {
908 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
910 final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
911 paramMap.putSingle("depth", "1o");
912 UriInfo mockInfo = mock(UriInfo.class);
913 when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
915 public MultivaluedMap<String, String> answer(InvocationOnMock invocation) {
920 getDataWithInvalidDepthParameterTest(mockInfo);
922 paramMap.putSingle("depth", "0");
923 getDataWithInvalidDepthParameterTest(mockInfo);
925 paramMap.putSingle("depth", "-1");
926 getDataWithInvalidDepthParameterTest(mockInfo);
929 private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
931 QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
932 YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
933 NormalizedNode value = (NormalizedNode<?,?>)(Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build());
934 when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value);
935 restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
936 fail("Expected RestconfDocumentedException");
937 } catch (RestconfDocumentedException e) {
938 assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
939 .getErrorMessage().contains("depth"));
943 private void verifyXMLResponse(final Response response, final NodeData nodeData) {
944 Document doc = response.readEntity(Document.class);
945 // Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
946 // System.out.println();
947 assertNotNull("Could not parse XML document", doc);
949 // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
951 verifyContainerElement(doc.getDocumentElement(), nodeData);
954 @SuppressWarnings("unchecked")
955 private void verifyContainerElement(final Element element, final NodeData nodeData) {
957 assertEquals("Element local name", nodeData.key, element.getLocalName());
959 NodeList childNodes = element.getChildNodes();
960 if (nodeData.data == null) { // empty container
961 assertTrue("Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
965 Map<String, NodeData> expChildMap = Maps.newHashMap();
966 for (NodeData expChild : (List<NodeData>) nodeData.data) {
967 expChildMap.put(expChild.key.toString(), expChild);
970 for (int i = 0; i < childNodes.getLength(); i++) {
971 org.w3c.dom.Node actualChild = childNodes.item(i);
972 if (!(actualChild instanceof Element)) {
976 Element actualElement = (Element) actualChild;
977 NodeData expChild = expChildMap.remove(actualElement.getLocalName());
979 "Unexpected child element for parent \"" + element.getLocalName() + "\": "
980 + actualElement.getLocalName(), expChild);
982 if (expChild.data == null || expChild.data instanceof List) {
983 verifyContainerElement(actualElement, expChild);
985 assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data,
986 actualElement.getTextContent());
990 if (!expChildMap.isEmpty()) {
991 fail("Missing elements for parent \"" + element.getLocalName() + "\": " + expChildMap.keySet());
995 private NodeData expectContainer(final String name, final NodeData... childData) {
996 return new NodeData(name, Lists.newArrayList(childData));
999 private NodeData expectEmptyContainer(final String name) {
1000 return new NodeData(name, null);
1003 private NodeData expectLeaf(final String name, final Object value) {
1004 return new NodeData(name, value);
1007 private QName toNestedQName(final String localName) {
1008 return QName.create("urn:nested:module", "2014-06-3", localName);
1011 @SuppressWarnings("unchecked")
1012 private CompositeNode toCompositeNode(final NodeData nodeData) {
1013 CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
1014 builder.setQName((QName) nodeData.key);
1016 for (NodeData child : (List<NodeData>) nodeData.data) {
1017 if (child.data instanceof List) {
1018 builder.add(toCompositeNode(child));
1020 builder.addLeaf((QName) child.key, child.data);
1024 return builder.toInstance();
1027 private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
1028 return new NodeData(key, Lists.newArrayList(childData));
1031 private NodeData toSimpleNodeData(final QName key, final Object value) {
1032 return new NodeData(key, value);