65fa8e08a0dc46e9c789c7945f9f0c6b4d59a240
[netconf.git] / restconf / restconf-nb-bierman02 / 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.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;
21
22 import com.google.common.collect.ImmutableMap;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32 import javax.ws.rs.core.Application;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.MultivaluedHashMap;
35 import javax.ws.rs.core.MultivaluedMap;
36 import javax.ws.rs.core.Response;
37 import javax.ws.rs.core.UriInfo;
38 import org.glassfish.jersey.server.ResourceConfig;
39 import org.glassfish.jersey.test.JerseyTest;
40 import org.junit.BeforeClass;
41 import org.junit.Ignore;
42 import org.junit.Test;
43 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
44 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
45 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
46 import org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService;
47 import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
48 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
49 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter;
50 import org.opendaylight.netconf.sal.rest.impl.RestconfDocumentedExceptionMapper;
51 import org.opendaylight.netconf.sal.rest.impl.XmlNormalizedNodeBodyReader;
52 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
53 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
54 import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
55 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
61 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
63 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
64 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
65 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
66 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
67 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
68 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
69 import org.opendaylight.yangtools.yang.model.api.Module;
70 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.w3c.dom.Document;
73 import org.w3c.dom.Element;
74 import org.w3c.dom.NodeList;
75
76 public class RestGetOperationTest extends JerseyTest {
77
78     static class NodeData {
79         Object key;
80         Object data; // List for a CompositeNode, value Object for a SimpleNode
81
82         NodeData(final Object key, final Object data) {
83             this.key = key;
84             this.data = data;
85         }
86     }
87
88     private static EffectiveModelContext schemaContextYangsIetf;
89     private static EffectiveModelContext schemaContextTestModule;
90     private static EffectiveModelContext schemaContextModules;
91     private static EffectiveModelContext schemaContextBehindMountPoint;
92
93     private static NormalizedNode answerFromGet;
94
95     private BrokerFacade brokerFacade;
96     private RestconfImpl restconfImpl;
97     private ControllerContext controllerContext;
98     private DOMMountPoint mountInstance;
99
100     private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf";
101
102     @BeforeClass
103     public static void init() throws Exception {
104         schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
105         schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
106         schemaContextModules = TestUtils.loadSchemaContext("/modules");
107         schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
108
109         answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
110     }
111
112     @Override
113     protected Application configure() {
114         /* enable/disable Jersey logs to console */
115         // enable(TestProperties.LOG_TRAFFIC);
116         // enable(TestProperties.DUMP_ENTITY);
117         // enable(TestProperties.RECORD_LOG_LEVEL);
118         // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
119
120         mountInstance = mock(DOMMountPoint.class);
121         controllerContext = TestRestconfUtils.newControllerContext(schemaContextYangsIetf, mountInstance);
122         brokerFacade = mock(BrokerFacade.class);
123         restconfImpl = RestconfImpl.newInstance(brokerFacade, controllerContext);
124
125         ResourceConfig resourceConfig = new ResourceConfig();
126         resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
127             new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(controllerContext),
128             new JsonNormalizedNodeBodyReader(controllerContext),
129             new RestconfDocumentedExceptionMapper(controllerContext));
130         return resourceConfig;
131     }
132
133     private void setControllerContext(final EffectiveModelContext schemaContext) {
134         controllerContext.setSchemas(schemaContext);
135     }
136
137     /**
138      * Tests of status codes for "/operational/{identifier}".
139      */
140     @Test
141     public void getOperationalStatusCodes() throws Exception {
142         setControllerContext(schemaContextYangsIetf);
143         mockReadOperationalDataMethod();
144         String uri = "/operational/ietf-interfaces:interfaces/interface/eth0";
145         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
146
147         uri = "/operational/wrong-module:interfaces/interface/eth0";
148         assertEquals(400, get(uri, MediaType.APPLICATION_XML));
149     }
150
151     /**
152      * Tests of status codes for "/config/{identifier}".
153      */
154     @Test
155     public void getConfigStatusCodes() throws Exception {
156         setControllerContext(schemaContextYangsIetf);
157         mockReadConfigurationDataMethod();
158         String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
159         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
160
161         uri = "/config/wrong-module:interfaces/interface/eth0";
162         assertEquals(400, get(uri, MediaType.APPLICATION_XML));
163     }
164
165     /**
166      * MountPoint test. URI represents mount point.
167      */
168     @Test
169     public void getDataWithUrlMountPoint() throws Exception {
170         when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
171                 isNull())).thenReturn(prepareCnDataForMountPointTest(false));
172         when(mountInstance.getService(DOMSchemaService.class))
173                 .thenReturn(Optional.of(FixedDOMSchemaService.of(schemaContextTestModule)));
174
175         String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/cont1";
176         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
177
178         uri = "/config/ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
179         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
180     }
181
182     /**
183      * MountPoint test. URI represents mount point.
184      * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
185      * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
186      * InstanceIdentifier parameter in method
187      * {@link BrokerFacade#readConfigurationData(DOMMountPoint, YangInstanceIdentifier)} which is called in
188      * method {@link RestconfImpl#readConfigurationData}
189      */
190     @Test
191     public void getDataWithSlashesBehindMountPoint() throws Exception {
192         final YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
193         when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier),
194                 isNull())).thenReturn(prepareCnDataForSlashesBehindMountPointTest());
195         when(mountInstance.getService(DOMSchemaService.class))
196                 .thenReturn(Optional.of(FixedDOMSchemaService.of(schemaContextTestModule)));
197
198         final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"
199                 + "test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
200         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
201     }
202
203     private static YangInstanceIdentifier prepareInstanceIdentifierForList() throws Exception {
204         final List<PathArgument> parameters = new ArrayList<>();
205
206         final QName qNameCont = newTestModuleQName("cont");
207         final QName qNameList = newTestModuleQName("lst1");
208         final QName qNameKeyList = newTestModuleQName("lf11");
209
210         parameters.add(new NodeIdentifier(qNameCont));
211         parameters.add(new NodeIdentifier(qNameList));
212         parameters.add(NodeIdentifierWithPredicates.of(qNameList, qNameKeyList, "GigabitEthernet0/0/0/0"));
213         return YangInstanceIdentifier.create(parameters);
214     }
215
216     private static QName newTestModuleQName(final String localPart) throws Exception {
217         return QName.create("test:module", "2014-01-09", localPart);
218     }
219
220     @Test
221     public void getDataMountPointIntoHighestElement() throws Exception {
222         when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
223                 isNull())).thenReturn(prepareCnDataForMountPointTest(true));
224         when(mountInstance.getService(DOMSchemaService.class))
225                 .thenReturn(Optional.of(FixedDOMSchemaService.of(schemaContextTestModule)));
226
227         final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
228         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
229     }
230
231     @Test
232     public void getDataWithIdentityrefInURL() throws Exception {
233         setControllerContext(schemaContextTestModule);
234
235         final QName moduleQN = newTestModuleQName("module");
236         final ImmutableMap<QName, Object> keyMap = ImmutableMap.of(
237                 newTestModuleQName("type"), newTestModuleQName("test-identity"),
238                 newTestModuleQName("name"), "foo");
239         final YangInstanceIdentifier iid = YangInstanceIdentifier.builder().node(newTestModuleQName("modules"))
240                 .node(moduleQN).nodeWithKey(moduleQN, keyMap).build();
241         final NormalizedNode data = ImmutableMapNodeBuilder.create()
242                 .withNodeIdentifier(new NodeIdentifier(moduleQN))
243                 .withChild(ImmutableNodes.mapEntryBuilder()
244                     .withNodeIdentifier(NodeIdentifierWithPredicates.of(moduleQN, keyMap))
245                     .withChild(ImmutableNodes.leafNode(newTestModuleQName("type"), newTestModuleQName("test-identity")))
246                     .withChild(ImmutableNodes.leafNode(newTestModuleQName("name"), "foo"))
247                     .withChild(ImmutableNodes.leafNode(newTestModuleQName("data"), "bar")).build()).build();
248         when(brokerFacade.readConfigurationData(iid, null)).thenReturn(data);
249
250         final String uri = "/config/test-module:modules/module/test-module:test-identity/foo";
251         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
252     }
253
254     // /modules
255     @Test
256     public void getModulesTest() throws Exception {
257         setControllerContext(schemaContextModules);
258
259         final String uri = "/modules";
260
261         Response response = target(uri).request("application/yang.api+json").get();
262         validateModulesResponseJson(response);
263
264         response = target(uri).request("application/yang.api+xml").get();
265         validateModulesResponseXml(response,schemaContextModules);
266     }
267
268     // /streams/
269     @Test
270     @Ignore // FIXME : find why it is fail by in gerrit build
271     public void getStreamsTest() throws Exception {
272         setControllerContext(schemaContextModules);
273
274         final String uri = "/streams";
275
276         Response response = target(uri).request("application/yang.api+json").get();
277         final String responseBody = response.readEntity(String.class);
278         assertEquals(200, response.getStatus());
279         assertNotNull(responseBody);
280         assertTrue(responseBody.contains("streams"));
281
282         response = target(uri).request("application/yang.api+xml").get();
283         assertEquals(200, response.getStatus());
284         final Document responseXmlBody = response.readEntity(Document.class);
285         assertNotNull(responseXmlBody);
286         final Element rootNode = responseXmlBody.getDocumentElement();
287
288         assertEquals("streams", rootNode.getLocalName());
289         assertEquals(RESTCONF_NS, rootNode.getNamespaceURI());
290     }
291
292     // /modules/module
293     @Test
294     public void getModuleTest() throws Exception {
295         setControllerContext(schemaContextModules);
296
297         final String uri = "/modules/module/module2/2014-01-02";
298
299         Response response = target(uri).request("application/yang.api+xml").get();
300         assertEquals(200, response.getStatus());
301         final Document responseXml = response.readEntity(Document.class);
302
303         final QName qname = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
304         assertNotNull(qname);
305
306         assertEquals("module2", qname.getLocalName());
307         assertEquals("module:2", qname.getNamespace().toString());
308         assertEquals("2014-01-02", qname.getRevision().get().toString());
309
310         response = target(uri).request("application/yang.api+json").get();
311         assertEquals(200, response.getStatus());
312         final String responseBody = response.readEntity(String.class);
313         assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
314                 .find());
315         final String[] split = responseBody.split("\"module\"");
316         assertEquals("\"module\" element is returned more then once", 2, split.length);
317
318     }
319
320     // /operations
321     @Ignore
322     @Test
323     public void getOperationsTest() throws Exception {
324         setControllerContext(schemaContextModules);
325
326         final String uri = "/operations";
327
328         Response response = target(uri).request("application/yang.api+xml").get();
329         assertEquals(500, response.getStatus());
330         final Document responseDoc = response.readEntity(Document.class);
331         validateOperationsResponseXml(responseDoc, schemaContextModules);
332
333         response = target(uri).request("application/yang.api+json").get();
334         assertEquals(200, response.getStatus());
335         final String responseBody = response.readEntity(String.class);
336         assertTrue("Json response for /operations dummy-rpc1-module1 is incorrect",
337                 validateOperationsResponseJson(responseBody, "dummy-rpc1-module1", "module1").find());
338         assertTrue("Json response for /operations dummy-rpc2-module1 is incorrect",
339                 validateOperationsResponseJson(responseBody, "dummy-rpc2-module1", "module1").find());
340         assertTrue("Json response for /operations dummy-rpc1-module2 is incorrect",
341                 validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
342         assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
343                 validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
344     }
345
346     private static void validateOperationsResponseXml(final Document responseDoc, final SchemaContext schemaContext) {
347
348         final Element operationsElem = responseDoc.getDocumentElement();
349         assertEquals(RESTCONF_NS, operationsElem.getNamespaceURI());
350         assertEquals("operations", operationsElem.getLocalName());
351
352         final NodeList operationsList = operationsElem.getChildNodes();
353         final HashSet<String> foundOperations = new HashSet<>();
354
355         for (int i = 0; i < operationsList.getLength(); i++) {
356             final org.w3c.dom.Node operation = operationsList.item(i);
357             foundOperations.add(operation.getLocalName());
358         }
359
360         for (final RpcDefinition schemaOp : schemaContext.getOperations()) {
361             assertTrue(foundOperations.contains(schemaOp.getQName().getLocalName()));
362         }
363     }
364
365     // /operations/pathToMountPoint/yang-ext:mount
366     @Ignore
367     @Test
368     public void getOperationsBehindMountPointTest() throws Exception {
369         setControllerContext(schemaContextModules);
370
371         mockMountPoint();
372
373         final String uri = "/operations/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
374
375         Response response = target(uri).request("application/yang.api+xml").get();
376         assertEquals(500, response.getStatus());
377
378         final Document responseDoc = response.readEntity(Document.class);
379         validateOperationsResponseXml(responseDoc, schemaContextBehindMountPoint);
380
381         response = target(uri).request("application/yang.api+json").get();
382         assertEquals(200, response.getStatus());
383         final String responseBody = response.readEntity(String.class);
384         assertTrue("Json response for /operations/mount_point rpc-behind-module1 is incorrect",
385             validateOperationsResponseJson(responseBody, "rpc-behind-module1", "module1-behind-mount-point").find());
386         assertTrue("Json response for /operations/mount_point rpc-behind-module2 is incorrect",
387             validateOperationsResponseJson(responseBody, "rpc-behind-module2", "module2-behind-mount-point").find());
388
389     }
390
391     private static Matcher validateOperationsResponseJson(final String searchIn, final String rpcName,
392             final String moduleName) {
393         final StringBuilder regex = new StringBuilder();
394         regex.append(".*\"" + rpcName + "\"");
395         final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
396         return ptrn.matcher(searchIn);
397
398     }
399
400     // /restconf/modules/pathToMountPoint/yang-ext:mount
401     @Test
402     public void getModulesBehindMountPoint() throws Exception {
403         setControllerContext(schemaContextModules);
404
405         mockMountPoint();
406
407         final String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
408
409         Response response = target(uri).request("application/yang.api+json").get();
410         assertEquals(200, response.getStatus());
411         final String responseBody = response.readEntity(String.class);
412
413         assertTrue(
414                 "module1-behind-mount-point in json wasn't found",
415                 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
416                         responseBody).find());
417         assertTrue(
418                 "module2-behind-mount-point in json wasn't found",
419                 prepareJsonRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point",
420                         responseBody).find());
421
422         response = target(uri).request("application/yang.api+xml").get();
423         assertEquals(200, response.getStatus());
424         validateModulesResponseXml(response, schemaContextBehindMountPoint);
425
426     }
427
428     // /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
429     @Test
430     public void getModuleBehindMountPoint() throws Exception {
431         setControllerContext(schemaContextModules);
432
433         mockMountPoint();
434
435         final String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"
436                 + "module1-behind-mount-point/2014-02-03";
437
438         Response response = target(uri).request("application/yang.api+json").get();
439         assertEquals(200, response.getStatus());
440         final String responseBody = response.readEntity(String.class);
441
442         assertTrue(
443                 "module1-behind-mount-point in json wasn't found",
444                 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
445                         responseBody).find());
446         final String[] split = responseBody.split("\"module\"");
447         assertEquals("\"module\" element is returned more then once", 2, split.length);
448
449         response = target(uri).request("application/yang.api+xml").get();
450         assertEquals(200, response.getStatus());
451         final Document responseXml = response.readEntity(Document.class);
452
453         final QName module = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
454
455         assertEquals("module1-behind-mount-point", module.getLocalName());
456         assertEquals("2014-02-03", module.getRevision().get().toString());
457         assertEquals("module:1:behind:mount:point", module.getNamespace().toString());
458     }
459
460     private static void validateModulesResponseXml(final Response response, final SchemaContext schemaContext) {
461         assertEquals(200, response.getStatus());
462         final Document responseBody = response.readEntity(Document.class);
463         final NodeList moduleNodes = responseBody.getDocumentElement().getElementsByTagNameNS(RESTCONF_NS, "module");
464
465         assertTrue(moduleNodes.getLength() > 0);
466
467         final HashSet<QName> foundModules = new HashSet<>();
468
469         for (int i = 0; i < moduleNodes.getLength(); i++) {
470             final org.w3c.dom.Node module = moduleNodes.item(i);
471
472             final QName name = assertedModuleXmlToModuleQName(module);
473             foundModules.add(name);
474         }
475
476         assertAllModules(foundModules,schemaContext);
477     }
478
479     private static void assertAllModules(final Set<QName> foundModules, final SchemaContext schemaContext) {
480         for (final Module module : schemaContext.getModules()) {
481             final QName current = QName.create(module.getQNameModule(), module.getName());
482             assertTrue("Module not found in response.", foundModules.contains(current));
483         }
484
485     }
486
487     private static QName assertedModuleXmlToModuleQName(final org.w3c.dom.Node module) {
488         assertEquals("module", module.getLocalName());
489         assertEquals(RESTCONF_NS, module.getNamespaceURI());
490         String revision = null;
491         String namespace = null;
492         String name = null;
493
494
495         final NodeList childNodes = module.getChildNodes();
496
497         for (int i = 0; i < childNodes.getLength(); i++) {
498             final org.w3c.dom.Node child = childNodes.item(i);
499             assertEquals(RESTCONF_NS, child.getNamespaceURI());
500
501             switch (child.getLocalName()) {
502                 case "name":
503                     assertNull("Name element appeared multiple times", name);
504                     name = child.getTextContent().trim();
505                     break;
506                 case "revision":
507                     assertNull("Revision element appeared multiple times", revision);
508                     revision = child.getTextContent().trim();
509                     break;
510                 case "namespace":
511                     assertNull("Namespace element appeared multiple times", namespace);
512                     namespace = child.getTextContent().trim();
513                     break;
514                 default:
515                     break;
516             }
517         }
518
519         assertNotNull("Revision was not part of xml",revision);
520         assertNotNull("Module namespace was not part of xml",namespace);
521         assertNotNull("Module identiffier was not part of xml",name);
522
523         return QName.create(namespace,revision,name);
524     }
525
526     private static void validateModulesResponseJson(final Response response) {
527         assertEquals(200, response.getStatus());
528         final String responseBody = response.readEntity(String.class);
529
530         assertTrue("Module1 in json wasn't found", prepareJsonRegex("module1", "2014-01-01", "module:1", responseBody)
531                 .find());
532         assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
533                 .find());
534         assertTrue("Module3 in json wasn't found", prepareJsonRegex("module3", "2014-01-03", "module:3", responseBody)
535                 .find());
536     }
537
538     private static Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
539             final String searchIn) {
540         final StringBuilder regex = new StringBuilder();
541         regex.append("^");
542
543         regex.append(".*\\{");
544         regex.append(".*\"name\"");
545         regex.append(".*:");
546         regex.append(".*\"" + module + "\",");
547
548         regex.append(".*\"revision\"");
549         regex.append(".*:");
550         regex.append(".*\"" + revision + "\",");
551
552         regex.append(".*\"namespace\"");
553         regex.append(".*:");
554         regex.append(".*\"" + namespace + "\"");
555
556         regex.append(".*\\}");
557
558         regex.append(".*");
559         regex.append("$");
560         final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
561         return ptrn.matcher(searchIn);
562
563     }
564
565
566     private int get(final String uri, final String mediaType) {
567         return target(uri).request(mediaType).get().getStatus();
568     }
569
570     /**
571      * Container structure.
572      *
573      * <p>
574      * container cont {
575      *   container cont1 {
576      *       leaf lf11 {
577      *           type string;
578      *       }
579      */
580     private static NormalizedNode prepareCnDataForMountPointTest(final boolean wrapToCont) throws Exception {
581         final String testModuleDate = "2014-01-09";
582         final ContainerNode contChild = Builders
583                 .containerBuilder()
584                 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont1", "test:module", testModuleDate))
585                 .withChild(
586                         Builders.leafBuilder()
587                                 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", testModuleDate))
588                                 .withValue("lf11 value").build()).build();
589
590         if (wrapToCont) {
591             return Builders.containerBuilder()
592                     .withNodeIdentifier(TestUtils.getNodeIdentifier("cont", "test:module", testModuleDate))
593                     .withChild(contChild).build();
594         }
595         return contChild;
596
597     }
598
599     private void mockReadOperationalDataMethod() {
600         when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
601     }
602
603     private void mockReadConfigurationDataMethod() {
604         when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class), isNull()))
605                 .thenReturn(answerFromGet);
606     }
607
608     private static NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws Exception {
609         return ImmutableMapEntryNodeBuilder.create()
610                 .withNodeIdentifier(
611                         TestUtils.getNodeIdentifierPredicate("lst1", "test:module", "2014-01-09", "lf11",
612                                 "GigabitEthernet0/0/0/0"))
613                 .withChild(
614                         ImmutableLeafNodeBuilder.create()
615                                 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", "2014-01-09"))
616                                 .withValue("GigabitEthernet0/0/0/0").build()).build();
617
618     }
619
620     /**
621      * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output.
622      */
623     @Test
624     public void getDataWithUriIncludeWhiteCharsParameterTest() throws Exception {
625         getDataWithUriIncludeWhiteCharsParameter("config");
626         getDataWithUriIncludeWhiteCharsParameter("operational");
627     }
628
629     private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws Exception {
630         mockReadConfigurationDataMethod();
631         mockReadOperationalDataMethod();
632         final String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
633         Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
634         final String xmlData = response.readEntity(String.class);
635
636         Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
637         Matcher matcher = pattern.matcher(xmlData);
638         // XML element can't surrounded with white character (e.g ">    " or
639         // "    <")
640         assertFalse(matcher.matches());
641
642         response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
643         final String jsonData = response.readEntity(String.class);
644         pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
645         matcher = pattern.matcher(jsonData);
646         // JSON element can't surrounded with white character (e.g "} ", " {",
647         // "] ", " [", " :" or ": ")
648         assertFalse(matcher.matches());
649     }
650
651     /**
652      * Tests behavior when invalid value of depth URI parameter.
653      */
654     @Test
655     @Ignore
656     public void getDataWithInvalidDepthParameterTest() {
657         setControllerContext(schemaContextModules);
658
659         final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
660         paramMap.putSingle("depth", "1o");
661         final UriInfo mockInfo = mock(UriInfo.class);
662         when(mockInfo.getQueryParameters(false)).thenAnswer(invocation -> paramMap);
663
664         getDataWithInvalidDepthParameterTest(mockInfo);
665
666         paramMap.putSingle("depth", "0");
667         getDataWithInvalidDepthParameterTest(mockInfo);
668
669         paramMap.putSingle("depth", "-1");
670         getDataWithInvalidDepthParameterTest(mockInfo);
671     }
672
673     private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
674         try {
675             final QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
676             final YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
677             final NormalizedNode value =
678                     Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build();
679             when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value);
680             restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
681             fail("Expected RestconfDocumentedException");
682         } catch (final RestconfDocumentedException e) {
683             assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
684                     .getErrorMessage().contains("depth"));
685         }
686     }
687
688     @SuppressWarnings("unused")
689     private void verifyXMLResponse(final Response response, final NodeData nodeData) {
690         final Document doc = response.readEntity(Document.class);
691         assertNotNull("Could not parse XML document", doc);
692
693         verifyContainerElement(doc.getDocumentElement(), nodeData);
694     }
695
696     @SuppressWarnings("unchecked")
697     private void verifyContainerElement(final Element element, final NodeData nodeData) {
698
699         assertEquals("Element local name", nodeData.key, element.getLocalName());
700
701         final NodeList childNodes = element.getChildNodes();
702         if (nodeData.data == null) { // empty container
703             assertTrue(
704                     "Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
705             return;
706         }
707
708         final Map<String, NodeData> expChildMap = new HashMap<>();
709         for (final NodeData expChild : (List<NodeData>) nodeData.data) {
710             expChildMap.put(expChild.key.toString(), expChild);
711         }
712
713         for (int i = 0; i < childNodes.getLength(); i++) {
714             final org.w3c.dom.Node actualChild = childNodes.item(i);
715             if (!(actualChild instanceof Element)) {
716                 continue;
717             }
718
719             final Element actualElement = (Element) actualChild;
720             final NodeData expChild = expChildMap.remove(actualElement.getLocalName());
721             assertNotNull(
722                     "Unexpected child element for parent \"" + element.getLocalName() + "\": "
723                             + actualElement.getLocalName(), expChild);
724
725             if (expChild.data == null || expChild.data instanceof List) {
726                 verifyContainerElement(actualElement, expChild);
727             } else {
728                 assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data,
729                         actualElement.getTextContent());
730             }
731         }
732
733         if (!expChildMap.isEmpty()) {
734             fail("Missing elements for parent \"" + element.getLocalName() + "\": " + expChildMap.keySet());
735         }
736     }
737
738     private void mockMountPoint() {
739         when(mountInstance.getService(DOMSchemaService.class))
740             .thenReturn(Optional.of(FixedDOMSchemaService.of(schemaContextBehindMountPoint)));
741     }
742 }