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