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;
20 import com.google.common.base.Optional;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Maps;
23 import java.io.FileNotFoundException;
24 import java.io.UnsupportedEncodingException;
26 import java.net.URISyntaxException;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.Date;
31 import java.util.HashSet;
32 import java.util.List;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37 import javax.ws.rs.core.Application;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.MultivaluedHashMap;
40 import javax.ws.rs.core.MultivaluedMap;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.UriInfo;
43 import org.glassfish.jersey.server.ResourceConfig;
44 import org.glassfish.jersey.test.JerseyTest;
45 import org.junit.BeforeClass;
46 import org.junit.Ignore;
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.JsonNormalizedNodeBodyReader;
53 import org.opendaylight.controller.sal.rest.impl.NormalizedNodeJsonBodyWriter;
54 import org.opendaylight.controller.sal.rest.impl.NormalizedNodeXmlBodyWriter;
55 import org.opendaylight.controller.sal.rest.impl.RestconfApplication;
56 import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper;
57 import org.opendaylight.controller.sal.rest.impl.XmlNormalizedNodeBodyReader;
58 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
59 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
60 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
61 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
67 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
70 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
71 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
72 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
73 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
74 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
75 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.Module;
77 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
78 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
79 import org.w3c.dom.Document;
80 import org.w3c.dom.Element;
81 import org.w3c.dom.NodeList;
83 public class RestGetOperationTest extends JerseyTest {
85 static class NodeData {
87 Object data; // List for a CompositeNode, value Object for a SimpleNode
89 NodeData(final Object key, final Object data) {
95 private static BrokerFacade brokerFacade;
96 private static RestconfImpl restconfImpl;
97 private static SchemaContext schemaContextYangsIetf;
98 private static SchemaContext schemaContextTestModule;
99 private static NormalizedNode answerFromGet;
101 private static SchemaContext schemaContextModules;
102 private static SchemaContext schemaContextBehindMountPoint;
104 private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf";
107 public static void init() throws FileNotFoundException, ParseException {
108 schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
109 schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
110 brokerFacade = mock(BrokerFacade.class);
111 restconfImpl = RestconfImpl.getInstance();
112 restconfImpl.setBroker(brokerFacade);
113 answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
115 schemaContextModules = TestUtils.loadSchemaContext("/modules");
116 schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
120 protected Application configure() {
121 /* enable/disable Jersey logs to console */
122 // enable(TestProperties.LOG_TRAFFIC);
123 // enable(TestProperties.DUMP_ENTITY);
124 // enable(TestProperties.RECORD_LOG_LEVEL);
125 // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
126 ResourceConfig resourceConfig = new ResourceConfig();
127 resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
128 new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
129 resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
130 resourceConfig.registerClasses(new RestconfApplication().getClasses());
131 return resourceConfig;
134 private void setControllerContext(final SchemaContext schemaContext) {
135 final ControllerContext controllerContext = ControllerContext.getInstance();
136 controllerContext.setSchemas(schemaContext);
137 restconfImpl.setControllerContext(controllerContext);
141 * Tests of status codes for "/operational/{identifier}".
144 public void getOperationalStatusCodes() throws UnsupportedEncodingException {
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 UnsupportedEncodingException {
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.
172 public void getDataWithUrlMountPoint() throws UnsupportedEncodingException, URISyntaxException, ParseException {
173 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
174 prepareCnDataForMountPointTest(false));
175 final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
176 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
177 final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
178 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
180 ControllerContext.getInstance().setMountService(mockMountService);
182 String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/cont1";
183 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
185 uri = "/config/ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
186 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
190 * MountPoint test. URI represents mount point.
192 * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
193 * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
194 * InstanceIdentifier parameter in method
195 * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, YangInstanceIdentifier)} which is called in
196 * method {@link RestconfImpl#readConfigurationData}
198 * @throws ParseException
201 public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException,
203 final YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
204 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier))).thenReturn(
205 prepareCnDataForSlashesBehindMountPointTest());
206 final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
207 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
208 final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
209 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
211 ControllerContext.getInstance().setMountService(mockMountService);
213 final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
214 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
217 private YangInstanceIdentifier prepareInstanceIdentifierForList() throws URISyntaxException, ParseException {
218 final List<PathArgument> parameters = new ArrayList<>();
220 final Date revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-01-09");
221 final URI uri = new URI("test:module");
222 final QName qNameCont = QName.create(uri, revision, "cont");
223 final QName qNameList = QName.create(uri, revision, "lst1");
224 final QName qNameKeyList = QName.create(uri, revision, "lf11");
226 parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameCont));
227 parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameList));
228 parameters.add(new YangInstanceIdentifier.NodeIdentifierWithPredicates(qNameList, qNameKeyList,
229 "GigabitEthernet0/0/0/0"));
230 return YangInstanceIdentifier.create(parameters);
234 public void getDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException,
236 when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
237 prepareCnDataForMountPointTest(true));
238 final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
239 when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
240 final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
241 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
243 ControllerContext.getInstance().setMountService(mockMountService);
245 final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
246 assertEquals(200, get(uri, MediaType.APPLICATION_XML));
251 public void getModulesTest() throws UnsupportedEncodingException, FileNotFoundException {
252 final ControllerContext controllerContext = ControllerContext.getInstance();
253 controllerContext.setGlobalSchema(schemaContextModules);
254 restconfImpl.setControllerContext(controllerContext);
256 final String uri = "/modules";
258 Response response = target(uri).request("application/yang.api+json").get();
259 validateModulesResponseJson(response);
261 response = target(uri).request("application/yang.api+xml").get();
262 validateModulesResponseXml(response,schemaContextModules);
267 @Ignore // FIXME : find why it is fail by in gerrit build
268 public void getStreamsTest() throws UnsupportedEncodingException, FileNotFoundException {
269 setControllerContext(schemaContextModules);
271 final String uri = "/streams";
273 Response response = target(uri).request("application/yang.api+json").get();
274 final String responseBody = response.readEntity(String.class);
275 assertEquals(200, response.getStatus());
276 assertNotNull(responseBody);
277 assertTrue(responseBody.contains("streams"));
279 response = target(uri).request("application/yang.api+xml").get();
280 assertEquals(200, response.getStatus());
281 final Document responseXmlBody = response.readEntity(Document.class);
282 assertNotNull(responseXmlBody);
283 final Element rootNode = responseXmlBody.getDocumentElement();
285 assertEquals("streams", rootNode.getLocalName());
286 assertEquals(RESTCONF_NS, rootNode.getNamespaceURI());
291 public void getModuleTest() throws FileNotFoundException, UnsupportedEncodingException {
292 setControllerContext(schemaContextModules);
294 final String uri = "/modules/module/module2/2014-01-02";
296 Response response = target(uri).request("application/yang.api+xml").get();
297 assertEquals(200, response.getStatus());
298 final Document responseXml = response.readEntity(Document.class);
300 final QName qname = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
301 assertNotNull(qname);
303 assertEquals("module2", qname.getLocalName());
304 assertEquals("module:2", qname.getNamespace().toString());
305 assertEquals("2014-01-02", qname.getFormattedRevision());
307 response = target(uri).request("application/yang.api+json").get();
308 assertEquals(200, response.getStatus());
309 final String responseBody = response.readEntity(String.class);
310 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
312 final String[] split = responseBody.split("\"module\"");
313 assertEquals("\"module\" element is returned more then once", 2, split.length);
319 @Ignore // FIXME restconf-netconf yang schema has to be updated for operations container
320 public void getOperationsTest() throws FileNotFoundException, UnsupportedEncodingException {
321 setControllerContext(schemaContextModules);
323 final String uri = "/operations";
325 Response response = target(uri).request("application/yang.api+xml").get();
326 assertEquals(200, response.getStatus());
327 final Document responseDoc = response.readEntity(Document.class);
328 validateOperationsResponseXml(responseDoc, schemaContextModules);
330 response = target(uri).request("application/yang.api+json").get();
331 assertEquals(200, response.getStatus());
332 final String responseBody = response.readEntity(String.class);
333 assertTrue("Json response for /operations dummy-rpc1-module1 is incorrect",
334 validateOperationsResponseJson(responseBody, "dummy-rpc1-module1", "module1").find());
335 assertTrue("Json response for /operations dummy-rpc2-module1 is incorrect",
336 validateOperationsResponseJson(responseBody, "dummy-rpc2-module1", "module1").find());
337 assertTrue("Json response for /operations dummy-rpc1-module2 is incorrect",
338 validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
339 assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
340 validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
344 private void validateOperationsResponseXml(final Document responseDoc, final SchemaContext schemaContext) {
345 final Element operationsElem = responseDoc.getDocumentElement();
346 assertEquals(RESTCONF_NS, operationsElem.getNamespaceURI());
347 assertEquals("operations", operationsElem.getLocalName());
350 final HashSet<QName> foundOperations = new HashSet<>();
352 final NodeList operationsList = operationsElem.getChildNodes();
353 for(int i = 0;i < operationsList.getLength();i++) {
354 final org.w3c.dom.Node operation = operationsList.item(i);
356 final String namespace = operation.getNamespaceURI();
357 final String name = operation.getLocalName();
358 final QName opQName = QName.create(URI.create(namespace), null, name);
359 foundOperations.add(opQName);
362 for(final RpcDefinition schemaOp : schemaContext.getOperations()) {
363 assertTrue(foundOperations.contains(schemaOp.getQName().withoutRevision()));
368 // /operations/pathToMountPoint/yang-ext:mount
370 @Ignore // FIXME fix the way to provide operations overview functionality asap
371 public void getOperationsBehindMountPointTest() throws FileNotFoundException, UnsupportedEncodingException {
372 setControllerContext(schemaContextModules);
374 final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
375 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
376 final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
377 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
379 ControllerContext.getInstance().setMountService(mockMountService);
381 final String uri = "/operations/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
383 Response response = target(uri).request("application/yang.api+xml").get();
384 assertEquals(200, response.getStatus());
386 final Document responseDoc = response.readEntity(Document.class);
387 validateOperationsResponseXml(responseDoc, schemaContextBehindMountPoint);
389 response = target(uri).request("application/yang.api+json").get();
390 assertEquals(200, response.getStatus());
391 final String responseBody = response.readEntity(String.class);
392 assertTrue("Json response for /operations/mount_point rpc-behind-module1 is incorrect",
393 validateOperationsResponseJson(responseBody, "rpc-behind-module1", "module1-behind-mount-point").find());
394 assertTrue("Json response for /operations/mount_point rpc-behind-module2 is incorrect",
395 validateOperationsResponseJson(responseBody, "rpc-behind-module2", "module2-behind-mount-point").find());
399 private Matcher validateOperationsResponseJson(final String searchIn, final String rpcName, final String moduleName) {
400 final StringBuilder regex = new StringBuilder();
403 regex.append(".*\\{");
404 regex.append(".*\"");
406 // operations prefix optional
408 regex.append("ietf-restconf:");
410 // :operations prefix optional
412 regex.append("operations\"");
414 regex.append(".*\\{");
416 regex.append(".*\"" + moduleName);
418 regex.append(rpcName + "\"");
419 regex.append(".*\\[");
420 regex.append(".*null");
421 regex.append(".*\\]");
423 regex.append(".*\\}");
424 regex.append(".*\\}");
428 final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
429 return ptrn.matcher(searchIn);
433 private Matcher validateOperationsResponseXml(final String searchIn, final String rpcName, final String namespace) {
434 final StringBuilder regex = new StringBuilder();
438 regex.append(".*<operations");
439 regex.append(".*xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"");
443 regex.append(".*" + rpcName);
444 regex.append(".*" + namespace);
448 regex.append(".*</operations.*");
453 final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
454 return ptrn.matcher(searchIn);
457 // /restconf/modules/pathToMountPoint/yang-ext:mount
459 public void getModulesBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
460 setControllerContext(schemaContextModules);
462 final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
463 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
464 final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
465 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
467 ControllerContext.getInstance().setMountService(mockMountService);
469 final String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
471 Response response = target(uri).request("application/yang.api+json").get();
472 assertEquals(200, response.getStatus());
473 final String responseBody = response.readEntity(String.class);
476 "module1-behind-mount-point in json wasn't found",
477 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
478 responseBody).find());
480 "module2-behind-mount-point in json wasn't found",
481 prepareJsonRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point",
482 responseBody).find());
484 response = target(uri).request("application/yang.api+xml").get();
485 assertEquals(200, response.getStatus());
486 validateModulesResponseXml(response, schemaContextBehindMountPoint);
490 // /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
492 public void getModuleBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
493 setControllerContext(schemaContextModules);
495 final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
496 when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
497 final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
498 when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
500 ControllerContext.getInstance().setMountService(mockMountService);
502 final String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/module1-behind-mount-point/2014-02-03";
504 Response response = target(uri).request("application/yang.api+json").get();
505 assertEquals(200, response.getStatus());
506 final String responseBody = response.readEntity(String.class);
509 "module1-behind-mount-point in json wasn't found",
510 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
511 responseBody).find());
512 final String[] split = responseBody.split("\"module\"");
513 assertEquals("\"module\" element is returned more then once", 2, split.length);
515 response = target(uri).request("application/yang.api+xml").get();
516 assertEquals(200, response.getStatus());
517 final Document responseXml = response.readEntity(Document.class);
519 final QName module = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
521 assertEquals("module1-behind-mount-point", module.getLocalName());
522 assertEquals("2014-02-03", module.getFormattedRevision());
523 assertEquals("module:1:behind:mount:point", module.getNamespace().toString());
528 private void validateModulesResponseXml(final Response response, final SchemaContext schemaContext) {
529 assertEquals(200, response.getStatus());
530 final Document responseBody = response.readEntity(Document.class);
531 final NodeList moduleNodes = responseBody.getDocumentElement().getElementsByTagNameNS(RESTCONF_NS, "module");
533 assertTrue(moduleNodes.getLength() > 0);
535 final HashSet<QName> foundModules = new HashSet<>();
537 for(int i=0;i < moduleNodes.getLength();i++) {
538 final org.w3c.dom.Node module = moduleNodes.item(i);
540 final QName name = assertedModuleXmlToModuleQName(module);
541 foundModules.add(name);
544 assertAllModules(foundModules,schemaContext);
547 private void assertAllModules(final Set<QName> foundModules, final SchemaContext schemaContext) {
548 for(final Module module : schemaContext.getModules()) {
549 final QName current = QName.create(module.getQNameModule(),module.getName());
550 assertTrue("Module not found in response.",foundModules.contains(current));
555 private QName assertedModuleXmlToModuleQName(final org.w3c.dom.Node module) {
556 assertEquals("module", module.getLocalName());
557 assertEquals(RESTCONF_NS, module.getNamespaceURI());
558 String revision = null;
559 String namespace = null;
563 final NodeList childNodes = module.getChildNodes();
565 for(int i =0;i < childNodes.getLength(); i++) {
566 final org.w3c.dom.Node child = childNodes.item(i);
567 assertEquals(RESTCONF_NS, child.getNamespaceURI());
569 switch(child.getLocalName()) {
571 assertNull("Name element appeared multiple times",name);
572 name = child.getTextContent().trim();
575 assertNull("Revision element appeared multiple times",revision);
576 revision = child.getTextContent().trim();
580 assertNull("Namespace element appeared multiple times",namespace);
581 namespace = child.getTextContent().trim();
586 assertNotNull("Revision was not part of xml",revision);
587 assertNotNull("Module namespace was not part of xml",namespace);
588 assertNotNull("Module identiffier was not part of xml",name);
591 // TODO Auto-generated method stub
593 return QName.create(namespace,revision,name);
596 private void validateModulesResponseJson(final Response response) {
597 assertEquals(200, response.getStatus());
598 final String responseBody = response.readEntity(String.class);
600 assertTrue("Module1 in json wasn't found", prepareJsonRegex("module1", "2014-01-01", "module:1", responseBody)
602 assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
604 assertTrue("Module3 in json wasn't found", prepareJsonRegex("module3", "2014-01-03", "module:3", responseBody)
608 private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
609 final String searchIn) {
610 final StringBuilder regex = new StringBuilder();
613 regex.append(".*\\{");
614 regex.append(".*\"name\"");
616 regex.append(".*\"" + module + "\",");
618 regex.append(".*\"revision\"");
620 regex.append(".*\"" + revision + "\",");
622 regex.append(".*\"namespace\"");
624 regex.append(".*\"" + namespace + "\"");
626 regex.append(".*\\}");
630 final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
631 return ptrn.matcher(searchIn);
636 private void prepareMockForModulesTest(final ControllerContext mockedControllerContext)
637 throws FileNotFoundException {
638 final SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
639 mockedControllerContext.setGlobalSchema(schemaContext);
640 // when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
643 private int get(final String uri, final String mediaType) {
644 return target(uri).request(mediaType).get().getStatus();
654 private NormalizedNode prepareCnDataForMountPointTest(final boolean wrapToCont) throws URISyntaxException, ParseException {
655 final String testModuleDate = "2014-01-09";
656 final ContainerNode contChild = Builders
658 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont1", "test:module", testModuleDate))
660 Builders.leafBuilder()
661 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", testModuleDate))
662 .withValue("lf11 value").build()).build();
665 return Builders.containerBuilder()
666 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont", "test:module", testModuleDate))
667 .withChild(contChild).build();
673 private void mockReadOperationalDataMethod() {
674 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
677 private void mockReadConfigurationDataMethod() {
678 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
681 private NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws ParseException {
682 return ImmutableMapEntryNodeBuilder
685 TestUtils.getNodeIdentifierPredicate("lst1", "test:module", "2014-01-09", "lf11",
686 "GigabitEthernet0/0/0/0"))
688 ImmutableLeafNodeBuilder.create()
689 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", "2014-01-09"))
690 .withValue("GigabitEthernet0/0/0/0").build()).build();
695 * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
697 * @throws UnsupportedEncodingException
700 public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
701 getDataWithUriIncludeWhiteCharsParameter("config");
702 getDataWithUriIncludeWhiteCharsParameter("operational");
705 private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws UnsupportedEncodingException {
706 mockReadConfigurationDataMethod();
707 mockReadOperationalDataMethod();
708 final String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
709 Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
710 final String xmlData = response.readEntity(String.class);
712 Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
713 Matcher matcher = pattern.matcher(xmlData);
714 // XML element can't surrounded with white character (e.g "> " or
716 assertFalse(matcher.matches());
718 response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
719 final String jsonData = response.readEntity(String.class);
720 pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
721 matcher = pattern.matcher(jsonData);
722 // JSON element can't surrounded with white character (e.g "} ", " {",
723 // "] ", " [", " :" or ": ")
724 assertFalse(matcher.matches());
729 public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
730 setControllerContext(schemaContextModules);
732 final CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
733 toNestedQName("depth1-cont"),
735 toNestedQName("depth2-cont1"),
737 toNestedQName("depth3-cont1"),
738 toCompositeNodeData(toNestedQName("depth4-cont1"),
739 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
740 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
741 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
743 toNestedQName("depth2-cont2"),
745 toNestedQName("depth3-cont2"),
746 toCompositeNodeData(toNestedQName("depth4-cont2"),
747 toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
748 toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
749 toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
750 toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
752 final Module module = TestUtils.findModule(schemaContextModules.getModules(), "nested-module");
753 assertNotNull(module);
755 final DataSchemaNode dataSchemaNode = TestUtils.resolveDataSchemaNode("depth1-cont", module);
756 assertNotNull(dataSchemaNode);
758 when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(
759 TestUtils.compositeNodeToDatastoreNormalizedNode(depth1Cont, dataSchemaNode));
761 // Test config with depth 1
763 Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
764 .request("application/xml").get();
766 verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
768 // Test config with depth 2
770 response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
774 // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
775 // Response mr=mock(Response.class);
776 // when(mr.getEntity()).thenReturn( new
777 // java.io.StringBufferInputStream(xml) );
781 expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
782 expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
784 // Test config with depth 3
786 response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
793 expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
794 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
795 expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
796 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
797 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
799 // Test config with depth 4
801 response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
810 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
811 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
812 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
815 expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
816 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
817 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
818 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
820 // Test config with depth 5
822 response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
833 expectContainer("depth4-cont1",
834 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
835 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
836 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
841 expectContainer("depth4-cont2",
842 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
843 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
844 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
845 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
847 // Test config with depth unbounded
849 response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
850 .request("application/xml").get();
860 expectContainer("depth4-cont1",
861 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
862 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
863 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
868 expectContainer("depth4-cont2",
869 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
870 expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
871 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
872 expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
876 final CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
877 toNestedQName("depth2-cont1"),
879 toNestedQName("depth3-cont1"),
880 toCompositeNodeData(toNestedQName("depth4-cont1"),
881 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
882 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
883 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
885 assertTrue(dataSchemaNode instanceof DataNodeContainer);
886 DataSchemaNode depth2cont1Schema = null;
887 for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
888 if (childNode.getQName().getLocalName().equals("depth2-cont1")) {
889 depth2cont1Schema = childNode;
893 assertNotNull(depth2Cont1);
895 when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(
896 TestUtils.compositeNodeToDatastoreNormalizedNode(depth2Cont1, depth2cont1Schema));
898 response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
899 .request("application/xml").get();
905 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
906 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
907 expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
911 * Tests behavior when invalid value of depth URI parameter
915 public void getDataWithInvalidDepthParameterTest() {
916 setControllerContext(schemaContextModules);
918 final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
919 paramMap.putSingle("depth", "1o");
920 final UriInfo mockInfo = mock(UriInfo.class);
921 when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
923 public MultivaluedMap<String, String> answer(final InvocationOnMock invocation) {
928 getDataWithInvalidDepthParameterTest(mockInfo);
930 paramMap.putSingle("depth", "0");
931 getDataWithInvalidDepthParameterTest(mockInfo);
933 paramMap.putSingle("depth", "-1");
934 getDataWithInvalidDepthParameterTest(mockInfo);
937 private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
939 final QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
940 final YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
941 final NormalizedNode value = (Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build());
942 when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value);
943 restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
944 fail("Expected RestconfDocumentedException");
945 } catch (final RestconfDocumentedException e) {
946 assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
947 .getErrorMessage().contains("depth"));
951 private void verifyXMLResponse(final Response response, final NodeData nodeData) {
952 final Document doc = response.readEntity(Document.class);
953 // Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
954 // System.out.println();
955 assertNotNull("Could not parse XML document", doc);
957 // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
959 verifyContainerElement(doc.getDocumentElement(), nodeData);
962 @SuppressWarnings("unchecked")
963 private void verifyContainerElement(final Element element, final NodeData nodeData) {
965 assertEquals("Element local name", nodeData.key, element.getLocalName());
967 final NodeList childNodes = element.getChildNodes();
968 if (nodeData.data == null) { // empty container
969 assertTrue("Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
973 final Map<String, NodeData> expChildMap = Maps.newHashMap();
974 for (final NodeData expChild : (List<NodeData>) nodeData.data) {
975 expChildMap.put(expChild.key.toString(), expChild);
978 for (int i = 0; i < childNodes.getLength(); i++) {
979 final org.w3c.dom.Node actualChild = childNodes.item(i);
980 if (!(actualChild instanceof Element)) {
984 final Element actualElement = (Element) actualChild;
985 final NodeData expChild = expChildMap.remove(actualElement.getLocalName());
987 "Unexpected child element for parent \"" + element.getLocalName() + "\": "
988 + actualElement.getLocalName(), expChild);
990 if (expChild.data == null || expChild.data instanceof List) {
991 verifyContainerElement(actualElement, expChild);
993 assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data,
994 actualElement.getTextContent());
998 if (!expChildMap.isEmpty()) {
999 fail("Missing elements for parent \"" + element.getLocalName() + "\": " + expChildMap.keySet());
1003 private NodeData expectContainer(final String name, final NodeData... childData) {
1004 return new NodeData(name, Lists.newArrayList(childData));
1007 private NodeData expectEmptyContainer(final String name) {
1008 return new NodeData(name, null);
1011 private NodeData expectLeaf(final String name, final Object value) {
1012 return new NodeData(name, value);
1015 private QName toNestedQName(final String localName) {
1016 return QName.create("urn:nested:module", "2014-06-3", localName);
1019 @SuppressWarnings("unchecked")
1020 private CompositeNode toCompositeNode(final NodeData nodeData) {
1021 final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
1022 builder.setQName((QName) nodeData.key);
1024 for (final NodeData child : (List<NodeData>) nodeData.data) {
1025 if (child.data instanceof List) {
1026 builder.add(toCompositeNode(child));
1028 builder.addLeaf((QName) child.key, child.data);
1032 return builder.toInstance();
1035 private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
1036 return new NodeData(key, Lists.newArrayList(childData));
1039 private NodeData toSimpleNodeData(final QName key, final Object value) {
1040 return new NodeData(key, value);