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