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