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.Ignore;
48 import org.junit.Test;
49 import org.mockito.invocation.InvocationOnMock;
50 import org.mockito.stubbing.Answer;
51 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
52 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
53 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
54 import org.opendaylight.controller.sal.rest.impl.RestconfApplication;
55 import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper;
56 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
57 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
58 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
59 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
60 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
61 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
62 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
63 import org.opendaylight.yangtools.yang.common.QName;
64 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
68 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
71 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
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.util.CompositeNodeBuilder;
75 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
76 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.Module;
78 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
79 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
80 import org.w3c.dom.Document;
81 import org.w3c.dom.Element;
82 import org.w3c.dom.NodeList;
84 public class RestGetOperationTest extends JerseyTest {
86 static class NodeData {
88 Object data; // List for a CompositeNode, value Object for a SimpleNode
90 NodeData(final Object key, final Object data) {
96 private static BrokerFacade brokerFacade;
97 private static RestconfImpl restconfImpl;
98 private static SchemaContext schemaContextYangsIetf;
99 private static SchemaContext schemaContextTestModule;
100 private static NormalizedNode answerFromGet;
102 private static SchemaContext schemaContextModules;
103 private static SchemaContext schemaContextBehindMountPoint;
105 private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf";
108 public static void init() throws FileNotFoundException, ParseException {
109 schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
110 schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
111 ControllerContext controllerContext = ControllerContext.getInstance();
112 controllerContext.setSchemas(schemaContextYangsIetf);
113 brokerFacade = mock(BrokerFacade.class);
114 restconfImpl = RestconfImpl.getInstance();
115 restconfImpl.setBroker(brokerFacade);
116 restconfImpl.setControllerContext(controllerContext);
117 answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
119 schemaContextModules = TestUtils.loadSchemaContext("/modules");
120 schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
124 protected Application configure() {
125 /* enable/disable Jersey logs to console */
126 // enable(TestProperties.LOG_TRAFFIC);
127 // enable(TestProperties.DUMP_ENTITY);
128 // enable(TestProperties.RECORD_LOG_LEVEL);
129 // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
130 ResourceConfig resourceConfig = new ResourceConfig();
131 resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
132 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
133 JsonToCompositeNodeProvider.INSTANCE);
134 resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
135 resourceConfig.registerClasses(new RestconfApplication().getClasses());
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 return ImmutableMapEntryNodeBuilder
680 TestUtils.getNodeIdentifierPredicate("lst1", "test:module", "2014-01-09", "lf11",
681 "GigabitEthernet0/0/0/0"))
683 ImmutableLeafNodeBuilder.create()
684 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", "2014-01-09"))
685 .withValue("GigabitEthernet0/0/0/0").build()).build();
690 * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
692 * @throws UnsupportedEncodingException
695 public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
696 getDataWithUriIncludeWhiteCharsParameter("config");
697 getDataWithUriIncludeWhiteCharsParameter("operational");
700 private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws UnsupportedEncodingException {
701 mockReadConfigurationDataMethod();
702 mockReadOperationalDataMethod();
703 String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
704 Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
705 String xmlData = response.readEntity(String.class);
707 Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
708 Matcher matcher = pattern.matcher(xmlData);
709 // XML element can't surrounded with white character (e.g "> " or
711 assertFalse(matcher.matches());
713 response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
714 String jsonData = response.readEntity(String.class);
715 pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
716 matcher = pattern.matcher(jsonData);
717 // JSON element can't surrounded with white character (e.g "} ", " {",
718 // "] ", " [", " :" or ": ")
719 assertFalse(matcher.matches());
724 public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
726 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
728 CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
729 toNestedQName("depth1-cont"),
731 toNestedQName("depth2-cont1"),
733 toNestedQName("depth3-cont1"),
734 toCompositeNodeData(toNestedQName("depth4-cont1"),
735 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
736 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
737 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
739 toNestedQName("depth2-cont2"),
741 toNestedQName("depth3-cont2"),
742 toCompositeNodeData(toNestedQName("depth4-cont2"),
743 toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
744 toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
745 toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
746 toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
748 Module module = TestUtils.findModule(schemaContextModules.getModules(), "nested-module");
749 assertNotNull(module);
751 DataSchemaNode dataSchemaNode = TestUtils.resolveDataSchemaNode("depth1-cont", module);
752 assertNotNull(dataSchemaNode);
754 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(
755 TestUtils.compositeNodeToDatastoreNormalizedNode(depth1Cont, dataSchemaNode));
757 // Test config with depth 1
759 Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
760 .request("application/xml").get();
762 verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
764 // Test config with depth 2
766 response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
770 // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
771 // Response mr=mock(Response.class);
772 // when(mr.getEntity()).thenReturn( new
773 // java.io.StringBufferInputStream(xml) );
777 expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
778 expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
780 // Test config with depth 3
782 response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
789 expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
790 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
791 expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
792 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
793 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
795 // Test config with depth 4
797 response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
806 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
807 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
808 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
811 expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
812 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
813 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
814 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
816 // Test config with depth 5
818 response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
829 expectContainer("depth4-cont1",
830 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
831 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
832 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
837 expectContainer("depth4-cont2",
838 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
839 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
840 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
841 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
843 // Test config with depth unbounded
845 response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
846 .request("application/xml").get();
856 expectContainer("depth4-cont1",
857 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
858 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
859 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
864 expectContainer("depth4-cont2",
865 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
866 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
867 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
868 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
872 CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
873 toNestedQName("depth2-cont1"),
875 toNestedQName("depth3-cont1"),
876 toCompositeNodeData(toNestedQName("depth4-cont1"),
877 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
878 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
879 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
881 assertTrue(dataSchemaNode instanceof DataNodeContainer);
882 DataSchemaNode depth2cont1Schema = null;
883 for (DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
884 if (childNode.getQName().getLocalName().equals("depth2-cont1")) {
885 depth2cont1Schema = childNode;
889 assertNotNull(depth2Cont1);
891 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(
892 TestUtils.compositeNodeToDatastoreNormalizedNode(depth2Cont1, depth2cont1Schema));
894 response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
895 .request("application/xml").get();
901 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
902 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
903 expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
907 * Tests behavior when invalid value of depth URI parameter
911 public void getDataWithInvalidDepthParameterTest() {
913 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
915 final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
916 paramMap.putSingle("depth", "1o");
917 UriInfo mockInfo = mock(UriInfo.class);
918 when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
920 public MultivaluedMap<String, String> answer(InvocationOnMock invocation) {
925 getDataWithInvalidDepthParameterTest(mockInfo);
927 paramMap.putSingle("depth", "0");
928 getDataWithInvalidDepthParameterTest(mockInfo);
930 paramMap.putSingle("depth", "-1");
931 getDataWithInvalidDepthParameterTest(mockInfo);
934 private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
936 QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
937 YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
938 NormalizedNode value = (Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build());
939 when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value);
940 restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
941 fail("Expected RestconfDocumentedException");
942 } catch (RestconfDocumentedException e) {
943 assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
944 .getErrorMessage().contains("depth"));
948 private void verifyXMLResponse(final Response response, final NodeData nodeData) {
949 Document doc = response.readEntity(Document.class);
950 // Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
951 // System.out.println();
952 assertNotNull("Could not parse XML document", doc);
954 // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
956 verifyContainerElement(doc.getDocumentElement(), nodeData);
959 @SuppressWarnings("unchecked")
960 private void verifyContainerElement(final Element element, final NodeData nodeData) {
962 assertEquals("Element local name", nodeData.key, element.getLocalName());
964 NodeList childNodes = element.getChildNodes();
965 if (nodeData.data == null) { // empty container
966 assertTrue("Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
970 Map<String, NodeData> expChildMap = Maps.newHashMap();
971 for (NodeData expChild : (List<NodeData>) nodeData.data) {
972 expChildMap.put(expChild.key.toString(), expChild);
975 for (int i = 0; i < childNodes.getLength(); i++) {
976 org.w3c.dom.Node actualChild = childNodes.item(i);
977 if (!(actualChild instanceof Element)) {
981 Element actualElement = (Element) actualChild;
982 NodeData expChild = expChildMap.remove(actualElement.getLocalName());
984 "Unexpected child element for parent \"" + element.getLocalName() + "\": "
985 + actualElement.getLocalName(), expChild);
987 if (expChild.data == null || expChild.data instanceof List) {
988 verifyContainerElement(actualElement, expChild);
990 assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data,
991 actualElement.getTextContent());
995 if (!expChildMap.isEmpty()) {
996 fail("Missing elements for parent \"" + element.getLocalName() + "\": " + expChildMap.keySet());
1000 private NodeData expectContainer(final String name, final NodeData... childData) {
1001 return new NodeData(name, Lists.newArrayList(childData));
1004 private NodeData expectEmptyContainer(final String name) {
1005 return new NodeData(name, null);
1008 private NodeData expectLeaf(final String name, final Object value) {
1009 return new NodeData(name, value);
1012 private QName toNestedQName(final String localName) {
1013 return QName.create("urn:nested:module", "2014-06-3", localName);
1016 @SuppressWarnings("unchecked")
1017 private CompositeNode toCompositeNode(final NodeData nodeData) {
1018 CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
1019 builder.setQName((QName) nodeData.key);
1021 for (NodeData child : (List<NodeData>) nodeData.data) {
1022 if (child.data instanceof List) {
1023 builder.add(toCompositeNode(child));
1025 builder.addLeaf((QName) child.key, child.data);
1029 return builder.toInstance();
1032 private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
1033 return new NodeData(key, Lists.newArrayList(childData));
1036 private NodeData toSimpleNodeData(final QName key, final Object value) {
1037 return new NodeData(key, value);