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;
29 import java.util.Optional;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import javax.ws.rs.core.Application;
34 import javax.ws.rs.core.MediaType;
35 import javax.ws.rs.core.MultivaluedHashMap;
36 import javax.ws.rs.core.MultivaluedMap;
37 import javax.ws.rs.core.Response;
38 import javax.ws.rs.core.UriInfo;
39 import org.glassfish.jersey.server.ResourceConfig;
40 import org.glassfish.jersey.test.JerseyTest;
41 import org.junit.BeforeClass;
42 import org.junit.Ignore;
43 import org.junit.Test;
44 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
45 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
46 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
47 import org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService;
48 import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
49 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
50 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter;
51 import org.opendaylight.netconf.sal.rest.impl.RestconfDocumentedExceptionMapper;
52 import org.opendaylight.netconf.sal.rest.impl.XmlNormalizedNodeBodyReader;
53 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
54 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
55 import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
56 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.common.Revision;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
63 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
65 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
66 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
67 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
68 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
69 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
70 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
71 import org.opendaylight.yangtools.yang.model.api.Module;
72 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
73 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
74 import org.w3c.dom.Document;
75 import org.w3c.dom.Element;
76 import org.w3c.dom.NodeList;
78 public class RestGetOperationTest extends JerseyTest {
80 static class NodeData {
82 Object data; // List for a CompositeNode, value Object for a SimpleNode
84 NodeData(final Object key, final Object data) {
90 private static EffectiveModelContext schemaContextYangsIetf;
91 private static EffectiveModelContext schemaContextTestModule;
92 private static EffectiveModelContext schemaContextModules;
93 private static EffectiveModelContext schemaContextBehindMountPoint;
95 @SuppressWarnings("rawtypes")
96 private static NormalizedNode answerFromGet;
98 private BrokerFacade brokerFacade;
99 private RestconfImpl restconfImpl;
100 private ControllerContext controllerContext;
101 private DOMMountPoint mountInstance;
103 private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf";
106 public static void init() throws Exception {
107 schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
108 schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
109 schemaContextModules = TestUtils.loadSchemaContext("/modules");
110 schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
112 answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
116 protected Application configure() {
117 /* enable/disable Jersey logs to console */
118 // enable(TestProperties.LOG_TRAFFIC);
119 // enable(TestProperties.DUMP_ENTITY);
120 // enable(TestProperties.RECORD_LOG_LEVEL);
121 // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
123 mountInstance = mock(DOMMountPoint.class);
124 controllerContext = TestRestconfUtils.newControllerContext(schemaContextYangsIetf, mountInstance);
125 brokerFacade = mock(BrokerFacade.class);
126 restconfImpl = RestconfImpl.newInstance(brokerFacade, controllerContext);
128 ResourceConfig resourceConfig = new ResourceConfig();
129 resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
130 new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(controllerContext),
131 new JsonNormalizedNodeBodyReader(controllerContext),
132 new RestconfDocumentedExceptionMapper(controllerContext));
133 return resourceConfig;
136 private void setControllerContext(final EffectiveModelContext schemaContext) {
137 controllerContext.setSchemas(schemaContext);
141 * Tests of status codes for "/operational/{identifier}".
144 public void getOperationalStatusCodes() throws Exception {
145 setControllerContext(schemaContextYangsIetf);
146 mockReadOperationalDataMethod();
147 String uri = "/operational/ietf-interfaces:interfaces/interface/eth0";
148 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
150 uri = "/operational/wrong-module:interfaces/interface/eth0";
151 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
155 * Tests of status codes for "/config/{identifier}".
158 public void getConfigStatusCodes() throws Exception {
159 setControllerContext(schemaContextYangsIetf);
160 mockReadConfigurationDataMethod();
161 String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
162 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
164 uri = "/config/wrong-module:interfaces/interface/eth0";
165 assertEquals(400, get(uri, MediaType.APPLICATION_XML));
169 * MountPoint test. URI represents mount point.
171 @SuppressWarnings("unchecked")
173 public void getDataWithUrlMountPoint() throws Exception {
174 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
175 isNull())).thenReturn(prepareCnDataForMountPointTest(false));
176 when(mountInstance.getService(DOMSchemaService.class))
177 .thenReturn(Optional.of(FixedDOMSchemaService.of(schemaContextTestModule)));
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.
188 * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
189 * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
190 * InstanceIdentifier parameter in method
191 * {@link BrokerFacade#readConfigurationData(DOMMountPoint, YangInstanceIdentifier)} which is called in
192 * method {@link RestconfImpl#readConfigurationData}
195 public void getDataWithSlashesBehindMountPoint() throws Exception {
196 final YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
197 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier),
198 isNull())).thenReturn(prepareCnDataForSlashesBehindMountPointTest());
199 when(mountInstance.getService(DOMSchemaService.class))
200 .thenReturn(Optional.of(FixedDOMSchemaService.of(schemaContextTestModule)));
202 final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"
203 + "test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
204 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
207 private static YangInstanceIdentifier prepareInstanceIdentifierForList() throws Exception {
208 final List<PathArgument> parameters = new ArrayList<>();
210 final QName qNameCont = newTestModuleQName("cont");
211 final QName qNameList = newTestModuleQName("lst1");
212 final QName qNameKeyList = newTestModuleQName("lf11");
214 parameters.add(new NodeIdentifier(qNameCont));
215 parameters.add(new NodeIdentifier(qNameList));
216 parameters.add(NodeIdentifierWithPredicates.of(qNameList, qNameKeyList, "GigabitEthernet0/0/0/0"));
217 return YangInstanceIdentifier.create(parameters);
220 private static QName newTestModuleQName(final String localPart) throws Exception {
221 return QName.create(URI.create("test:module"), Revision.of("2014-01-09"), localPart);
225 public void getDataMountPointIntoHighestElement() throws Exception {
226 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
227 isNull())).thenReturn(prepareCnDataForMountPointTest(true));
228 when(mountInstance.getService(DOMSchemaService.class))
229 .thenReturn(Optional.of(FixedDOMSchemaService.of(schemaContextTestModule)));
231 final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
232 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
235 @SuppressWarnings("unchecked")
237 public void getDataWithIdentityrefInURL() throws Exception {
238 setControllerContext(schemaContextTestModule);
240 final QName moduleQN = newTestModuleQName("module");
241 final ImmutableMap<QName, Object> keyMap = ImmutableMap.of(
242 newTestModuleQName("type"), newTestModuleQName("test-identity"),
243 newTestModuleQName("name"), "foo");
244 final YangInstanceIdentifier iid = YangInstanceIdentifier.builder().node(newTestModuleQName("modules"))
245 .node(moduleQN).nodeWithKey(moduleQN, keyMap).build();
246 @SuppressWarnings("rawtypes")
247 final NormalizedNode data = ImmutableMapNodeBuilder.create().withNodeIdentifier(
248 new NodeIdentifier(moduleQN)).withChild(ImmutableNodes.mapEntryBuilder()
249 .withNodeIdentifier(NodeIdentifierWithPredicates.of(moduleQN, keyMap))
250 .withChild(ImmutableNodes.leafNode(newTestModuleQName("type"), newTestModuleQName("test-identity")))
251 .withChild(ImmutableNodes.leafNode(newTestModuleQName("name"), "foo"))
252 .withChild(ImmutableNodes.leafNode(newTestModuleQName("data"), "bar")).build()).build();
253 when(brokerFacade.readConfigurationData(iid, null)).thenReturn(data);
255 final String uri = "/config/test-module:modules/module/test-module:test-identity/foo";
256 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
261 public void getModulesTest() throws Exception {
262 setControllerContext(schemaContextModules);
264 final String uri = "/modules";
266 Response response = target(uri).request("application/yang.api+json").get();
267 validateModulesResponseJson(response);
269 response = target(uri).request("application/yang.api+xml").get();
270 validateModulesResponseXml(response,schemaContextModules);
275 @Ignore // FIXME : find why it is fail by in gerrit build
276 public void getStreamsTest() throws Exception {
277 setControllerContext(schemaContextModules);
279 final String uri = "/streams";
281 Response response = target(uri).request("application/yang.api+json").get();
282 final String responseBody = response.readEntity(String.class);
283 assertEquals(200, response.getStatus());
284 assertNotNull(responseBody);
285 assertTrue(responseBody.contains("streams"));
287 response = target(uri).request("application/yang.api+xml").get();
288 assertEquals(200, response.getStatus());
289 final Document responseXmlBody = response.readEntity(Document.class);
290 assertNotNull(responseXmlBody);
291 final Element rootNode = responseXmlBody.getDocumentElement();
293 assertEquals("streams", rootNode.getLocalName());
294 assertEquals(RESTCONF_NS, rootNode.getNamespaceURI());
299 public void getModuleTest() throws Exception {
300 setControllerContext(schemaContextModules);
302 final String uri = "/modules/module/module2/2014-01-02";
304 Response response = target(uri).request("application/yang.api+xml").get();
305 assertEquals(200, response.getStatus());
306 final Document responseXml = response.readEntity(Document.class);
308 final QName qname = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
309 assertNotNull(qname);
311 assertEquals("module2", qname.getLocalName());
312 assertEquals("module:2", qname.getNamespace().toString());
313 assertEquals("2014-01-02", qname.getRevision().get().toString());
315 response = target(uri).request("application/yang.api+json").get();
316 assertEquals(200, response.getStatus());
317 final String responseBody = response.readEntity(String.class);
318 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
320 final String[] split = responseBody.split("\"module\"");
321 assertEquals("\"module\" element is returned more then once", 2, split.length);
328 public void getOperationsTest() throws Exception {
329 setControllerContext(schemaContextModules);
331 final String uri = "/operations";
333 Response response = target(uri).request("application/yang.api+xml").get();
334 assertEquals(500, response.getStatus());
335 final Document responseDoc = response.readEntity(Document.class);
336 validateOperationsResponseXml(responseDoc, schemaContextModules);
338 response = target(uri).request("application/yang.api+json").get();
339 assertEquals(200, response.getStatus());
340 final String responseBody = response.readEntity(String.class);
341 assertTrue("Json response for /operations dummy-rpc1-module1 is incorrect",
342 validateOperationsResponseJson(responseBody, "dummy-rpc1-module1", "module1").find());
343 assertTrue("Json response for /operations dummy-rpc2-module1 is incorrect",
344 validateOperationsResponseJson(responseBody, "dummy-rpc2-module1", "module1").find());
345 assertTrue("Json response for /operations dummy-rpc1-module2 is incorrect",
346 validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
347 assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
348 validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
351 private static void validateOperationsResponseXml(final Document responseDoc, final SchemaContext schemaContext) {
353 final Element operationsElem = responseDoc.getDocumentElement();
354 assertEquals(RESTCONF_NS, operationsElem.getNamespaceURI());
355 assertEquals("operations", operationsElem.getLocalName());
357 final NodeList operationsList = operationsElem.getChildNodes();
358 final HashSet<String> foundOperations = new HashSet<>();
360 for (int i = 0; i < operationsList.getLength(); i++) {
361 final org.w3c.dom.Node operation = operationsList.item(i);
362 foundOperations.add(operation.getLocalName());
365 for (final RpcDefinition schemaOp : schemaContext.getOperations()) {
366 assertTrue(foundOperations.contains(schemaOp.getQName().getLocalName()));
370 // /operations/pathToMountPoint/yang-ext:mount
373 public void getOperationsBehindMountPointTest() throws Exception {
374 setControllerContext(schemaContextModules);
378 final String uri = "/operations/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
380 Response response = target(uri).request("application/yang.api+xml").get();
381 assertEquals(500, response.getStatus());
383 final Document responseDoc = response.readEntity(Document.class);
384 validateOperationsResponseXml(responseDoc, schemaContextBehindMountPoint);
386 response = target(uri).request("application/yang.api+json").get();
387 assertEquals(200, response.getStatus());
388 final String responseBody = response.readEntity(String.class);
389 assertTrue("Json response for /operations/mount_point rpc-behind-module1 is incorrect",
390 validateOperationsResponseJson(responseBody, "rpc-behind-module1", "module1-behind-mount-point").find());
391 assertTrue("Json response for /operations/mount_point rpc-behind-module2 is incorrect",
392 validateOperationsResponseJson(responseBody, "rpc-behind-module2", "module2-behind-mount-point").find());
396 private static Matcher validateOperationsResponseJson(final String searchIn, final String rpcName,
397 final String moduleName) {
398 final StringBuilder regex = new StringBuilder();
399 regex.append(".*\"" + rpcName + "\"");
400 final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
401 return ptrn.matcher(searchIn);
405 // /restconf/modules/pathToMountPoint/yang-ext:mount
407 public void getModulesBehindMountPoint() throws Exception {
408 setControllerContext(schemaContextModules);
412 final String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
414 Response response = target(uri).request("application/yang.api+json").get();
415 assertEquals(200, response.getStatus());
416 final String responseBody = response.readEntity(String.class);
419 "module1-behind-mount-point in json wasn't found",
420 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
421 responseBody).find());
423 "module2-behind-mount-point in json wasn't found",
424 prepareJsonRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point",
425 responseBody).find());
427 response = target(uri).request("application/yang.api+xml").get();
428 assertEquals(200, response.getStatus());
429 validateModulesResponseXml(response, schemaContextBehindMountPoint);
433 // /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
435 public void getModuleBehindMountPoint() throws Exception {
436 setControllerContext(schemaContextModules);
440 final String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"
441 + "module1-behind-mount-point/2014-02-03";
443 Response response = target(uri).request("application/yang.api+json").get();
444 assertEquals(200, response.getStatus());
445 final String responseBody = response.readEntity(String.class);
448 "module1-behind-mount-point in json wasn't found",
449 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
450 responseBody).find());
451 final String[] split = responseBody.split("\"module\"");
452 assertEquals("\"module\" element is returned more then once", 2, split.length);
454 response = target(uri).request("application/yang.api+xml").get();
455 assertEquals(200, response.getStatus());
456 final Document responseXml = response.readEntity(Document.class);
458 final QName module = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
460 assertEquals("module1-behind-mount-point", module.getLocalName());
461 assertEquals("2014-02-03", module.getRevision().get().toString());
462 assertEquals("module:1:behind:mount:point", module.getNamespace().toString());
465 private static void validateModulesResponseXml(final Response response, final SchemaContext schemaContext) {
466 assertEquals(200, response.getStatus());
467 final Document responseBody = response.readEntity(Document.class);
468 final NodeList moduleNodes = responseBody.getDocumentElement().getElementsByTagNameNS(RESTCONF_NS, "module");
470 assertTrue(moduleNodes.getLength() > 0);
472 final HashSet<QName> foundModules = new HashSet<>();
474 for (int i = 0; i < moduleNodes.getLength(); i++) {
475 final org.w3c.dom.Node module = moduleNodes.item(i);
477 final QName name = assertedModuleXmlToModuleQName(module);
478 foundModules.add(name);
481 assertAllModules(foundModules,schemaContext);
484 private static void assertAllModules(final Set<QName> foundModules, final SchemaContext schemaContext) {
485 for (final Module module : schemaContext.getModules()) {
486 final QName current = QName.create(module.getQNameModule(), module.getName());
487 assertTrue("Module not found in response.", foundModules.contains(current));
492 private static QName assertedModuleXmlToModuleQName(final org.w3c.dom.Node module) {
493 assertEquals("module", module.getLocalName());
494 assertEquals(RESTCONF_NS, module.getNamespaceURI());
495 String revision = null;
496 String namespace = null;
500 final NodeList childNodes = module.getChildNodes();
502 for (int i = 0; i < childNodes.getLength(); i++) {
503 final org.w3c.dom.Node child = childNodes.item(i);
504 assertEquals(RESTCONF_NS, child.getNamespaceURI());
506 switch (child.getLocalName()) {
508 assertNull("Name element appeared multiple times", name);
509 name = child.getTextContent().trim();
512 assertNull("Revision element appeared multiple times", revision);
513 revision = child.getTextContent().trim();
516 assertNull("Namespace element appeared multiple times", namespace);
517 namespace = child.getTextContent().trim();
524 assertNotNull("Revision was not part of xml",revision);
525 assertNotNull("Module namespace was not part of xml",namespace);
526 assertNotNull("Module identiffier was not part of xml",name);
528 return QName.create(namespace,revision,name);
531 private static void validateModulesResponseJson(final Response response) {
532 assertEquals(200, response.getStatus());
533 final String responseBody = response.readEntity(String.class);
535 assertTrue("Module1 in json wasn't found", prepareJsonRegex("module1", "2014-01-01", "module:1", responseBody)
537 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
539 assertTrue("Module3 in json wasn't found", prepareJsonRegex("module3", "2014-01-03", "module:3", responseBody)
543 private static Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
544 final String searchIn) {
545 final StringBuilder regex = new StringBuilder();
548 regex.append(".*\\{");
549 regex.append(".*\"name\"");
551 regex.append(".*\"" + module + "\",");
553 regex.append(".*\"revision\"");
555 regex.append(".*\"" + revision + "\",");
557 regex.append(".*\"namespace\"");
559 regex.append(".*\"" + namespace + "\"");
561 regex.append(".*\\}");
565 final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
566 return ptrn.matcher(searchIn);
571 private int get(final String uri, final String mediaType) {
572 return target(uri).request(mediaType).get().getStatus();
576 * Container structure.
585 @SuppressWarnings("rawtypes")
586 private static NormalizedNode prepareCnDataForMountPointTest(final boolean wrapToCont) throws Exception {
587 final String testModuleDate = "2014-01-09";
588 final ContainerNode contChild = Builders
590 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont1", "test:module", testModuleDate))
592 Builders.leafBuilder()
593 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", testModuleDate))
594 .withValue("lf11 value").build()).build();
597 return Builders.containerBuilder()
598 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont", "test:module", testModuleDate))
599 .withChild(contChild).build();
605 @SuppressWarnings("unchecked")
606 private void mockReadOperationalDataMethod() {
607 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
610 @SuppressWarnings("unchecked")
611 private void mockReadConfigurationDataMethod() {
612 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class), isNull()))
613 .thenReturn(answerFromGet);
616 @SuppressWarnings("rawtypes")
617 private static NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws Exception {
618 return ImmutableMapEntryNodeBuilder
621 TestUtils.getNodeIdentifierPredicate("lst1", "test:module", "2014-01-09", "lf11",
622 "GigabitEthernet0/0/0/0"))
624 ImmutableLeafNodeBuilder.create()
625 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", "2014-01-09"))
626 .withValue("GigabitEthernet0/0/0/0").build()).build();
631 * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output.
634 public void getDataWithUriIncludeWhiteCharsParameterTest() throws Exception {
635 getDataWithUriIncludeWhiteCharsParameter("config");
636 getDataWithUriIncludeWhiteCharsParameter("operational");
639 private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws Exception {
640 mockReadConfigurationDataMethod();
641 mockReadOperationalDataMethod();
642 final String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
643 Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
644 final String xmlData = response.readEntity(String.class);
646 Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
647 Matcher matcher = pattern.matcher(xmlData);
648 // XML element can't surrounded with white character (e.g "> " or
650 assertFalse(matcher.matches());
652 response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
653 final String jsonData = response.readEntity(String.class);
654 pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
655 matcher = pattern.matcher(jsonData);
656 // JSON element can't surrounded with white character (e.g "} ", " {",
657 // "] ", " [", " :" or ": ")
658 assertFalse(matcher.matches());
662 * Tests behavior when invalid value of depth URI parameter.
666 public void getDataWithInvalidDepthParameterTest() {
667 setControllerContext(schemaContextModules);
669 final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
670 paramMap.putSingle("depth", "1o");
671 final UriInfo mockInfo = mock(UriInfo.class);
672 when(mockInfo.getQueryParameters(false)).thenAnswer(invocation -> paramMap);
674 getDataWithInvalidDepthParameterTest(mockInfo);
676 paramMap.putSingle("depth", "0");
677 getDataWithInvalidDepthParameterTest(mockInfo);
679 paramMap.putSingle("depth", "-1");
680 getDataWithInvalidDepthParameterTest(mockInfo);
683 @SuppressWarnings({"rawtypes", "unchecked"})
684 private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
686 final QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
687 final YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
688 final NormalizedNode value =
689 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build();
690 when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value);
691 restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
692 fail("Expected RestconfDocumentedException");
693 } catch (final RestconfDocumentedException e) {
694 assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
695 .getErrorMessage().contains("depth"));
699 @SuppressWarnings("unused")
700 private void verifyXMLResponse(final Response response, final NodeData nodeData) {
701 final Document doc = response.readEntity(Document.class);
702 assertNotNull("Could not parse XML document", doc);
704 verifyContainerElement(doc.getDocumentElement(), nodeData);
707 @SuppressWarnings("unchecked")
708 private void verifyContainerElement(final Element element, final NodeData nodeData) {
710 assertEquals("Element local name", nodeData.key, element.getLocalName());
712 final NodeList childNodes = element.getChildNodes();
713 if (nodeData.data == null) { // empty container
715 "Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
719 final Map<String, NodeData> expChildMap = new HashMap<>();
720 for (final NodeData expChild : (List<NodeData>) nodeData.data) {
721 expChildMap.put(expChild.key.toString(), expChild);
724 for (int i = 0; i < childNodes.getLength(); i++) {
725 final org.w3c.dom.Node actualChild = childNodes.item(i);
726 if (!(actualChild instanceof Element)) {
730 final Element actualElement = (Element) actualChild;
731 final NodeData expChild = expChildMap.remove(actualElement.getLocalName());
733 "Unexpected child element for parent \"" + element.getLocalName() + "\": "
734 + actualElement.getLocalName(), expChild);
736 if (expChild.data == null || expChild.data instanceof List) {
737 verifyContainerElement(actualElement, expChild);
739 assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data,
740 actualElement.getTextContent());
744 if (!expChildMap.isEmpty()) {
745 fail("Missing elements for parent \"" + element.getLocalName() + "\": " + expChildMap.keySet());
749 private void mockMountPoint() {
750 when(mountInstance.getService(DOMSchemaService.class))
751 .thenReturn(Optional.of(FixedDOMSchemaService.of(schemaContextBehindMountPoint)));