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.MapEntryNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
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.api.CollectionNodeBuilder;
73 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
74 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
75 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
76 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
77 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
78 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.Module;
80 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
81 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
82 import org.w3c.dom.Document;
83 import org.w3c.dom.Element;
84 import org.w3c.dom.NodeList;
86 public class RestGetOperationTest extends JerseyTest {
88 static class NodeData {
90 Object data; // List for a CompositeNode, value Object for a SimpleNode
92 NodeData(final Object key, final Object data) {
98 private static BrokerFacade brokerFacade;
99 private static RestconfImpl restconfImpl;
100 private static SchemaContext schemaContextYangsIetf;
101 private static SchemaContext schemaContextTestModule;
102 private static NormalizedNode answerFromGet;
104 private static SchemaContext schemaContextModules;
105 private static SchemaContext schemaContextBehindMountPoint;
107 private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf";
110 public static void init() throws FileNotFoundException, ParseException {
111 schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
112 schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
113 ControllerContext controllerContext = ControllerContext.getInstance();
114 controllerContext.setSchemas(schemaContextYangsIetf);
115 brokerFacade = mock(BrokerFacade.class);
116 restconfImpl = RestconfImpl.getInstance();
117 restconfImpl.setBroker(brokerFacade);
118 restconfImpl.setControllerContext(controllerContext);
119 answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
121 schemaContextModules = TestUtils.loadSchemaContext("/modules");
122 schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
126 protected Application configure() {
127 /* enable/disable Jersey logs to console */
128 // enable(TestProperties.LOG_TRAFFIC);
129 // enable(TestProperties.DUMP_ENTITY);
130 // enable(TestProperties.RECORD_LOG_LEVEL);
131 // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
132 ResourceConfig resourceConfig = new ResourceConfig();
133 resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
134 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
135 JsonToCompositeNodeProvider.INSTANCE);
136 resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
137 return resourceConfig;
141 * Tests of status codes for "/operational/{identifier}".
144 public void getOperationalStatusCodes() throws UnsupportedEncodingException {
145 mockReadOperationalDataMethod();
146 String uri = "/operational/ietf-interfaces:interfaces/interface/eth0";
147 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
149 uri = "/operational/wrong-module:interfaces/interface/eth0";
150 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
154 * Tests of status codes for "/config/{identifier}".
157 public void getConfigStatusCodes() throws UnsupportedEncodingException {
158 mockReadConfigurationDataMethod();
159 String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
160 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
162 uri = "/config/wrong-module:interfaces/interface/eth0";
163 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
167 * MountPoint test. URI represents mount point.
170 public void getDataWithUrlMountPoint() throws UnsupportedEncodingException, URISyntaxException, ParseException {
171 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
172 prepareCnDataForMountPointTest(false));
173 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
174 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
175 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
176 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
178 ControllerContext.getInstance().setMountService(mockMountService);
180 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/cont1";
181 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
183 uri = "/config/ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
184 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
188 * MountPoint test. URI represents mount point.
190 * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
191 * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
192 * InstanceIdentifier parameter in method
193 * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, YangInstanceIdentifier)} which is called in
194 * method {@link RestconfImpl#readConfigurationData}
196 * @throws ParseException
199 public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException,
201 YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
202 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier))).thenReturn(
203 prepareCnDataForSlashesBehindMountPointTest());
204 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
205 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
206 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
207 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
209 ControllerContext.getInstance().setMountService(mockMountService);
211 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
212 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
215 private YangInstanceIdentifier prepareInstanceIdentifierForList() throws URISyntaxException, ParseException {
216 List<PathArgument> parameters = new ArrayList<>();
218 Date revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-01-09");
219 URI uri = new URI("test:module");
220 QName qNameCont = QName.create(uri, revision, "cont");
221 QName qNameList = QName.create(uri, revision, "lst1");
222 QName qNameKeyList = QName.create(uri, revision, "lf11");
224 parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameCont));
225 parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameList));
226 parameters.add(new YangInstanceIdentifier.NodeIdentifierWithPredicates(qNameList, qNameKeyList,
227 "GigabitEthernet0/0/0/0"));
228 return YangInstanceIdentifier.create(parameters);
232 public void getDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException,
234 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
235 prepareCnDataForMountPointTest(true));
236 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
237 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
238 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
239 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
241 ControllerContext.getInstance().setMountService(mockMountService);
243 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
244 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
249 public void getModulesTest() throws UnsupportedEncodingException, FileNotFoundException {
250 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
252 String uri = "/modules";
254 Response response = target(uri).request("application/yang.api+json").get();
255 validateModulesResponseJson(response);
257 response = target(uri).request("application/yang.api+xml").get();
258 validateModulesResponseXml(response,schemaContextModules);
263 public void getStreamsTest() throws UnsupportedEncodingException, FileNotFoundException {
264 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
266 String uri = "/streams";
268 Response response = target(uri).request("application/yang.api+json").get();
269 String responseBody = response.readEntity(String.class);
270 assertNotNull(responseBody);
271 assertTrue(responseBody.contains("streams"));
273 response = target(uri).request("application/yang.api+xml").get();
274 Document responseXmlBody = response.readEntity(Document.class);
275 assertNotNull(responseXmlBody);
276 Element rootNode = responseXmlBody.getDocumentElement();
278 assertEquals("streams", rootNode.getLocalName());
279 assertEquals(RESTCONF_NS, rootNode.getNamespaceURI());
284 public void getModuleTest() throws FileNotFoundException, UnsupportedEncodingException {
285 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
287 String uri = "/modules/module/module2/2014-01-02";
289 Response response = target(uri).request("application/yang.api+xml").get();
290 assertEquals(200, response.getStatus());
291 Document responseXml = response.readEntity(Document.class);
295 QName qname = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
296 assertNotNull(qname);
298 assertEquals("module2", qname.getLocalName());
299 assertEquals("module:2", qname.getNamespace().toString());
300 assertEquals("2014-01-02", qname.getFormattedRevision());
302 response = target(uri).request("application/yang.api+json").get();
303 assertEquals(200, response.getStatus());
304 String responseBody = response.readEntity(String.class);
305 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
307 String[] split = responseBody.split("\"module\"");
308 assertEquals("\"module\" element is returned more then once", 2, split.length);
314 public void getOperationsTest() throws FileNotFoundException, UnsupportedEncodingException {
315 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
317 String uri = "/operations";
319 Response response = target(uri).request("application/yang.api+xml").get();
320 assertEquals(200, response.getStatus());
321 Document responseDoc = response.readEntity(Document.class);
322 validateOperationsResponseXml(responseDoc, schemaContextModules);
324 response = target(uri).request("application/yang.api+json").get();
325 assertEquals(200, response.getStatus());
326 String responseBody = response.readEntity(String.class);
327 assertTrue("Json response for /operations dummy-rpc1-module1 is incorrect",
328 validateOperationsResponseJson(responseBody, "dummy-rpc1-module1", "module1").find());
329 assertTrue("Json response for /operations dummy-rpc2-module1 is incorrect",
330 validateOperationsResponseJson(responseBody, "dummy-rpc2-module1", "module1").find());
331 assertTrue("Json response for /operations dummy-rpc1-module2 is incorrect",
332 validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
333 assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
334 validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
338 private void validateOperationsResponseXml(final Document responseDoc, final SchemaContext schemaContext) {
339 Element operationsElem = responseDoc.getDocumentElement();
340 assertEquals(RESTCONF_NS, operationsElem.getNamespaceURI());
341 assertEquals("operations", operationsElem.getLocalName());
344 HashSet<QName> foundOperations = new HashSet<>();
346 NodeList operationsList = operationsElem.getChildNodes();
347 for(int i = 0;i < operationsList.getLength();i++) {
348 org.w3c.dom.Node operation = operationsList.item(i);
350 String namespace = operation.getNamespaceURI();
351 String name = operation.getLocalName();
352 QName opQName = QName.create(URI.create(namespace), null, name);
353 foundOperations.add(opQName);
356 for(RpcDefinition schemaOp : schemaContext.getOperations()) {
357 assertTrue(foundOperations.contains(schemaOp.getQName().withoutRevision()));
362 // /operations/pathToMountPoint/yang-ext:mount
364 public void getOperationsBehindMountPointTest() throws FileNotFoundException, UnsupportedEncodingException {
365 ControllerContext controllerContext = ControllerContext.getInstance();
366 controllerContext.setGlobalSchema(schemaContextModules);
368 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
369 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
370 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
371 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
373 controllerContext.setMountService(mockMountService);
375 String uri = "/operations/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
377 Response response = target(uri).request("application/yang.api+xml").get();
378 assertEquals(200, response.getStatus());
380 Document responseDoc = response.readEntity(Document.class);
381 validateOperationsResponseXml(responseDoc, schemaContextBehindMountPoint);
383 response = target(uri).request("application/yang.api+json").get();
384 assertEquals(200, response.getStatus());
385 String responseBody = response.readEntity(String.class);
386 assertTrue("Json response for /operations/mount_point rpc-behind-module1 is incorrect",
387 validateOperationsResponseJson(responseBody, "rpc-behind-module1", "module1-behind-mount-point").find());
388 assertTrue("Json response for /operations/mount_point rpc-behind-module2 is incorrect",
389 validateOperationsResponseJson(responseBody, "rpc-behind-module2", "module2-behind-mount-point").find());
393 private Matcher validateOperationsResponseJson(final String searchIn, final String rpcName, final String moduleName) {
394 StringBuilder regex = new StringBuilder();
397 regex.append(".*\\{");
398 regex.append(".*\"");
400 // operations prefix optional
402 regex.append("ietf-restconf:");
404 // :operations prefix optional
406 regex.append("operations\"");
408 regex.append(".*\\{");
410 regex.append(".*\"" + moduleName);
412 regex.append(rpcName + "\"");
413 regex.append(".*\\[");
414 regex.append(".*null");
415 regex.append(".*\\]");
417 regex.append(".*\\}");
418 regex.append(".*\\}");
422 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
423 return ptrn.matcher(searchIn);
427 private Matcher validateOperationsResponseXml(final String searchIn, final String rpcName, final String namespace) {
428 StringBuilder regex = new StringBuilder();
432 regex.append(".*<operations");
433 regex.append(".*xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"");
437 regex.append(".*" + rpcName);
438 regex.append(".*" + namespace);
442 regex.append(".*</operations.*");
447 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
448 return ptrn.matcher(searchIn);
451 // /restconf/modules/pathToMountPoint/yang-ext:mount
453 public void getModulesBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
454 ControllerContext controllerContext = ControllerContext.getInstance();
455 controllerContext.setGlobalSchema(schemaContextModules);
457 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
458 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
459 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
460 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
462 controllerContext.setMountService(mockMountService);
464 String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
466 Response response = target(uri).request("application/yang.api+json").get();
467 assertEquals(200, response.getStatus());
468 String responseBody = response.readEntity(String.class);
471 "module1-behind-mount-point in json wasn't found",
472 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
473 responseBody).find());
475 "module2-behind-mount-point in json wasn't found",
476 prepareJsonRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point",
477 responseBody).find());
479 response = target(uri).request("application/yang.api+xml").get();
480 assertEquals(200, response.getStatus());
481 validateModulesResponseXml(response, schemaContextBehindMountPoint);
485 // /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
487 public void getModuleBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
488 ControllerContext controllerContext = ControllerContext.getInstance();
489 controllerContext.setGlobalSchema(schemaContextModules);
491 DOMMountPoint mountInstance = mock(DOMMountPoint.class);
492 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
493 DOMMountPointService mockMountService = mock(DOMMountPointService.class);
494 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
496 controllerContext.setMountService(mockMountService);
498 String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/module1-behind-mount-point/2014-02-03";
500 Response response = target(uri).request("application/yang.api+json").get();
501 assertEquals(200, response.getStatus());
502 String responseBody = response.readEntity(String.class);
505 "module1-behind-mount-point in json wasn't found",
506 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
507 responseBody).find());
508 String[] split = responseBody.split("\"module\"");
509 assertEquals("\"module\" element is returned more then once", 2, split.length);
511 response = target(uri).request("application/yang.api+xml").get();
512 assertEquals(200, response.getStatus());
513 Document responseXml = response.readEntity(Document.class);
515 QName module = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
517 assertEquals("module1-behind-mount-point", module.getLocalName());
518 assertEquals("2014-02-03", module.getFormattedRevision());
519 assertEquals("module:1:behind:mount:point", module.getNamespace().toString());
524 private void validateModulesResponseXml(final Response response, final SchemaContext schemaContext) {
525 assertEquals(200, response.getStatus());
526 Document responseBody = response.readEntity(Document.class);
527 NodeList moduleNodes = responseBody.getDocumentElement().getElementsByTagNameNS(RESTCONF_NS, "module");
529 assertTrue(moduleNodes.getLength() > 0);
531 HashSet<QName> foundModules = new HashSet<>();
533 for(int i=0;i < moduleNodes.getLength();i++) {
534 org.w3c.dom.Node module = moduleNodes.item(i);
536 QName name = assertedModuleXmlToModuleQName(module);
537 foundModules.add(name);
540 assertAllModules(foundModules,schemaContext);
543 private void assertAllModules(final Set<QName> foundModules, final SchemaContext schemaContext) {
544 for(Module module : schemaContext.getModules()) {
545 QName current = QName.create(module.getQNameModule(),module.getName());
546 assertTrue("Module not found in response.",foundModules.contains(current));
551 private QName assertedModuleXmlToModuleQName(final org.w3c.dom.Node module) {
552 assertEquals("module", module.getLocalName());
553 assertEquals(RESTCONF_NS, module.getNamespaceURI());
554 String revision = null;
555 String namespace = null;
559 NodeList childNodes = module.getChildNodes();
561 for(int i =0;i < childNodes.getLength(); i++) {
562 org.w3c.dom.Node child = childNodes.item(i);
563 assertEquals(RESTCONF_NS, child.getNamespaceURI());
565 switch(child.getLocalName()) {
567 assertNull("Name element appeared multiple times",name);
568 name = child.getTextContent().trim();
571 assertNull("Revision element appeared multiple times",revision);
572 revision = child.getTextContent().trim();
576 assertNull("Namespace element appeared multiple times",namespace);
577 namespace = child.getTextContent().trim();
582 assertNotNull("Revision was not part of xml",revision);
583 assertNotNull("Module namespace was not part of xml",namespace);
584 assertNotNull("Module identiffier was not part of xml",name);
587 // TODO Auto-generated method stub
589 return QName.create(namespace,revision,name);
592 private void validateModulesResponseJson(final Response response) {
593 assertEquals(200, response.getStatus());
594 String responseBody = response.readEntity(String.class);
596 assertTrue("Module1 in json wasn't found", prepareJsonRegex("module1", "2014-01-01", "module:1", responseBody)
598 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
600 assertTrue("Module3 in json wasn't found", prepareJsonRegex("module3", "2014-01-03", "module:3", responseBody)
604 private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
605 final String searchIn) {
606 StringBuilder regex = new StringBuilder();
609 regex.append(".*\\{");
610 regex.append(".*\"name\"");
612 regex.append(".*\"" + module + "\",");
614 regex.append(".*\"revision\"");
616 regex.append(".*\"" + revision + "\",");
618 regex.append(".*\"namespace\"");
620 regex.append(".*\"" + namespace + "\"");
622 regex.append(".*\\}");
626 Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
627 return ptrn.matcher(searchIn);
632 private void prepareMockForModulesTest(final ControllerContext mockedControllerContext)
633 throws FileNotFoundException {
634 SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
635 mockedControllerContext.setGlobalSchema(schemaContext);
636 // when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
639 private int get(final String uri, final String mediaType) {
640 return target(uri).request(mediaType).get().getStatus();
650 private NormalizedNode prepareCnDataForMountPointTest(boolean wrapToCont) throws URISyntaxException, ParseException {
651 String testModuleDate = "2014-01-09";
652 ContainerNode contChild = Builders
654 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont1", "test:module", testModuleDate))
656 Builders.leafBuilder()
657 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", testModuleDate))
658 .withValue("lf11 value").build()).build();
661 return Builders.containerBuilder()
662 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont", "test:module", testModuleDate))
663 .withChild(contChild).build();
669 private void mockReadOperationalDataMethod() {
670 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
673 private void mockReadConfigurationDataMethod() {
674 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
677 private NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws ParseException {
678 CollectionNodeBuilder<MapEntryNode, MapNode> lst1 = ImmutableMapNodeBuilder.create();
679 lst1.withNodeIdentifier(TestUtils.getNodeIdentifier("lst1", "test:module", "2014-01-09"));
680 lst1.withChild(ImmutableMapEntryNodeBuilder
683 TestUtils.getNodeIdentifierPredicate("lst1", "test:module", "2014-01-09", "lf11",
684 "GigabitEthernet0/0/0/0"))
686 ImmutableLeafNodeBuilder.create()
687 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", "2014-01-09"))
688 .withValue("GigabitEthernet0/0/0/0").build()).build());
694 * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
696 * @throws UnsupportedEncodingException
699 public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
700 getDataWithUriIncludeWhiteCharsParameter("config");
701 getDataWithUriIncludeWhiteCharsParameter("operational");
704 private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws UnsupportedEncodingException {
705 mockReadConfigurationDataMethod();
706 mockReadOperationalDataMethod();
707 String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
708 Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
709 String xmlData = response.readEntity(String.class);
711 Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
712 Matcher matcher = pattern.matcher(xmlData);
713 // XML element can't surrounded with white character (e.g "> " or
715 assertFalse(matcher.matches());
717 response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
718 String jsonData = response.readEntity(String.class);
719 pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
720 matcher = pattern.matcher(jsonData);
721 // JSON element can't surrounded with white character (e.g "} ", " {",
722 // "] ", " [", " :" or ": ")
723 assertFalse(matcher.matches());
727 public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
729 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
731 CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
732 toNestedQName("depth1-cont"),
734 toNestedQName("depth2-cont1"),
736 toNestedQName("depth3-cont1"),
737 toCompositeNodeData(toNestedQName("depth4-cont1"),
738 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
739 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
740 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
742 toNestedQName("depth2-cont2"),
744 toNestedQName("depth3-cont2"),
745 toCompositeNodeData(toNestedQName("depth4-cont2"),
746 toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
747 toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
748 toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
749 toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
751 Module module = TestUtils.findModule(schemaContextModules.getModules(), "nested-module");
752 assertNotNull(module);
754 DataSchemaNode dataSchemaNode = TestUtils.resolveDataSchemaNode("depth1-cont", module);
755 assertNotNull(dataSchemaNode);
757 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(
758 TestUtils.compositeNodeToDatastoreNormalizedNode(depth1Cont, dataSchemaNode));
760 // Test config with depth 1
762 Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
763 .request("application/xml").get();
765 verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
767 // Test config with depth 2
769 response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
773 // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
774 // Response mr=mock(Response.class);
775 // when(mr.getEntity()).thenReturn( new
776 // java.io.StringBufferInputStream(xml) );
780 expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
781 expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
783 // Test config with depth 3
785 response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
792 expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
793 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
794 expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
795 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
796 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
798 // Test config with depth 4
800 response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
809 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
810 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
811 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
814 expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
815 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
816 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
817 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
819 // Test config with depth 5
821 response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
832 expectContainer("depth4-cont1",
833 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
834 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
835 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
840 expectContainer("depth4-cont2",
841 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
842 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
843 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
844 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
846 // Test config with depth unbounded
848 response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
849 .request("application/xml").get();
859 expectContainer("depth4-cont1",
860 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
861 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
862 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
867 expectContainer("depth4-cont2",
868 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
869 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
870 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
871 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
875 CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
876 toNestedQName("depth2-cont1"),
878 toNestedQName("depth3-cont1"),
879 toCompositeNodeData(toNestedQName("depth4-cont1"),
880 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
881 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
882 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
884 assertTrue(dataSchemaNode instanceof DataNodeContainer);
885 DataSchemaNode depth2cont1Schema = null;
886 for (DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
887 if (childNode.getQName().getLocalName().equals("depth2-cont1")) {
888 depth2cont1Schema = childNode;
892 assertNotNull(depth2Cont1);
894 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(
895 TestUtils.compositeNodeToDatastoreNormalizedNode(depth2Cont1, depth2cont1Schema));
897 response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
898 .request("application/xml").get();
904 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
905 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
906 expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
910 * Tests behavior when invalid value of depth URI parameter
913 public void getDataWithInvalidDepthParameterTest() {
915 ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
917 final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
918 paramMap.putSingle("depth", "1o");
919 UriInfo mockInfo = mock(UriInfo.class);
920 when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
922 public MultivaluedMap<String, String> answer(InvocationOnMock invocation) {
927 getDataWithInvalidDepthParameterTest(mockInfo);
929 paramMap.putSingle("depth", "0");
930 getDataWithInvalidDepthParameterTest(mockInfo);
932 paramMap.putSingle("depth", "-1");
933 getDataWithInvalidDepthParameterTest(mockInfo);
936 private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
938 QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
939 YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
940 NormalizedNode value = (NormalizedNode<?,?>)(Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build());
941 when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value);
942 restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
943 fail("Expected RestconfDocumentedException");
944 } catch (RestconfDocumentedException e) {
945 assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
946 .getErrorMessage().contains("depth"));
950 private void verifyXMLResponse(final Response response, final NodeData nodeData) {
951 Document doc = response.readEntity(Document.class);
952 // Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
953 // System.out.println();
954 assertNotNull("Could not parse XML document", doc);
956 // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
958 verifyContainerElement(doc.getDocumentElement(), nodeData);
961 @SuppressWarnings("unchecked")
962 private void verifyContainerElement(final Element element, final NodeData nodeData) {
964 assertEquals("Element local name", nodeData.key, element.getLocalName());
966 NodeList childNodes = element.getChildNodes();
967 if (nodeData.data == null) { // empty container
968 assertTrue("Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
972 Map<String, NodeData> expChildMap = Maps.newHashMap();
973 for (NodeData expChild : (List<NodeData>) nodeData.data) {
974 expChildMap.put(expChild.key.toString(), expChild);
977 for (int i = 0; i < childNodes.getLength(); i++) {
978 org.w3c.dom.Node actualChild = childNodes.item(i);
979 if (!(actualChild instanceof Element)) {
983 Element actualElement = (Element) actualChild;
984 NodeData expChild = expChildMap.remove(actualElement.getLocalName());
986 "Unexpected child element for parent \"" + element.getLocalName() + "\": "
987 + actualElement.getLocalName(), expChild);
989 if (expChild.data == null || expChild.data instanceof List) {
990 verifyContainerElement(actualElement, expChild);
992 assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data,
993 actualElement.getTextContent());
997 if (!expChildMap.isEmpty()) {
998 fail("Missing elements for parent \"" + element.getLocalName() + "\": " + expChildMap.keySet());
1002 private NodeData expectContainer(final String name, final NodeData... childData) {
1003 return new NodeData(name, Lists.newArrayList(childData));
1006 private NodeData expectEmptyContainer(final String name) {
1007 return new NodeData(name, null);
1010 private NodeData expectLeaf(final String name, final Object value) {
1011 return new NodeData(name, value);
1014 private QName toNestedQName(final String localName) {
1015 return QName.create("urn:nested:module", "2014-06-3", localName);
1018 @SuppressWarnings("unchecked")
1019 private CompositeNode toCompositeNode(final NodeData nodeData) {
1020 CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
1021 builder.setQName((QName) nodeData.key);
1023 for (NodeData child : (List<NodeData>) nodeData.data) {
1024 if (child.data instanceof List) {
1025 builder.add(toCompositeNode(child));
1027 builder.addLeaf((QName) child.key, child.data);
1031 return builder.toInstance();
1034 private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
1035 return new NodeData(key, Lists.newArrayList(childData));
1038 private NodeData toSimpleNodeData(final QName key, final Object value) {
1039 return new NodeData(key, value);