536d140cf1b78e05b7a3e77d38e43a32d8a1f8f4
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / RestGetOperationTest.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.sal.restconf.impl.test;
9
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.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.mockito.Matchers.any;
16 import static org.mockito.Matchers.eq;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.when;
19
20 import com.google.common.collect.Lists;
21 import com.google.common.collect.Maps;
22 import java.io.FileNotFoundException;
23 import java.io.InputStream;
24 import java.io.UnsupportedEncodingException;
25 import java.net.URI;
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.List;
32 import java.util.Map;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35 import javax.ws.rs.core.Application;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.MultivaluedHashMap;
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.UriInfo;
41 import org.glassfish.jersey.server.ResourceConfig;
42 import org.glassfish.jersey.test.JerseyTest;
43 import org.junit.BeforeClass;
44 import org.junit.Test;
45 import org.mockito.invocation.InvocationOnMock;
46 import org.mockito.stubbing.Answer;
47 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
48 import org.opendaylight.controller.sal.core.api.mount.MountService;
49 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
50 import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper;
51 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
52 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
53 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
54 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
55 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
56 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
57 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
58 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
59 import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
60 import org.opendaylight.yangtools.yang.common.QName;
61 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
62 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
64 import org.opendaylight.yangtools.yang.data.api.Node;
65 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
66 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.w3c.dom.Document;
69 import org.w3c.dom.Element;
70 import org.w3c.dom.NodeList;
71
72 public class RestGetOperationTest extends JerseyTest {
73
74     static class NodeData {
75         Object key;
76         Object data; // List for a CompositeNode, value Object for a SimpleNode
77
78         NodeData(final Object key, final Object data) {
79             this.key = key;
80             this.data = data;
81         }
82     }
83
84     private static BrokerFacade brokerFacade;
85     private static RestconfImpl restconfImpl;
86     private static SchemaContext schemaContextYangsIetf;
87     private static SchemaContext schemaContextTestModule;
88     private static CompositeNode answerFromGet;
89
90     private static SchemaContext schemaContextModules;
91     private static SchemaContext schemaContextBehindMountPoint;
92
93     @BeforeClass
94     public static void init() throws FileNotFoundException {
95         schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
96         schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
97         ControllerContext controllerContext = ControllerContext.getInstance();
98         controllerContext.setSchemas(schemaContextYangsIetf);
99         brokerFacade = mock(BrokerFacade.class);
100         restconfImpl = RestconfImpl.getInstance();
101         restconfImpl.setBroker(brokerFacade);
102         restconfImpl.setControllerContext(controllerContext);
103         answerFromGet = prepareCompositeNodeWithIetfInterfacesInterfacesData();
104
105         schemaContextModules = TestUtils.loadSchemaContext("/modules");
106         schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
107     }
108
109     @Override
110     protected Application configure() {
111         /* enable/disable Jersey logs to console */
112         // enable(TestProperties.LOG_TRAFFIC);
113         // enable(TestProperties.DUMP_ENTITY);
114         // enable(TestProperties.RECORD_LOG_LEVEL);
115         // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
116         ResourceConfig resourceConfig = new ResourceConfig();
117         resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
118                 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
119                 JsonToCompositeNodeProvider.INSTANCE);
120         resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
121         return resourceConfig;
122     }
123
124     /**
125      * Tests of status codes for "/operational/{identifier}".
126      */
127     @Test
128     public void getOperationalStatusCodes() throws UnsupportedEncodingException {
129         mockReadOperationalDataMethod();
130         String uri = "/operational/ietf-interfaces:interfaces/interface/eth0";
131         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
132
133         uri = "/operational/wrong-module:interfaces/interface/eth0";
134         assertEquals(400, get(uri, MediaType.APPLICATION_XML));
135     }
136
137     /**
138      * Tests of status codes for "/config/{identifier}".
139      */
140     @Test
141     public void getConfigStatusCodes() throws UnsupportedEncodingException {
142         mockReadConfigurationDataMethod();
143         String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
144         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
145
146         uri = "/config/wrong-module:interfaces/interface/eth0";
147         assertEquals(400, get(uri, MediaType.APPLICATION_XML));
148     }
149
150     /**
151      * MountPoint test. URI represents mount point.
152      */
153     @Test
154     public void getDataWithUrlMountPoint() throws UnsupportedEncodingException, URISyntaxException {
155         when(
156                 brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class),
157                         any(InstanceIdentifier.class))).thenReturn(prepareCnDataForMountPointTest());
158         MountInstance mountInstance = mock(MountInstance.class);
159         when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
160         MountService mockMountService = mock(MountService.class);
161         when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
162
163         ControllerContext.getInstance().setMountService(mockMountService);
164
165         String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/cont1";
166         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
167
168         uri = "/config/ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
169         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
170     }
171
172     /**
173      * MountPoint test. URI represents mount point.
174      *
175      * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
176      * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
177      * InstanceIdentifier parameter in method
178      * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, InstanceIdentifier)} which is called in
179      * method {@link RestconfImpl#readConfigurationData}
180      *
181      *
182      * @throws ParseException
183      */
184     @Test
185     public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException,
186             ParseException {
187         InstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
188         when(
189                 brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class),
190                         eq(awaitedInstanceIdentifier))).thenReturn(prepareCnDataForMountPointTest());
191         MountInstance mountInstance = mock(MountInstance.class);
192         when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
193         MountService mockMountService = mock(MountService.class);
194         when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
195
196         ControllerContext.getInstance().setMountService(mockMountService);
197
198         String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
199         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
200     }
201
202     private InstanceIdentifier prepareInstanceIdentifierForList() throws URISyntaxException, ParseException {
203         List<PathArgument> parameters = new ArrayList<>();
204
205         Date revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-01-09");
206         URI uri = new URI("test:module");
207         QName qNameCont = QName.create(uri, revision, "cont");
208         QName qNameList = QName.create(uri, revision, "lst1");
209         QName qNameKeyList = QName.create(uri, revision, "lf11");
210
211         parameters.add(new InstanceIdentifier.NodeIdentifier(qNameCont));
212         parameters.add(new InstanceIdentifier.NodeIdentifierWithPredicates(qNameList, qNameKeyList,
213                 "GigabitEthernet0/0/0/0"));
214         return InstanceIdentifier.create(parameters);
215     }
216
217     @Test
218     public void getDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException {
219         when(
220                 brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class),
221                         any(InstanceIdentifier.class))).thenReturn(prepareCnDataForMountPointTest());
222         MountInstance mountInstance = mock(MountInstance.class);
223         when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
224         MountService mockMountService = mock(MountService.class);
225         when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
226
227         ControllerContext.getInstance().setMountService(mockMountService);
228
229         String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
230         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
231     }
232
233     // /modules
234     @Test
235     public void getModulesTest() throws UnsupportedEncodingException, FileNotFoundException {
236         ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
237
238         String uri = "/modules";
239
240         Response response = target(uri).request("application/yang.api+json").get();
241         validateModulesResponseJson(response);
242
243         response = target(uri).request("application/yang.api+xml").get();
244         validateModulesResponseXml(response);
245     }
246
247     // /streams/
248     @Test
249     public void getStreamsTest() throws UnsupportedEncodingException, FileNotFoundException {
250         ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
251
252         String uri = "/streams";
253
254         Response response = target(uri).request("application/yang.api+json").get();
255         String responseBody = response.readEntity(String.class);
256         assertNotNull(responseBody);
257         assertTrue(responseBody.contains("streams"));
258
259         response = target(uri).request("application/yang.api+xml").get();
260         responseBody = response.readEntity(String.class);
261         assertNotNull(responseBody);
262         assertTrue(responseBody.contains("<streams xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\""));
263     }
264
265     // /modules/module
266     @Test
267     public void getModuleTest() throws FileNotFoundException, UnsupportedEncodingException {
268         ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
269
270         String uri = "/modules/module/module2/2014-01-02";
271
272         Response response = target(uri).request("application/yang.api+xml").get();
273         assertEquals(200, response.getStatus());
274         String responseBody = response.readEntity(String.class);
275         assertTrue("Module2 in xml wasn't found", prepareXmlRegex("module2", "2014-01-02", "module:2", responseBody)
276                 .find());
277         String[] split = responseBody.split("<module");
278         assertEquals("<module element is returned more then once", 2, split.length);
279
280         response = target(uri).request("application/yang.api+json").get();
281         assertEquals(200, response.getStatus());
282         responseBody = response.readEntity(String.class);
283         assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
284                 .find());
285         split = responseBody.split("\"module\"");
286         assertEquals("\"module\" element is returned more then once", 2, split.length);
287
288     }
289
290     // /operations
291     @Test
292     public void getOperationsTest() throws FileNotFoundException, UnsupportedEncodingException {
293         ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
294
295         String uri = "/operations";
296
297         Response response = target(uri).request("application/yang.api+xml").get();
298         assertEquals(200, response.getStatus());
299         String responseBody = response.readEntity(String.class);
300         assertTrue("Xml response for /operations dummy-rpc1-module1 is incorrect",
301                 validateOperationsResponseXml(responseBody, "dummy-rpc1-module1", "module:1").find());
302         assertTrue("Xml response for /operations dummy-rpc2-module1 is incorrect",
303                 validateOperationsResponseXml(responseBody, "dummy-rpc2-module1", "module:1").find());
304         assertTrue("Xml response for /operations dummy-rpc1-module2 is incorrect",
305                 validateOperationsResponseXml(responseBody, "dummy-rpc1-module2", "module:2").find());
306         assertTrue("Xml response for /operations dummy-rpc2-module2 is incorrect",
307                 validateOperationsResponseXml(responseBody, "dummy-rpc2-module2", "module:2").find());
308
309         response = target(uri).request("application/yang.api+json").get();
310         assertEquals(200, response.getStatus());
311         responseBody = response.readEntity(String.class);
312         assertTrue("Json response for /operations dummy-rpc1-module1 is incorrect",
313                 validateOperationsResponseJson(responseBody, "dummy-rpc1-module1", "module1").find());
314         assertTrue("Json response for /operations dummy-rpc2-module1 is incorrect",
315                 validateOperationsResponseJson(responseBody, "dummy-rpc2-module1", "module1").find());
316         assertTrue("Json response for /operations dummy-rpc1-module2 is incorrect",
317                 validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
318         assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
319                 validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
320
321     }
322
323     // /operations/pathToMountPoint/yang-ext:mount
324     @Test
325     public void getOperationsBehindMountPointTest() throws FileNotFoundException, UnsupportedEncodingException {
326         ControllerContext controllerContext = ControllerContext.getInstance();
327         controllerContext.setGlobalSchema(schemaContextModules);
328
329         MountInstance mountInstance = mock(MountInstance.class);
330         when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
331         MountService mockMountService = mock(MountService.class);
332         when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
333
334         controllerContext.setMountService(mockMountService);
335
336         String uri = "/operations/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
337
338         Response response = target(uri).request("application/yang.api+xml").get();
339         assertEquals(200, response.getStatus());
340         String responseBody = response.readEntity(String.class);
341         assertTrue("Xml response for /operations/mount_point rpc-behind-module1 is incorrect",
342                 validateOperationsResponseXml(responseBody, "rpc-behind-module1", "module:1:behind:mount:point").find());
343         assertTrue("Xml response for /operations/mount_point rpc-behind-module2 is incorrect",
344                 validateOperationsResponseXml(responseBody, "rpc-behind-module2", "module:2:behind:mount:point").find());
345
346         response = target(uri).request("application/yang.api+json").get();
347         assertEquals(200, response.getStatus());
348         responseBody = response.readEntity(String.class);
349         assertTrue("Json response for /operations/mount_point rpc-behind-module1 is incorrect",
350                 validateOperationsResponseJson(responseBody, "rpc-behind-module1", "module1-behind-mount-point").find());
351         assertTrue("Json response for /operations/mount_point rpc-behind-module2 is incorrect",
352                 validateOperationsResponseJson(responseBody, "rpc-behind-module2", "module2-behind-mount-point").find());
353
354     }
355
356     private Matcher validateOperationsResponseJson(final String searchIn, final String rpcName, final String moduleName) {
357         StringBuilder regex = new StringBuilder();
358         regex.append("^");
359
360         regex.append(".*\\{");
361         regex.append(".*\"");
362
363         // operations prefix optional
364         regex.append("(");
365         regex.append("ietf-restconf:");
366         regex.append("|)");
367         // :operations prefix optional
368
369         regex.append("operations\"");
370         regex.append(".*:");
371         regex.append(".*\\{");
372
373         regex.append(".*\"" + moduleName);
374         regex.append(":");
375         regex.append(rpcName + "\"");
376         regex.append(".*\\[");
377         regex.append(".*null");
378         regex.append(".*\\]");
379
380         regex.append(".*\\}");
381         regex.append(".*\\}");
382
383         regex.append(".*");
384         regex.append("$");
385         Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
386         return ptrn.matcher(searchIn);
387
388     }
389
390     private Matcher validateOperationsResponseXml(final String searchIn, final String rpcName, final String namespace) {
391         StringBuilder regex = new StringBuilder();
392
393         regex.append("^");
394
395         regex.append(".*<operations");
396         regex.append(".*xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"");
397         regex.append(".*>");
398
399         regex.append(".*<");
400         regex.append(".*" + rpcName);
401         regex.append(".*" + namespace);
402         regex.append(".*/");
403         regex.append(".*>");
404
405         regex.append(".*</operations.*");
406         regex.append(".*>");
407
408         regex.append(".*");
409         regex.append("$");
410         Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
411         return ptrn.matcher(searchIn);
412     }
413
414     // /restconf/modules/pathToMountPoint/yang-ext:mount
415     @Test
416     public void getModulesBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
417         ControllerContext controllerContext = ControllerContext.getInstance();
418         controllerContext.setGlobalSchema(schemaContextModules);
419
420         MountInstance mountInstance = mock(MountInstance.class);
421         when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
422         MountService mockMountService = mock(MountService.class);
423         when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
424
425         controllerContext.setMountService(mockMountService);
426
427         String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
428
429         Response response = target(uri).request("application/yang.api+json").get();
430         assertEquals(200, response.getStatus());
431         String responseBody = response.readEntity(String.class);
432
433         assertTrue(
434                 "module1-behind-mount-point in json wasn't found",
435                 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
436                         responseBody).find());
437         assertTrue(
438                 "module2-behind-mount-point in json wasn't found",
439                 prepareJsonRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point",
440                         responseBody).find());
441
442         response = target(uri).request("application/yang.api+xml").get();
443         assertEquals(200, response.getStatus());
444         responseBody = response.readEntity(String.class);
445         assertTrue(
446                 "module1-behind-mount-point in json wasn't found",
447                 prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody)
448                         .find());
449         assertTrue(
450                 "module2-behind-mount-point in json wasn't found",
451                 prepareXmlRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point", responseBody)
452                         .find());
453
454     }
455
456     // /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
457     @Test
458     public void getModuleBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
459         ControllerContext controllerContext = ControllerContext.getInstance();
460         controllerContext.setGlobalSchema(schemaContextModules);
461
462         MountInstance mountInstance = mock(MountInstance.class);
463         when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
464         MountService mockMountService = mock(MountService.class);
465         when(mockMountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
466
467         controllerContext.setMountService(mockMountService);
468
469         String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/module1-behind-mount-point/2014-02-03";
470
471         Response response = target(uri).request("application/yang.api+json").get();
472         assertEquals(200, response.getStatus());
473         String responseBody = response.readEntity(String.class);
474
475         assertTrue(
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());
479         String[] split = responseBody.split("\"module\"");
480         assertEquals("\"module\" element is returned more then once", 2, split.length);
481
482         response = target(uri).request("application/yang.api+xml").get();
483         assertEquals(200, response.getStatus());
484         responseBody = response.readEntity(String.class);
485         assertTrue(
486                 "module1-behind-mount-point in json wasn't found",
487                 prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody)
488                         .find());
489         split = responseBody.split("<module");
490         assertEquals("<module element is returned more then once", 2, split.length);
491
492     }
493
494     private void validateModulesResponseXml(final Response response) {
495         assertEquals(200, response.getStatus());
496         String responseBody = response.readEntity(String.class);
497
498         assertTrue("Module1 in xml wasn't found", prepareXmlRegex("module1", "2014-01-01", "module:1", responseBody)
499                 .find());
500         assertTrue("Module2 in xml wasn't found", prepareXmlRegex("module2", "2014-01-02", "module:2", responseBody)
501                 .find());
502         assertTrue("Module3 in xml wasn't found", prepareXmlRegex("module3", "2014-01-03", "module:3", responseBody)
503                 .find());
504     }
505
506     private void validateModulesResponseJson(final Response response) {
507         assertEquals(200, response.getStatus());
508         String responseBody = response.readEntity(String.class);
509
510         assertTrue("Module1 in json wasn't found", prepareJsonRegex("module1", "2014-01-01", "module:1", responseBody)
511                 .find());
512         assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
513                 .find());
514         assertTrue("Module3 in json wasn't found", prepareJsonRegex("module3", "2014-01-03", "module:3", responseBody)
515                 .find());
516     }
517
518     private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
519             final String searchIn) {
520         StringBuilder regex = new StringBuilder();
521         regex.append("^");
522
523         regex.append(".*\\{");
524         regex.append(".*\"name\"");
525         regex.append(".*:");
526         regex.append(".*\"" + module + "\",");
527
528         regex.append(".*\"revision\"");
529         regex.append(".*:");
530         regex.append(".*\"" + revision + "\",");
531
532         regex.append(".*\"namespace\"");
533         regex.append(".*:");
534         regex.append(".*\"" + namespace + "\"");
535
536         regex.append(".*\\}");
537
538         regex.append(".*");
539         regex.append("$");
540         Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
541         return ptrn.matcher(searchIn);
542
543     }
544
545     private Matcher prepareXmlRegex(final String module, final String revision, final String namespace,
546             final String searchIn) {
547         StringBuilder regex = new StringBuilder();
548         regex.append("^");
549
550         regex.append(".*<module.*");
551         regex.append(".*>");
552
553         regex.append(".*<name>");
554         regex.append(".*" + module);
555         regex.append(".*<\\/name>");
556
557         regex.append(".*<revision>");
558         regex.append(".*" + revision);
559         regex.append(".*<\\/revision>");
560
561         regex.append(".*<namespace>");
562         regex.append(".*" + namespace);
563         regex.append(".*<\\/namespace>");
564
565         regex.append(".*<\\/module.*>");
566
567         regex.append(".*");
568         regex.append("$");
569
570         Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
571         return ptrn.matcher(searchIn);
572     }
573
574     private void prepareMockForModulesTest(final ControllerContext mockedControllerContext)
575             throws FileNotFoundException {
576         SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
577         mockedControllerContext.setGlobalSchema(schemaContext);
578         // when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
579     }
580
581     private int get(final String uri, final String mediaType) {
582         return target(uri).request(mediaType).get().getStatus();
583     }
584
585     private CompositeNode prepareCnDataForMountPointTest() throws URISyntaxException {
586         CompositeNodeWrapper cont1 = new CompositeNodeWrapper(new URI("test:module"), "cont1");
587         SimpleNodeWrapper lf11 = new SimpleNodeWrapper(new URI("test:module"), "lf11", "lf11 value");
588         cont1.addValue(lf11);
589         return cont1.unwrap();
590     }
591
592     private void mockReadOperationalDataMethod() {
593         when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(answerFromGet);
594     }
595
596     private void mockReadConfigurationDataMethod() {
597         when(brokerFacade.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(answerFromGet);
598     }
599
600     private static CompositeNode prepareCompositeNodeWithIetfInterfacesInterfacesData() {
601         CompositeNode intface;
602         try {
603             intface = new CompositeNodeWrapper(new URI("interface"), "interface");
604             List<Node<?>> childs = new ArrayList<>();
605
606             childs.add(new SimpleNodeWrapper(new URI("name"), "name", "eth0"));
607             childs.add(new SimpleNodeWrapper(new URI("type"), "type", "ethernetCsmacd"));
608             childs.add(new SimpleNodeWrapper(new URI("enabled"), "enabled", Boolean.FALSE));
609             childs.add(new SimpleNodeWrapper(new URI("description"), "description", "some interface"));
610             intface.setValue(childs);
611             return intface;
612         } catch (URISyntaxException e) {
613         }
614
615         return null;
616     }
617
618     /**
619      * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
620      *
621      * @throws UnsupportedEncodingException
622      */
623     @Test
624     public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
625         getDataWithUriIncludeWhiteCharsParameter("config");
626         getDataWithUriIncludeWhiteCharsParameter("operational");
627     }
628
629     private void getDataWithUriIncludeWhiteCharsParameter(String target) throws UnsupportedEncodingException {
630         mockReadConfigurationDataMethod();
631         String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
632         Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
633         String xmlData = response.readEntity(String.class);
634
635         Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
636         Matcher matcher = pattern.matcher(xmlData);
637         // XML element can't surrounded with white character (e.g ">    " or
638         // "    <")
639         assertFalse(matcher.matches());
640
641         response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
642         String jsonData = response.readEntity(String.class);
643         pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
644         matcher = pattern.matcher(jsonData);
645         // JSON element can't surrounded with white character (e.g "} ", " {",
646         // "] ", " [", " :" or ": ")
647         assertFalse(matcher.matches());
648     }
649
650     @Test
651     public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
652
653         ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
654
655         CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
656                 toNestedQName("depth1-cont"),
657                 toCompositeNodeData(
658                         toNestedQName("depth2-cont1"),
659                         toCompositeNodeData(
660                                 toNestedQName("depth3-cont1"),
661                                 toCompositeNodeData(toNestedQName("depth4-cont1"),
662                                         toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
663                                 toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
664                         toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
665                 toCompositeNodeData(
666                         toNestedQName("depth2-cont2"),
667                         toCompositeNodeData(
668                                 toNestedQName("depth3-cont2"),
669                                 toCompositeNodeData(toNestedQName("depth4-cont2"),
670                                         toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
671                                 toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
672                         toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
673                 toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
674
675         when(brokerFacade.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(depth1Cont);
676
677         // Test config with depth 1
678
679         Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
680                 .request("application/xml").get();
681
682         verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
683
684         // Test config with depth 2
685
686         response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
687                 .get();
688
689         // String
690         // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
691         // Response mr=mock(Response.class);
692         // when(mr.getEntity()).thenReturn( new
693         // java.io.StringBufferInputStream(xml) );
694
695         verifyXMLResponse(
696                 response,
697                 expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
698                         expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
699
700         // Test config with depth 3
701
702         response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
703                 .get();
704
705         verifyXMLResponse(
706                 response,
707                 expectContainer(
708                         "depth1-cont",
709                         expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
710                                 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
711                         expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
712                                 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
713                         expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
714
715         // Test config with depth 4
716
717         response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
718                 .get();
719
720         verifyXMLResponse(
721                 response,
722                 expectContainer(
723                         "depth1-cont",
724                         expectContainer(
725                                 "depth2-cont1",
726                                 expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
727                                         expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
728                                 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
729                         expectContainer(
730                                 "depth2-cont2",
731                                 expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
732                                         expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
733                                 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
734                         expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
735
736         // Test config with depth 5
737
738         response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
739                 .get();
740
741         verifyXMLResponse(
742                 response,
743                 expectContainer(
744                         "depth1-cont",
745                         expectContainer(
746                                 "depth2-cont1",
747                                 expectContainer(
748                                         "depth3-cont1",
749                                         expectContainer("depth4-cont1",
750                                                 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
751                                         expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
752                                 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
753                         expectContainer(
754                                 "depth2-cont2",
755                                 expectContainer(
756                                         "depth3-cont2",
757                                         expectContainer("depth4-cont2",
758                                                 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
759                                         expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
760                                 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
761                         expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
762
763         // Test config with depth unbounded
764
765         response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
766                 .request("application/xml").get();
767
768         verifyXMLResponse(
769                 response,
770                 expectContainer(
771                         "depth1-cont",
772                         expectContainer(
773                                 "depth2-cont1",
774                                 expectContainer(
775                                         "depth3-cont1",
776                                         expectContainer("depth4-cont1",
777                                                 expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
778                                         expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
779                                 expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
780                         expectContainer(
781                                 "depth2-cont2",
782                                 expectContainer(
783                                         "depth3-cont2",
784                                         expectContainer("depth4-cont2",
785                                                 expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
786                                         expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
787                                 expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
788                         expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
789
790         // Test operational
791
792         CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
793                 toNestedQName("depth2-cont1"),
794                 toCompositeNodeData(
795                         toNestedQName("depth3-cont1"),
796                         toCompositeNodeData(toNestedQName("depth4-cont1"),
797                                 toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
798                         toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
799                 toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
800
801         when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(depth2Cont1);
802
803         response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
804                 .request("application/xml").get();
805
806         verifyXMLResponse(
807                 response,
808                 expectContainer(
809                         "depth2-cont1",
810                         expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
811                                 expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
812                         expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
813     }
814
815     @Test
816     public void getDataWithInvalidDepthParameterTest() {
817
818         ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
819
820         final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
821         paramMap.putSingle("depth", "1o");
822         UriInfo mockInfo = mock(UriInfo.class);
823         when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
824             @Override
825             public MultivaluedMap<String, String> answer(final InvocationOnMock invocation) {
826                 return paramMap;
827             }
828         });
829
830         getDataWithInvalidDepthParameterTest(mockInfo);
831
832         paramMap.putSingle("depth", "0");
833         getDataWithInvalidDepthParameterTest(mockInfo);
834
835         paramMap.putSingle("depth", "-1");
836         getDataWithInvalidDepthParameterTest(mockInfo);
837     }
838
839     private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
840         try {
841             restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
842             fail("Expected RestconfDocumentedException");
843         } catch (RestconfDocumentedException e) {
844             assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
845                     .getErrorMessage().contains("depth"));
846         }
847     }
848
849     private void verifyXMLResponse(final Response response, final NodeData nodeData) {
850
851         Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
852         assertNotNull("Could not parse XML document", doc);
853
854         // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
855
856         verifyContainerElement(doc.getDocumentElement(), nodeData);
857     }
858
859     @SuppressWarnings("unchecked")
860     private void verifyContainerElement(final Element element, final NodeData nodeData) {
861
862         assertEquals("Element local name", nodeData.key, element.getNodeName());
863
864         NodeList childNodes = element.getChildNodes();
865         if (nodeData.data == null) { // empty container
866             assertTrue("Expected no child elements for \"" + element.getNodeName() + "\"", childNodes.getLength() == 0);
867             return;
868         }
869
870         Map<String, NodeData> expChildMap = Maps.newHashMap();
871         for (NodeData expChild : (List<NodeData>) nodeData.data) {
872             expChildMap.put(expChild.key.toString(), expChild);
873         }
874
875         for (int i = 0; i < childNodes.getLength(); i++) {
876             org.w3c.dom.Node actualChild = childNodes.item(i);
877             if (!(actualChild instanceof Element)) {
878                 continue;
879             }
880
881             Element actualElement = (Element) actualChild;
882             NodeData expChild = expChildMap.remove(actualElement.getNodeName());
883             assertNotNull(
884                     "Unexpected child element for parent \"" + element.getNodeName() + "\": "
885                             + actualElement.getNodeName(), expChild);
886
887             if (expChild.data == null || expChild.data instanceof List) {
888                 verifyContainerElement(actualElement, expChild);
889             } else {
890                 assertEquals("Text content for element: " + actualElement.getNodeName(), expChild.data,
891                         actualElement.getTextContent());
892             }
893         }
894
895         if (!expChildMap.isEmpty()) {
896             fail("Missing elements for parent \"" + element.getNodeName() + "\": " + expChildMap.keySet());
897         }
898     }
899
900     private NodeData expectContainer(final String name, final NodeData... childData) {
901         return new NodeData(name, Lists.newArrayList(childData));
902     }
903
904     private NodeData expectEmptyContainer(final String name) {
905         return new NodeData(name, null);
906     }
907
908     private NodeData expectLeaf(final String name, final Object value) {
909         return new NodeData(name, value);
910     }
911
912     private QName toNestedQName(final String localName) {
913         return QName.create("urn:nested:module", "2014-06-3", localName);
914     }
915
916     @SuppressWarnings("unchecked")
917     private CompositeNode toCompositeNode(final NodeData nodeData) {
918         CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
919         builder.setQName((QName) nodeData.key);
920
921         for (NodeData child : (List<NodeData>) nodeData.data) {
922             if (child.data instanceof List) {
923                 builder.add(toCompositeNode(child));
924             } else {
925                 builder.addLeaf((QName) child.key, child.data);
926             }
927         }
928
929         return builder.toInstance();
930     }
931
932     private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
933         return new NodeData(key, Lists.newArrayList(childData));
934     }
935
936     private NodeData toSimpleNodeData(final QName key, final Object value) {
937         return new NodeData(key, value);
938     }
939 }