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