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