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.ArgumentMatchers.any;
17 import static org.mockito.ArgumentMatchers.eq;
18 import static org.mockito.ArgumentMatchers.isNull;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.when;
22 import com.google.common.collect.ImmutableMap;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32 import javax.ws.rs.core.Application;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.MultivaluedHashMap;
35 import javax.ws.rs.core.MultivaluedMap;
36 import javax.ws.rs.core.Response;
37 import javax.ws.rs.core.UriInfo;
38 import org.glassfish.jersey.server.ResourceConfig;
39 import org.glassfish.jersey.test.JerseyTest;
40 import org.junit.BeforeClass;
41 import org.junit.Ignore;
42 import org.junit.Test;
43 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
44 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
45 import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
46 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
47 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter;
48 import org.opendaylight.netconf.sal.rest.impl.RestconfDocumentedExceptionMapper;
49 import org.opendaylight.netconf.sal.rest.impl.XmlNormalizedNodeBodyReader;
50 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
51 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
52 import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
53 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.common.Revision;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
60 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
62 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
63 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
64 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
65 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
66 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
67 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
68 import org.opendaylight.yangtools.yang.model.api.Module;
69 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.w3c.dom.Document;
72 import org.w3c.dom.Element;
73 import org.w3c.dom.NodeList;
75 public class RestGetOperationTest extends JerseyTest {
77 static class NodeData {
79 Object data; // List for a CompositeNode, value Object for a SimpleNode
81 NodeData(final Object key, final Object data) {
87 private static EffectiveModelContext schemaContextYangsIetf;
88 private static EffectiveModelContext schemaContextTestModule;
89 private static EffectiveModelContext schemaContextModules;
90 private static EffectiveModelContext schemaContextBehindMountPoint;
92 @SuppressWarnings("rawtypes")
93 private static NormalizedNode answerFromGet;
95 private BrokerFacade brokerFacade;
96 private RestconfImpl restconfImpl;
97 private ControllerContext controllerContext;
98 private DOMMountPoint mountInstance;
100 private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf";
103 public static void init() throws Exception {
104 schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
105 schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
106 schemaContextModules = TestUtils.loadSchemaContext("/modules");
107 schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
109 answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
113 protected Application configure() {
114 /* enable/disable Jersey logs to console */
115 // enable(TestProperties.LOG_TRAFFIC);
116 // enable(TestProperties.DUMP_ENTITY);
117 // enable(TestProperties.RECORD_LOG_LEVEL);
118 // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
120 mountInstance = mock(DOMMountPoint.class);
121 controllerContext = TestRestconfUtils.newControllerContext(schemaContextYangsIetf, mountInstance);
122 brokerFacade = mock(BrokerFacade.class);
123 restconfImpl = RestconfImpl.newInstance(brokerFacade, controllerContext);
125 ResourceConfig resourceConfig = new ResourceConfig();
126 resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
127 new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(controllerContext),
128 new JsonNormalizedNodeBodyReader(controllerContext),
129 new RestconfDocumentedExceptionMapper(controllerContext));
130 return resourceConfig;
133 private void setControllerContext(final EffectiveModelContext schemaContext) {
134 controllerContext.setSchemas(schemaContext);
138 * Tests of status codes for "/operational/{identifier}".
141 public void getOperationalStatusCodes() throws Exception {
142 setControllerContext(schemaContextYangsIetf);
143 mockReadOperationalDataMethod();
144 String uri = "/operational/ietf-interfaces:interfaces/interface/eth0";
145 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
147 uri = "/operational/wrong-module:interfaces/interface/eth0";
148 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
152 * Tests of status codes for "/config/{identifier}".
155 public void getConfigStatusCodes() throws Exception {
156 setControllerContext(schemaContextYangsIetf);
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.
168 @SuppressWarnings("unchecked")
170 public void getDataWithUrlMountPoint() throws Exception {
171 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
172 isNull())).thenReturn(prepareCnDataForMountPointTest(false));
173 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
175 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/cont1";
176 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
178 uri = "/config/ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
179 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
183 * MountPoint test. URI represents mount point.
184 * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
185 * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
186 * InstanceIdentifier parameter in method
187 * {@link BrokerFacade#readConfigurationData(DOMMountPoint, YangInstanceIdentifier)} which is called in
188 * method {@link RestconfImpl#readConfigurationData}
191 public void getDataWithSlashesBehindMountPoint() throws Exception {
192 final YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
193 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier),
194 isNull())).thenReturn(prepareCnDataForSlashesBehindMountPointTest());
196 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
198 final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"
199 + "test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
200 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
203 private static YangInstanceIdentifier prepareInstanceIdentifierForList() throws Exception {
204 final List<PathArgument> parameters = new ArrayList<>();
206 final QName qNameCont = newTestModuleQName("cont");
207 final QName qNameList = newTestModuleQName("lst1");
208 final QName qNameKeyList = newTestModuleQName("lf11");
210 parameters.add(new NodeIdentifier(qNameCont));
211 parameters.add(new NodeIdentifier(qNameList));
212 parameters.add(NodeIdentifierWithPredicates.of(qNameList, qNameKeyList, "GigabitEthernet0/0/0/0"));
213 return YangInstanceIdentifier.create(parameters);
216 private static QName newTestModuleQName(final String localPart) throws Exception {
217 return QName.create(URI.create("test:module"), Revision.of("2014-01-09"), localPart);
221 public void getDataMountPointIntoHighestElement() throws Exception {
222 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
223 isNull())).thenReturn(prepareCnDataForMountPointTest(true));
225 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
227 final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
228 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
231 @SuppressWarnings("unchecked")
233 public void getDataWithIdentityrefInURL() throws Exception {
234 setControllerContext(schemaContextTestModule);
236 final QName moduleQN = newTestModuleQName("module");
237 final ImmutableMap<QName, Object> keyMap = ImmutableMap.of(
238 newTestModuleQName("type"), newTestModuleQName("test-identity"),
239 newTestModuleQName("name"), "foo");
240 final YangInstanceIdentifier iid = YangInstanceIdentifier.builder().node(newTestModuleQName("modules"))
241 .node(moduleQN).nodeWithKey(moduleQN, keyMap).build();
242 @SuppressWarnings("rawtypes")
243 final NormalizedNode data = ImmutableMapNodeBuilder.create().withNodeIdentifier(
244 new NodeIdentifier(moduleQN)).withChild(ImmutableNodes.mapEntryBuilder()
245 .withNodeIdentifier(NodeIdentifierWithPredicates.of(moduleQN, keyMap))
246 .withChild(ImmutableNodes.leafNode(newTestModuleQName("type"), newTestModuleQName("test-identity")))
247 .withChild(ImmutableNodes.leafNode(newTestModuleQName("name"), "foo"))
248 .withChild(ImmutableNodes.leafNode(newTestModuleQName("data"), "bar")).build()).build();
249 when(brokerFacade.readConfigurationData(iid, null)).thenReturn(data);
251 final String uri = "/config/test-module:modules/module/test-module:test-identity/foo";
252 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
257 public void getModulesTest() throws Exception {
258 setControllerContext(schemaContextModules);
260 final String uri = "/modules";
262 Response response = target(uri).request("application/yang.api+json").get();
263 validateModulesResponseJson(response);
265 response = target(uri).request("application/yang.api+xml").get();
266 validateModulesResponseXml(response,schemaContextModules);
271 @Ignore // FIXME : find why it is fail by in gerrit build
272 public void getStreamsTest() throws Exception {
273 setControllerContext(schemaContextModules);
275 final String uri = "/streams";
277 Response response = target(uri).request("application/yang.api+json").get();
278 final String responseBody = response.readEntity(String.class);
279 assertEquals(200, response.getStatus());
280 assertNotNull(responseBody);
281 assertTrue(responseBody.contains("streams"));
283 response = target(uri).request("application/yang.api+xml").get();
284 assertEquals(200, response.getStatus());
285 final Document responseXmlBody = response.readEntity(Document.class);
286 assertNotNull(responseXmlBody);
287 final Element rootNode = responseXmlBody.getDocumentElement();
289 assertEquals("streams", rootNode.getLocalName());
290 assertEquals(RESTCONF_NS, rootNode.getNamespaceURI());
295 public void getModuleTest() throws Exception {
296 setControllerContext(schemaContextModules);
298 final String uri = "/modules/module/module2/2014-01-02";
300 Response response = target(uri).request("application/yang.api+xml").get();
301 assertEquals(200, response.getStatus());
302 final Document responseXml = response.readEntity(Document.class);
304 final QName qname = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
305 assertNotNull(qname);
307 assertEquals("module2", qname.getLocalName());
308 assertEquals("module:2", qname.getNamespace().toString());
309 assertEquals("2014-01-02", qname.getRevision().get().toString());
311 response = target(uri).request("application/yang.api+json").get();
312 assertEquals(200, response.getStatus());
313 final String responseBody = response.readEntity(String.class);
314 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
316 final String[] split = responseBody.split("\"module\"");
317 assertEquals("\"module\" element is returned more then once", 2, split.length);
324 public void getOperationsTest() throws Exception {
325 setControllerContext(schemaContextModules);
327 final String uri = "/operations";
329 Response response = target(uri).request("application/yang.api+xml").get();
330 assertEquals(500, response.getStatus());
331 final Document responseDoc = response.readEntity(Document.class);
332 validateOperationsResponseXml(responseDoc, schemaContextModules);
334 response = target(uri).request("application/yang.api+json").get();
335 assertEquals(200, response.getStatus());
336 final String responseBody = response.readEntity(String.class);
337 assertTrue("Json response for /operations dummy-rpc1-module1 is incorrect",
338 validateOperationsResponseJson(responseBody, "dummy-rpc1-module1", "module1").find());
339 assertTrue("Json response for /operations dummy-rpc2-module1 is incorrect",
340 validateOperationsResponseJson(responseBody, "dummy-rpc2-module1", "module1").find());
341 assertTrue("Json response for /operations dummy-rpc1-module2 is incorrect",
342 validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
343 assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
344 validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
347 private static void validateOperationsResponseXml(final Document responseDoc, final SchemaContext schemaContext) {
349 final Element operationsElem = responseDoc.getDocumentElement();
350 assertEquals(RESTCONF_NS, operationsElem.getNamespaceURI());
351 assertEquals("operations", operationsElem.getLocalName());
353 final NodeList operationsList = operationsElem.getChildNodes();
354 final HashSet<String> foundOperations = new HashSet<>();
356 for (int i = 0; i < operationsList.getLength(); i++) {
357 final org.w3c.dom.Node operation = operationsList.item(i);
358 foundOperations.add(operation.getLocalName());
361 for (final RpcDefinition schemaOp : schemaContext.getOperations()) {
362 assertTrue(foundOperations.contains(schemaOp.getQName().getLocalName()));
366 // /operations/pathToMountPoint/yang-ext:mount
369 public void getOperationsBehindMountPointTest() throws Exception {
370 setControllerContext(schemaContextModules);
372 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
374 final String uri = "/operations/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
376 Response response = target(uri).request("application/yang.api+xml").get();
377 assertEquals(500, response.getStatus());
379 final 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 final 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 static Matcher validateOperationsResponseJson(final String searchIn, final String rpcName,
393 final String moduleName) {
394 final StringBuilder regex = new StringBuilder();
395 regex.append(".*\"" + rpcName + "\"");
396 final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
397 return ptrn.matcher(searchIn);
401 // /restconf/modules/pathToMountPoint/yang-ext:mount
403 public void getModulesBehindMountPoint() throws Exception {
404 setControllerContext(schemaContextModules);
406 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
408 final String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
410 Response response = target(uri).request("application/yang.api+json").get();
411 assertEquals(200, response.getStatus());
412 final String responseBody = response.readEntity(String.class);
415 "module1-behind-mount-point in json wasn't found",
416 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
417 responseBody).find());
419 "module2-behind-mount-point in json wasn't found",
420 prepareJsonRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point",
421 responseBody).find());
423 response = target(uri).request("application/yang.api+xml").get();
424 assertEquals(200, response.getStatus());
425 validateModulesResponseXml(response, schemaContextBehindMountPoint);
429 // /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
431 public void getModuleBehindMountPoint() throws Exception {
432 setControllerContext(schemaContextModules);
434 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
436 final String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"
437 + "module1-behind-mount-point/2014-02-03";
439 Response response = target(uri).request("application/yang.api+json").get();
440 assertEquals(200, response.getStatus());
441 final String responseBody = response.readEntity(String.class);
444 "module1-behind-mount-point in json wasn't found",
445 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
446 responseBody).find());
447 final String[] split = responseBody.split("\"module\"");
448 assertEquals("\"module\" element is returned more then once", 2, split.length);
450 response = target(uri).request("application/yang.api+xml").get();
451 assertEquals(200, response.getStatus());
452 final Document responseXml = response.readEntity(Document.class);
454 final QName module = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
456 assertEquals("module1-behind-mount-point", module.getLocalName());
457 assertEquals("2014-02-03", module.getRevision().get().toString());
458 assertEquals("module:1:behind:mount:point", module.getNamespace().toString());
463 private static void validateModulesResponseXml(final Response response, final SchemaContext schemaContext) {
464 assertEquals(200, response.getStatus());
465 final Document responseBody = response.readEntity(Document.class);
466 final NodeList moduleNodes = responseBody.getDocumentElement().getElementsByTagNameNS(RESTCONF_NS, "module");
468 assertTrue(moduleNodes.getLength() > 0);
470 final HashSet<QName> foundModules = new HashSet<>();
472 for (int i = 0; i < moduleNodes.getLength(); i++) {
473 final org.w3c.dom.Node module = moduleNodes.item(i);
475 final QName name = assertedModuleXmlToModuleQName(module);
476 foundModules.add(name);
479 assertAllModules(foundModules,schemaContext);
482 private static void assertAllModules(final Set<QName> foundModules, final SchemaContext schemaContext) {
483 for (final Module module : schemaContext.getModules()) {
484 final QName current = QName.create(module.getQNameModule(), module.getName());
485 assertTrue("Module not found in response.", foundModules.contains(current));
490 private static QName assertedModuleXmlToModuleQName(final org.w3c.dom.Node module) {
491 assertEquals("module", module.getLocalName());
492 assertEquals(RESTCONF_NS, module.getNamespaceURI());
493 String revision = null;
494 String namespace = null;
498 final NodeList childNodes = module.getChildNodes();
500 for (int i = 0; i < childNodes.getLength(); i++) {
501 final org.w3c.dom.Node child = childNodes.item(i);
502 assertEquals(RESTCONF_NS, child.getNamespaceURI());
504 switch (child.getLocalName()) {
506 assertNull("Name element appeared multiple times", name);
507 name = child.getTextContent().trim();
510 assertNull("Revision element appeared multiple times", revision);
511 revision = child.getTextContent().trim();
514 assertNull("Namespace element appeared multiple times", namespace);
515 namespace = child.getTextContent().trim();
522 assertNotNull("Revision was not part of xml",revision);
523 assertNotNull("Module namespace was not part of xml",namespace);
524 assertNotNull("Module identiffier was not part of xml",name);
526 return QName.create(namespace,revision,name);
529 private static void validateModulesResponseJson(final Response response) {
530 assertEquals(200, response.getStatus());
531 final String responseBody = response.readEntity(String.class);
533 assertTrue("Module1 in json wasn't found", prepareJsonRegex("module1", "2014-01-01", "module:1", responseBody)
535 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
537 assertTrue("Module3 in json wasn't found", prepareJsonRegex("module3", "2014-01-03", "module:3", responseBody)
541 private static Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
542 final String searchIn) {
543 final StringBuilder regex = new StringBuilder();
546 regex.append(".*\\{");
547 regex.append(".*\"name\"");
549 regex.append(".*\"" + module + "\",");
551 regex.append(".*\"revision\"");
553 regex.append(".*\"" + revision + "\",");
555 regex.append(".*\"namespace\"");
557 regex.append(".*\"" + namespace + "\"");
559 regex.append(".*\\}");
563 final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
564 return ptrn.matcher(searchIn);
569 private int get(final String uri, final String mediaType) {
570 return target(uri).request(mediaType).get().getStatus();
574 * Container structure.
583 @SuppressWarnings("rawtypes")
584 private static NormalizedNode prepareCnDataForMountPointTest(final boolean wrapToCont) throws Exception {
585 final String testModuleDate = "2014-01-09";
586 final ContainerNode contChild = Builders
588 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont1", "test:module", testModuleDate))
590 Builders.leafBuilder()
591 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", testModuleDate))
592 .withValue("lf11 value").build()).build();
595 return Builders.containerBuilder()
596 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont", "test:module", testModuleDate))
597 .withChild(contChild).build();
603 @SuppressWarnings("unchecked")
604 private void mockReadOperationalDataMethod() {
605 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
608 @SuppressWarnings("unchecked")
609 private void mockReadConfigurationDataMethod() {
610 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class), isNull()))
611 .thenReturn(answerFromGet);
614 @SuppressWarnings("rawtypes")
615 private static NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws Exception {
616 return ImmutableMapEntryNodeBuilder
619 TestUtils.getNodeIdentifierPredicate("lst1", "test:module", "2014-01-09", "lf11",
620 "GigabitEthernet0/0/0/0"))
622 ImmutableLeafNodeBuilder.create()
623 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", "2014-01-09"))
624 .withValue("GigabitEthernet0/0/0/0").build()).build();
629 * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output.
632 public void getDataWithUriIncludeWhiteCharsParameterTest() throws Exception {
633 getDataWithUriIncludeWhiteCharsParameter("config");
634 getDataWithUriIncludeWhiteCharsParameter("operational");
637 private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws Exception {
638 mockReadConfigurationDataMethod();
639 mockReadOperationalDataMethod();
640 final String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
641 Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
642 final String xmlData = response.readEntity(String.class);
644 Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
645 Matcher matcher = pattern.matcher(xmlData);
646 // XML element can't surrounded with white character (e.g "> " or
648 assertFalse(matcher.matches());
650 response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
651 final String jsonData = response.readEntity(String.class);
652 pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
653 matcher = pattern.matcher(jsonData);
654 // JSON element can't surrounded with white character (e.g "} ", " {",
655 // "] ", " [", " :" or ": ")
656 assertFalse(matcher.matches());
660 * Tests behavior when invalid value of depth URI parameter.
664 public void getDataWithInvalidDepthParameterTest() {
665 setControllerContext(schemaContextModules);
667 final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
668 paramMap.putSingle("depth", "1o");
669 final UriInfo mockInfo = mock(UriInfo.class);
670 when(mockInfo.getQueryParameters(false)).thenAnswer(invocation -> paramMap);
672 getDataWithInvalidDepthParameterTest(mockInfo);
674 paramMap.putSingle("depth", "0");
675 getDataWithInvalidDepthParameterTest(mockInfo);
677 paramMap.putSingle("depth", "-1");
678 getDataWithInvalidDepthParameterTest(mockInfo);
681 @SuppressWarnings({"rawtypes", "unchecked"})
682 private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
684 final QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
685 final YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
686 final NormalizedNode value =
687 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build();
688 when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value);
689 restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
690 fail("Expected RestconfDocumentedException");
691 } catch (final RestconfDocumentedException e) {
692 assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
693 .getErrorMessage().contains("depth"));
697 @SuppressWarnings("unused")
698 private void verifyXMLResponse(final Response response, final NodeData nodeData) {
699 final Document doc = response.readEntity(Document.class);
700 assertNotNull("Could not parse XML document", doc);
702 verifyContainerElement(doc.getDocumentElement(), nodeData);
705 @SuppressWarnings("unchecked")
706 private void verifyContainerElement(final Element element, final NodeData nodeData) {
708 assertEquals("Element local name", nodeData.key, element.getLocalName());
710 final NodeList childNodes = element.getChildNodes();
711 if (nodeData.data == null) { // empty container
713 "Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
717 final Map<String, NodeData> expChildMap = new HashMap<>();
718 for (final NodeData expChild : (List<NodeData>) nodeData.data) {
719 expChildMap.put(expChild.key.toString(), expChild);
722 for (int i = 0; i < childNodes.getLength(); i++) {
723 final org.w3c.dom.Node actualChild = childNodes.item(i);
724 if (!(actualChild instanceof Element)) {
728 final Element actualElement = (Element) actualChild;
729 final NodeData expChild = expChildMap.remove(actualElement.getLocalName());
731 "Unexpected child element for parent \"" + element.getLocalName() + "\": "
732 + actualElement.getLocalName(), expChild);
734 if (expChild.data == null || expChild.data instanceof List) {
735 verifyContainerElement(actualElement, expChild);
737 assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data,
738 actualElement.getTextContent());
742 if (!expChildMap.isEmpty()) {
743 fail("Missing elements for parent \"" + element.getLocalName() + "\": " + expChildMap.keySet());