Merge "Cleanup: Remove passing around of DataPersistenceProvider"
[controller.git] / opendaylight / md-sal / sal-rest-connector / 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.Matchers.any;
17 import static org.mockito.Matchers.eq;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.when;
20
21 import com.google.common.base.Optional;
22 import com.google.common.collect.Maps;
23 import java.io.FileNotFoundException;
24 import java.io.UnsupportedEncodingException;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.Date;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Set;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37 import javax.ws.rs.core.Application;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.MultivaluedHashMap;
40 import javax.ws.rs.core.MultivaluedMap;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.UriInfo;
43 import org.glassfish.jersey.server.ResourceConfig;
44 import org.glassfish.jersey.test.JerseyTest;
45 import org.junit.BeforeClass;
46 import org.junit.Ignore;
47 import org.junit.Test;
48 import org.mockito.invocation.InvocationOnMock;
49 import org.mockito.stubbing.Answer;
50 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
51 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
52 import org.opendaylight.controller.sal.rest.impl.JsonNormalizedNodeBodyReader;
53 import org.opendaylight.controller.sal.rest.impl.NormalizedNodeJsonBodyWriter;
54 import org.opendaylight.controller.sal.rest.impl.NormalizedNodeXmlBodyWriter;
55 import org.opendaylight.controller.sal.rest.impl.RestconfApplication;
56 import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper;
57 import org.opendaylight.controller.sal.rest.impl.XmlNormalizedNodeBodyReader;
58 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
59 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
60 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
61 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
66 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
68 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
69 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
70 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
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 BrokerFacade brokerFacade;
91     private static RestconfImpl restconfImpl;
92     private static SchemaContext schemaContextYangsIetf;
93     private static SchemaContext schemaContextTestModule;
94     @SuppressWarnings("rawtypes")
95     private static NormalizedNode answerFromGet;
96
97     private static SchemaContext schemaContextModules;
98     private static SchemaContext schemaContextBehindMountPoint;
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 FileNotFoundException, ParseException {
104         schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
105         schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
106         brokerFacade = mock(BrokerFacade.class);
107         restconfImpl = RestconfImpl.getInstance();
108         restconfImpl.setBroker(brokerFacade);
109         answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
110
111         schemaContextModules = TestUtils.loadSchemaContext("/modules");
112         schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
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         ResourceConfig resourceConfig = new ResourceConfig();
123         resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
124                 new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
125         resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
126         resourceConfig.registerClasses(new RestconfApplication().getClasses());
127         return resourceConfig;
128     }
129
130     private void setControllerContext(final SchemaContext schemaContext) {
131         final ControllerContext controllerContext = ControllerContext.getInstance();
132         controllerContext.setSchemas(schemaContext);
133         restconfImpl.setControllerContext(controllerContext);
134     }
135
136     /**
137      * Tests of status codes for "/operational/{identifier}".
138      */
139     @Test
140     public void getOperationalStatusCodes() throws UnsupportedEncodingException {
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 UnsupportedEncodingException {
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 UnsupportedEncodingException, URISyntaxException, ParseException {
170         when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
171                 prepareCnDataForMountPointTest(false));
172         final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
173         when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
174         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
175         when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
176
177         ControllerContext.getInstance().setMountService(mockMountService);
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      *
189      * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
190      * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
191      * InstanceIdentifier parameter in method
192      * {@link BrokerFacade#readConfigurationData(DOMMountPoint, YangInstanceIdentifier)} which is called in
193      * method {@link RestconfImpl#readConfigurationData}
194      *
195      * @throws ParseException
196      */
197     @Test
198     public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException,
199             ParseException {
200         final YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
201         when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier))).thenReturn(
202                 prepareCnDataForSlashesBehindMountPointTest());
203         final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
204         when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
205         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
206         when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
207
208         ControllerContext.getInstance().setMountService(mockMountService);
209
210         final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
211         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
212     }
213
214     private YangInstanceIdentifier prepareInstanceIdentifierForList() throws URISyntaxException, ParseException {
215         final List<PathArgument> parameters = new ArrayList<>();
216
217         final Date revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-01-09");
218         final URI uri = new URI("test:module");
219         final QName qNameCont = QName.create(uri, revision, "cont");
220         final QName qNameList = QName.create(uri, revision, "lst1");
221         final QName qNameKeyList = QName.create(uri, revision, "lf11");
222
223         parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameCont));
224         parameters.add(new YangInstanceIdentifier.NodeIdentifier(qNameList));
225         parameters.add(new YangInstanceIdentifier.NodeIdentifierWithPredicates(qNameList, qNameKeyList,
226                 "GigabitEthernet0/0/0/0"));
227         return YangInstanceIdentifier.create(parameters);
228     }
229
230     @Test
231     public void getDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException,
232             ParseException {
233         when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
234                 prepareCnDataForMountPointTest(true));
235         final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
236         when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
237         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
238         when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
239
240         ControllerContext.getInstance().setMountService(mockMountService);
241
242         final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
243         assertEquals(200, get(uri, MediaType.APPLICATION_XML));
244     }
245
246     // /modules
247     @Test
248     public void getModulesTest() throws UnsupportedEncodingException, FileNotFoundException {
249         final ControllerContext controllerContext = ControllerContext.getInstance();
250         controllerContext.setGlobalSchema(schemaContextModules);
251         restconfImpl.setControllerContext(controllerContext);
252
253         final String uri = "/modules";
254
255         Response response = target(uri).request("application/yang.api+json").get();
256         validateModulesResponseJson(response);
257
258         response = target(uri).request("application/yang.api+xml").get();
259         validateModulesResponseXml(response,schemaContextModules);
260     }
261
262     // /streams/
263     @Test
264     @Ignore // FIXME : find why it is fail by in gerrit build
265     public void getStreamsTest() throws UnsupportedEncodingException, FileNotFoundException {
266         setControllerContext(schemaContextModules);
267
268         final String uri = "/streams";
269
270         Response response = target(uri).request("application/yang.api+json").get();
271         final String responseBody = response.readEntity(String.class);
272         assertEquals(200, response.getStatus());
273         assertNotNull(responseBody);
274         assertTrue(responseBody.contains("streams"));
275
276         response = target(uri).request("application/yang.api+xml").get();
277         assertEquals(200, response.getStatus());
278         final Document responseXmlBody = response.readEntity(Document.class);
279         assertNotNull(responseXmlBody);
280         final Element rootNode = responseXmlBody.getDocumentElement();
281
282         assertEquals("streams", rootNode.getLocalName());
283         assertEquals(RESTCONF_NS, rootNode.getNamespaceURI());
284     }
285
286     // /modules/module
287     @Test
288     public void getModuleTest() throws FileNotFoundException, UnsupportedEncodingException {
289         setControllerContext(schemaContextModules);
290
291         final String uri = "/modules/module/module2/2014-01-02";
292
293         Response response = target(uri).request("application/yang.api+xml").get();
294         assertEquals(200, response.getStatus());
295         final Document responseXml = response.readEntity(Document.class);
296
297         final QName qname = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
298         assertNotNull(qname);
299
300         assertEquals("module2", qname.getLocalName());
301         assertEquals("module:2", qname.getNamespace().toString());
302         assertEquals("2014-01-02", qname.getFormattedRevision());
303
304         response = target(uri).request("application/yang.api+json").get();
305         assertEquals(200, response.getStatus());
306         final String responseBody = response.readEntity(String.class);
307         assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
308                 .find());
309         final String[] split = responseBody.split("\"module\"");
310         assertEquals("\"module\" element is returned more then once", 2, split.length);
311
312     }
313
314     // /operations
315     @Test
316     @Ignore // FIXME restconf-netconf yang schema has to be updated for operations container
317     public void getOperationsTest() throws FileNotFoundException, UnsupportedEncodingException {
318         setControllerContext(schemaContextModules);
319
320         final String uri = "/operations";
321
322         Response response = target(uri).request("application/yang.api+xml").get();
323         assertEquals(200, response.getStatus());
324         final Document responseDoc = response.readEntity(Document.class);
325         validateOperationsResponseXml(responseDoc, schemaContextModules);
326
327         response = target(uri).request("application/yang.api+json").get();
328         assertEquals(200, response.getStatus());
329         final String responseBody = response.readEntity(String.class);
330         assertTrue("Json response for /operations dummy-rpc1-module1 is incorrect",
331                 validateOperationsResponseJson(responseBody, "dummy-rpc1-module1", "module1").find());
332         assertTrue("Json response for /operations dummy-rpc2-module1 is incorrect",
333                 validateOperationsResponseJson(responseBody, "dummy-rpc2-module1", "module1").find());
334         assertTrue("Json response for /operations dummy-rpc1-module2 is incorrect",
335                 validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
336         assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
337                 validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
338
339     }
340
341     private void validateOperationsResponseXml(final Document responseDoc, final SchemaContext schemaContext) {
342         final Element operationsElem = responseDoc.getDocumentElement();
343         assertEquals(RESTCONF_NS, operationsElem.getNamespaceURI());
344         assertEquals("operations", operationsElem.getLocalName());
345
346
347         final HashSet<QName> foundOperations = new HashSet<>();
348
349         final NodeList operationsList = operationsElem.getChildNodes();
350         for(int i = 0;i < operationsList.getLength();i++) {
351             final org.w3c.dom.Node operation = operationsList.item(i);
352
353             final String namespace = operation.getNamespaceURI();
354             final String name = operation.getLocalName();
355             final QName opQName = QName.create(URI.create(namespace), null, name);
356             foundOperations.add(opQName);
357         }
358
359         for(final RpcDefinition schemaOp : schemaContext.getOperations()) {
360             assertTrue(foundOperations.contains(schemaOp.getQName().withoutRevision()));
361         }
362
363     }
364
365     // /operations/pathToMountPoint/yang-ext:mount
366     @Test
367     @Ignore // FIXME fix the way to provide operations overview functionality asap
368     public void getOperationsBehindMountPointTest() throws FileNotFoundException, UnsupportedEncodingException {
369         setControllerContext(schemaContextModules);
370
371         final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
372         when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
373         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
374         when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
375
376         ControllerContext.getInstance().setMountService(mockMountService);
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(200, 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 Matcher validateOperationsResponseJson(final String searchIn, final String rpcName, final String moduleName) {
397         final StringBuilder regex = new StringBuilder();
398         regex.append("^");
399
400         regex.append(".*\\{");
401         regex.append(".*\"");
402
403         // operations prefix optional
404         regex.append("(");
405         regex.append("ietf-restconf:");
406         regex.append("|)");
407         // :operations prefix optional
408
409         regex.append("operations\"");
410         regex.append(".*:");
411         regex.append(".*\\{");
412
413         regex.append(".*\"" + moduleName);
414         regex.append(":");
415         regex.append(rpcName + "\"");
416         regex.append(".*\\[");
417         regex.append(".*null");
418         regex.append(".*\\]");
419
420         regex.append(".*\\}");
421         regex.append(".*\\}");
422
423         regex.append(".*");
424         regex.append("$");
425         final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
426         return ptrn.matcher(searchIn);
427
428     }
429
430     private Matcher validateOperationsResponseXml(final String searchIn, final String rpcName, final String namespace) {
431         final StringBuilder regex = new StringBuilder();
432
433         regex.append("^");
434
435         regex.append(".*<operations");
436         regex.append(".*xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"");
437         regex.append(".*>");
438
439         regex.append(".*<");
440         regex.append(".*" + rpcName);
441         regex.append(".*" + namespace);
442         regex.append(".*/");
443         regex.append(".*>");
444
445         regex.append(".*</operations.*");
446         regex.append(".*>");
447
448         regex.append(".*");
449         regex.append("$");
450         final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
451         return ptrn.matcher(searchIn);
452     }
453
454     // /restconf/modules/pathToMountPoint/yang-ext:mount
455     @Test
456     public void getModulesBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
457         setControllerContext(schemaContextModules);
458
459         final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
460         when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
461         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
462         when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
463
464         ControllerContext.getInstance().setMountService(mockMountService);
465
466         final String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
467
468         Response response = target(uri).request("application/yang.api+json").get();
469         assertEquals(200, response.getStatus());
470         final String responseBody = response.readEntity(String.class);
471
472         assertTrue(
473                 "module1-behind-mount-point in json wasn't found",
474                 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
475                         responseBody).find());
476         assertTrue(
477                 "module2-behind-mount-point in json wasn't found",
478                 prepareJsonRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point",
479                         responseBody).find());
480
481         response = target(uri).request("application/yang.api+xml").get();
482         assertEquals(200, response.getStatus());
483         validateModulesResponseXml(response, schemaContextBehindMountPoint);
484
485     }
486
487     // /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
488     @Test
489     public void getModuleBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
490         setControllerContext(schemaContextModules);
491
492         final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
493         when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
494         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
495         when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
496
497         ControllerContext.getInstance().setMountService(mockMountService);
498
499         final String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/module1-behind-mount-point/2014-02-03";
500
501         Response response = target(uri).request("application/yang.api+json").get();
502         assertEquals(200, response.getStatus());
503         final String responseBody = response.readEntity(String.class);
504
505         assertTrue(
506                 "module1-behind-mount-point in json wasn't found",
507                 prepareJsonRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point",
508                         responseBody).find());
509         final String[] split = responseBody.split("\"module\"");
510         assertEquals("\"module\" element is returned more then once", 2, split.length);
511
512         response = target(uri).request("application/yang.api+xml").get();
513         assertEquals(200, response.getStatus());
514         final Document responseXml = response.readEntity(Document.class);
515
516         final QName module = assertedModuleXmlToModuleQName(responseXml.getDocumentElement());
517
518         assertEquals("module1-behind-mount-point", module.getLocalName());
519         assertEquals("2014-02-03", module.getFormattedRevision());
520         assertEquals("module:1:behind:mount:point", module.getNamespace().toString());
521
522
523     }
524
525     private void validateModulesResponseXml(final Response response, final SchemaContext schemaContext) {
526         assertEquals(200, response.getStatus());
527         final Document responseBody = response.readEntity(Document.class);
528         final NodeList moduleNodes = responseBody.getDocumentElement().getElementsByTagNameNS(RESTCONF_NS, "module");
529
530         assertTrue(moduleNodes.getLength() > 0);
531
532         final HashSet<QName> foundModules = new HashSet<>();
533
534         for(int i=0;i < moduleNodes.getLength();i++) {
535             final org.w3c.dom.Node module = moduleNodes.item(i);
536
537             final QName name = assertedModuleXmlToModuleQName(module);
538             foundModules.add(name);
539         }
540
541         assertAllModules(foundModules,schemaContext);
542     }
543
544     private void assertAllModules(final Set<QName> foundModules, final SchemaContext schemaContext) {
545         for(final Module module : schemaContext.getModules()) {
546             final QName current = QName.create(module.getQNameModule(),module.getName());
547             assertTrue("Module not found in response.",foundModules.contains(current));
548         }
549
550     }
551
552     private QName assertedModuleXmlToModuleQName(final org.w3c.dom.Node module) {
553         assertEquals("module", module.getLocalName());
554         assertEquals(RESTCONF_NS, module.getNamespaceURI());
555         String revision = null;
556         String namespace = null;
557         String name = null;
558
559
560         final NodeList childNodes = module.getChildNodes();
561
562         for(int i =0;i < childNodes.getLength(); i++) {
563             final org.w3c.dom.Node child = childNodes.item(i);
564             assertEquals(RESTCONF_NS, child.getNamespaceURI());
565
566             switch(child.getLocalName()) {
567                 case "name":
568                     assertNull("Name element appeared multiple times",name);
569                     name = child.getTextContent().trim();
570                     break;
571                 case "revision":
572                     assertNull("Revision element appeared multiple times",revision);
573                     revision = child.getTextContent().trim();
574                     break;
575
576                 case "namespace":
577                     assertNull("Namespace element appeared multiple times",namespace);
578                     namespace = child.getTextContent().trim();
579                     break;
580             }
581         }
582
583         assertNotNull("Revision was not part of xml",revision);
584         assertNotNull("Module namespace was not part of xml",namespace);
585         assertNotNull("Module identiffier was not part of xml",name);
586
587
588         // TODO Auto-generated method stub
589
590         return QName.create(namespace,revision,name);
591     }
592
593     private void validateModulesResponseJson(final Response response) {
594         assertEquals(200, response.getStatus());
595         final String responseBody = response.readEntity(String.class);
596
597         assertTrue("Module1 in json wasn't found", prepareJsonRegex("module1", "2014-01-01", "module:1", responseBody)
598                 .find());
599         assertTrue("Module2 in json wasn't found", prepareJsonRegex("module2", "2014-01-02", "module:2", responseBody)
600                 .find());
601         assertTrue("Module3 in json wasn't found", prepareJsonRegex("module3", "2014-01-03", "module:3", responseBody)
602                 .find());
603     }
604
605     private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
606             final String searchIn) {
607         final StringBuilder regex = new StringBuilder();
608         regex.append("^");
609
610         regex.append(".*\\{");
611         regex.append(".*\"name\"");
612         regex.append(".*:");
613         regex.append(".*\"" + module + "\",");
614
615         regex.append(".*\"revision\"");
616         regex.append(".*:");
617         regex.append(".*\"" + revision + "\",");
618
619         regex.append(".*\"namespace\"");
620         regex.append(".*:");
621         regex.append(".*\"" + namespace + "\"");
622
623         regex.append(".*\\}");
624
625         regex.append(".*");
626         regex.append("$");
627         final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
628         return ptrn.matcher(searchIn);
629
630     }
631
632
633     private int get(final String uri, final String mediaType) {
634         return target(uri).request(mediaType).get().getStatus();
635     }
636
637     /**
638     container cont {
639         container cont1 {
640             leaf lf11 {
641                 type string;
642             }
643     */
644     @SuppressWarnings("rawtypes")
645     private NormalizedNode prepareCnDataForMountPointTest(final boolean wrapToCont) throws URISyntaxException, ParseException {
646         final String testModuleDate = "2014-01-09";
647         final ContainerNode contChild = Builders
648                 .containerBuilder()
649                 .withNodeIdentifier(TestUtils.getNodeIdentifier("cont1", "test:module", testModuleDate))
650                 .withChild(
651                         Builders.leafBuilder()
652                                 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", testModuleDate))
653                                 .withValue("lf11 value").build()).build();
654
655         if (wrapToCont) {
656             return Builders.containerBuilder()
657                     .withNodeIdentifier(TestUtils.getNodeIdentifier("cont", "test:module", testModuleDate))
658                     .withChild(contChild).build();
659         }
660         return contChild;
661
662     }
663
664     @SuppressWarnings("unchecked")
665     private void mockReadOperationalDataMethod() {
666         when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
667     }
668
669     @SuppressWarnings("unchecked")
670     private void mockReadConfigurationDataMethod() {
671         when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
672     }
673
674     @SuppressWarnings("rawtypes")
675     private NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws ParseException {
676         return ImmutableMapEntryNodeBuilder
677                 .create()
678                 .withNodeIdentifier(
679                         TestUtils.getNodeIdentifierPredicate("lst1", "test:module", "2014-01-09", "lf11",
680                                 "GigabitEthernet0/0/0/0"))
681                 .withChild(
682                         ImmutableLeafNodeBuilder.create()
683                                 .withNodeIdentifier(TestUtils.getNodeIdentifier("lf11", "test:module", "2014-01-09"))
684                                 .withValue("GigabitEthernet0/0/0/0").build()).build();
685
686     }
687
688     /**
689      * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
690      *
691      * @throws UnsupportedEncodingException
692      */
693     @Test
694     public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
695         getDataWithUriIncludeWhiteCharsParameter("config");
696         getDataWithUriIncludeWhiteCharsParameter("operational");
697     }
698
699     private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws UnsupportedEncodingException {
700         mockReadConfigurationDataMethod();
701         mockReadOperationalDataMethod();
702         final String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
703         Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
704         final String xmlData = response.readEntity(String.class);
705
706         Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
707         Matcher matcher = pattern.matcher(xmlData);
708         // XML element can't surrounded with white character (e.g ">    " or
709         // "    <")
710         assertFalse(matcher.matches());
711
712         response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
713         final String jsonData = response.readEntity(String.class);
714         pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
715         matcher = pattern.matcher(jsonData);
716         // JSON element can't surrounded with white character (e.g "} ", " {",
717         // "] ", " [", " :" or ": ")
718         assertFalse(matcher.matches());
719     }
720
721     /**
722      * Tests behavior when invalid value of depth URI parameter
723      */
724     @Test
725     @Ignore
726     public void getDataWithInvalidDepthParameterTest() {
727         setControllerContext(schemaContextModules);
728
729         final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
730         paramMap.putSingle("depth", "1o");
731         final UriInfo mockInfo = mock(UriInfo.class);
732         when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
733             @Override
734             public MultivaluedMap<String, String> answer(final InvocationOnMock invocation) {
735                 return paramMap;
736             }
737         });
738
739         getDataWithInvalidDepthParameterTest(mockInfo);
740
741         paramMap.putSingle("depth", "0");
742         getDataWithInvalidDepthParameterTest(mockInfo);
743
744         paramMap.putSingle("depth", "-1");
745         getDataWithInvalidDepthParameterTest(mockInfo);
746     }
747
748     @SuppressWarnings({"rawtypes", "unchecked"})
749     private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
750         try {
751             final QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
752             final YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
753             final NormalizedNode value = (Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build());
754             when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value);
755             restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
756             fail("Expected RestconfDocumentedException");
757         } catch (final RestconfDocumentedException e) {
758             assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
759                     .getErrorMessage().contains("depth"));
760         }
761     }
762
763     @SuppressWarnings("unused")
764     private void verifyXMLResponse(final Response response, final NodeData nodeData) {
765         final Document doc = response.readEntity(Document.class);
766 //        Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
767 //        System.out.println();
768         assertNotNull("Could not parse XML document", doc);
769
770         // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
771
772         verifyContainerElement(doc.getDocumentElement(), nodeData);
773     }
774
775     @SuppressWarnings("unchecked")
776     private void verifyContainerElement(final Element element, final NodeData nodeData) {
777
778         assertEquals("Element local name", nodeData.key, element.getLocalName());
779
780         final NodeList childNodes = element.getChildNodes();
781         if (nodeData.data == null) { // empty container
782             assertTrue("Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
783             return;
784         }
785
786         final Map<String, NodeData> expChildMap = Maps.newHashMap();
787         for (final NodeData expChild : (List<NodeData>) nodeData.data) {
788             expChildMap.put(expChild.key.toString(), expChild);
789         }
790
791         for (int i = 0; i < childNodes.getLength(); i++) {
792             final org.w3c.dom.Node actualChild = childNodes.item(i);
793             if (!(actualChild instanceof Element)) {
794                 continue;
795             }
796
797             final Element actualElement = (Element) actualChild;
798             final NodeData expChild = expChildMap.remove(actualElement.getLocalName());
799             assertNotNull(
800                     "Unexpected child element for parent \"" + element.getLocalName() + "\": "
801                             + actualElement.getLocalName(), expChild);
802
803             if (expChild.data == null || expChild.data instanceof List) {
804                 verifyContainerElement(actualElement, expChild);
805             } else {
806                 assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data,
807                         actualElement.getTextContent());
808             }
809         }
810
811         if (!expChildMap.isEmpty()) {
812             fail("Missing elements for parent \"" + element.getLocalName() + "\": " + expChildMap.keySet());
813         }
814     }
815
816 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.