Merge "Add missing flush() on buffered writer."
[netconf.git] / restconf / restconf-nb-bierman02 / src / test / java / org / opendaylight / controller / sal / rest / impl / test / providers / TestXmlBodyReaderMountPoint.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.sal.rest.impl.test.providers;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Mockito.mock;
16 import static org.mockito.Mockito.when;
17
18 import com.google.common.base.Optional;
19 import java.io.File;
20 import java.io.InputStream;
21 import java.net.URI;
22 import java.text.ParseException;
23 import java.util.Collection;
24 import javax.ws.rs.core.MediaType;
25 import org.junit.Assert;
26 import org.junit.BeforeClass;
27 import org.junit.Test;
28 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
29 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
30 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
31 import org.opendaylight.netconf.sal.rest.impl.XmlNormalizedNodeBodyReader;
32 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
33 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
34 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
35 import org.opendaylight.restconf.common.errors.RestconfError;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
41 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
48
49 public class TestXmlBodyReaderMountPoint extends AbstractBodyReaderTest {
50     private final XmlNormalizedNodeBodyReader xmlBodyReader;
51     private static SchemaContext schemaContext;
52
53     private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule();
54
55     private static QNameModule initializeInstanceIdentifierModule() {
56         try {
57             return QNameModule.create(URI.create("instance:identifier:module"),
58                 SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17"));
59         } catch (final ParseException e) {
60             throw new Error(e);
61         }
62     }
63
64     public TestXmlBodyReaderMountPoint() throws Exception {
65         this.xmlBodyReader = new XmlNormalizedNodeBodyReader();
66     }
67
68     @Override
69     protected MediaType getMediaType() {
70         return new MediaType(MediaType.APPLICATION_XML, null);
71     }
72
73     @BeforeClass
74     public static void initialization() throws Exception {
75         final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
76         testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
77         schemaContext = YangParserTestUtils.parseYangSources(testFiles);
78
79         final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
80         when(mountInstance.getSchemaContext()).thenReturn(schemaContext);
81         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
82         when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class)))
83                 .thenReturn(Optional.of(mountInstance));
84
85         ControllerContext.getInstance().setMountService(mockMountService);
86         CONTROLLER_CONTEXT.setSchemas(schemaContext);
87     }
88
89     @Test
90     public void moduleDataTest() throws Exception {
91         final DataSchemaNode dataSchemaNode = schemaContext
92                 .getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
93         final String uri = "instance-identifier-module:cont/yang-ext:mount/instance-identifier-module:cont";
94         mockBodyReader(uri, this.xmlBodyReader, false);
95         final InputStream inputStream = TestXmlBodyReaderMountPoint.class
96                 .getResourceAsStream("/instanceidentifier/xml/xmldata.xml");
97         final NormalizedNodeContext returnValue = this.xmlBodyReader.readFrom(null,
98                 null, null, this.mediaType, null, inputStream);
99         checkMountPointNormalizedNodeContext(returnValue);
100         checkExpectValueNormalizeNodeContext(dataSchemaNode, returnValue);
101     }
102
103     @Test
104     public void moduleSubContainerDataPutTest() throws Exception {
105         final DataSchemaNode dataSchemaNode = schemaContext
106                 .getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
107         final String uri = "instance-identifier-module:cont/yang-ext:mount/instance-identifier-module:cont/cont1";
108         mockBodyReader(uri, this.xmlBodyReader, false);
109         final InputStream inputStream = TestXmlBodyReaderMountPoint.class
110                 .getResourceAsStream("/instanceidentifier/xml/xml_sub_container.xml");
111         final NormalizedNodeContext returnValue = this.xmlBodyReader.readFrom(null,
112                 null, null, this.mediaType, null, inputStream);
113         checkMountPointNormalizedNodeContext(returnValue);
114         checkExpectValueNormalizeNodeContext(dataSchemaNode, returnValue,
115                 QName.create(dataSchemaNode.getQName(), "cont1"));
116     }
117
118     @Test
119     public void moduleSubContainerDataPostTest() throws Exception {
120         final DataSchemaNode dataSchemaNode = schemaContext
121                 .getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont"));
122         final String uri = "instance-identifier-module:cont/yang-ext:mount/instance-identifier-module:cont";
123         mockBodyReader(uri, this.xmlBodyReader, true);
124         final InputStream inputStream = TestXmlBodyReaderMountPoint.class
125                 .getResourceAsStream("/instanceidentifier/xml/xml_sub_container.xml");
126         final NormalizedNodeContext returnValue = this.xmlBodyReader.readFrom(null,
127                 null, null, this.mediaType, null, inputStream);
128         checkMountPointNormalizedNodeContext(returnValue);
129         checkExpectValueNormalizeNodeContext(dataSchemaNode, returnValue);
130     }
131
132     @Test
133     public void rpcModuleInputTest() throws Exception {
134         final String uri = "instance-identifier-module:cont/yang-ext:mount/invoke-rpc-module:rpc-test";
135         mockBodyReader(uri, this.xmlBodyReader, true);
136         final InputStream inputStream = TestXmlBodyReaderMountPoint.class
137                 .getResourceAsStream("/invoke-rpc/xml/rpc-input.xml");
138         final NormalizedNodeContext returnValue = this.xmlBodyReader.readFrom(null,
139                 null, null, this.mediaType, null, inputStream);
140         checkNormalizedNodeContext(returnValue);
141         final ContainerNode contNode = (ContainerNode) returnValue.getData();
142         final YangInstanceIdentifier yangCont = YangInstanceIdentifier.of(QName.create(contNode.getNodeType(), "cont"));
143         final Optional<DataContainerChild<? extends PathArgument, ?>> contDataNodePotential = contNode.getChild(yangCont
144                 .getLastPathArgument());
145         assertTrue(contDataNodePotential.isPresent());
146         final ContainerNode contDataNode = (ContainerNode) contDataNodePotential.get();
147         final YangInstanceIdentifier yangLeaf =
148                 YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf"));
149         final Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode = contDataNode.getChild(yangLeaf
150                 .getLastPathArgument());
151         assertTrue(leafDataNode.isPresent());
152         assertTrue("lf-test".equalsIgnoreCase(leafDataNode.get().getValue().toString()));
153     }
154
155     private void checkExpectValueNormalizeNodeContext(
156             final DataSchemaNode dataSchemaNode,
157             final NormalizedNodeContext nnContext) {
158         checkExpectValueNormalizeNodeContext(dataSchemaNode, nnContext, null);
159     }
160
161     protected void checkExpectValueNormalizeNodeContext(
162             final DataSchemaNode dataSchemaNode,
163             final NormalizedNodeContext nnContext, final QName qualifiedName) {
164         YangInstanceIdentifier dataNodeIdent = YangInstanceIdentifier
165                 .of(dataSchemaNode.getQName());
166         final DOMMountPoint mountPoint = nnContext
167                 .getInstanceIdentifierContext().getMountPoint();
168         final DataSchemaNode mountDataSchemaNode = mountPoint
169                 .getSchemaContext().getDataChildByName(
170                         dataSchemaNode.getQName());
171         assertNotNull(mountDataSchemaNode);
172         if ((qualifiedName != null) && (dataSchemaNode instanceof DataNodeContainer)) {
173             final DataSchemaNode child = ((DataNodeContainer) dataSchemaNode)
174                     .getDataChildByName(qualifiedName);
175             dataNodeIdent = YangInstanceIdentifier.builder(dataNodeIdent)
176                     .node(child.getQName()).build();
177             assertTrue(nnContext.getInstanceIdentifierContext().getSchemaNode()
178                     .equals(child));
179         } else {
180             assertTrue(mountDataSchemaNode.equals(dataSchemaNode));
181         }
182         assertNotNull(NormalizedNodes.findNode(nnContext.getData(),
183                 dataNodeIdent));
184     }
185
186     /**
187      * Test when container with the same name is placed in two modules (foo-module and bar-module). Namespace must be
188      * used to distinguish between them to find correct one. Check if container was found not only according to its name
189      * but also by correct namespace used in payload.
190      */
191     @Test
192     public void findFooContainerUsingNamespaceTest() throws Exception {
193         mockBodyReader("instance-identifier-module:cont/yang-ext:mount", this.xmlBodyReader, true);
194         final InputStream inputStream = TestXmlBodyReader.class
195                 .getResourceAsStream("/instanceidentifier/xml/xmlDataFindFooContainer.xml");
196         final NormalizedNodeContext returnValue = this.xmlBodyReader
197                 .readFrom(null, null, null, this.mediaType, null, inputStream);
198
199         // check return value
200         checkMountPointNormalizedNodeContext(returnValue);
201         // check if container was found both according to its name and namespace
202         assertEquals("Not correct container found, name was ignored",
203                 "foo-bar-container", returnValue.getData().getNodeType().getLocalName());
204         assertEquals("Not correct container found, namespace was ignored",
205                 "foo:module", returnValue.getData().getNodeType().getNamespace().toString());
206     }
207
208     /**
209      * Test when container with the same name is placed in two modules (foo-module and bar-module). Namespace must be
210      * used to distinguish between them to find correct one. Check if container was found not only according to its name
211      * but also by correct namespace used in payload.
212      */
213     @Test
214     public void findBarContainerUsingNamespaceTest() throws Exception {
215         mockBodyReader("instance-identifier-module:cont/yang-ext:mount", this.xmlBodyReader, true);
216         final InputStream inputStream = TestXmlBodyReader.class
217                 .getResourceAsStream("/instanceidentifier/xml/xmlDataFindBarContainer.xml");
218         final NormalizedNodeContext returnValue = this.xmlBodyReader
219                 .readFrom(null, null, null, this.mediaType, null, inputStream);
220
221         // check return value
222         checkMountPointNormalizedNodeContext(returnValue);
223         // check if container was found both according to its name and namespace
224         assertEquals("Not correct container found, name was ignored",
225                 "foo-bar-container", returnValue.getData().getNodeType().getLocalName());
226         assertEquals("Not correct container found, namespace was ignored",
227                 "bar:module", returnValue.getData().getNodeType().getNamespace().toString());
228     }
229
230     /**
231      * Test PUT operation when message root element is not the same as the last element in request URI.
232      * PUT operation message should always start with schema node from URI otherwise exception should be
233      * thrown.
234      */
235     @Test
236     public void wrongRootElementTest() throws Exception {
237         mockBodyReader("instance-identifier-module:cont/yang-ext:mount", this.xmlBodyReader, false);
238         final InputStream inputStream = TestXmlBodyReader.class.getResourceAsStream(
239                 "/instanceidentifier/xml/bug7933.xml");
240         try {
241             this.xmlBodyReader.readFrom(null, null, null, this.mediaType, null, inputStream);
242             Assert.fail("Test should fail due to malformed PUT operation message");
243         } catch (final RestconfDocumentedException exception) {
244             final RestconfError restconfError = exception.getErrors().get(0);
245             Assert.assertEquals(RestconfError.ErrorType.PROTOCOL, restconfError.getErrorType());
246             Assert.assertEquals(RestconfError.ErrorTag.MALFORMED_MESSAGE, restconfError.getErrorTag());
247         }
248     }
249 }