Migrate users of AnyXml node to DOMSource
[controller.git] / opendaylight / netconf / mdsal-netconf-connector / src / test / java / org / opendaylight / controller / netconf / mdsal / connector / ops / NetconfMDSalMappingTest.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.netconf.mdsal.connector.ops;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15
16 import com.google.common.base.Preconditions;
17 import com.google.common.io.ByteSource;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Collection;
23 import java.util.EnumMap;
24 import java.util.List;
25 import java.util.concurrent.ExecutorService;
26 import javax.xml.parsers.ParserConfigurationException;
27 import org.custommonkey.xmlunit.DetailedDiff;
28 import org.custommonkey.xmlunit.Diff;
29 import org.custommonkey.xmlunit.XMLUnit;
30 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
31 import org.junit.Before;
32 import org.junit.Ignore;
33 import org.junit.Test;
34 import org.opendaylight.controller.cluster.datastore.ConcurrentDOMDataBroker;
35 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
36 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
37 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
38 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
39 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
40 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
41 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
42 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
43 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
44 import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
45 import org.opendaylight.controller.netconf.mdsal.connector.TransactionProvider;
46 import org.opendaylight.controller.netconf.mdsal.connector.ops.get.Get;
47 import org.opendaylight.controller.netconf.mdsal.connector.ops.get.GetConfig;
48 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
49 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
50 import org.opendaylight.controller.sal.core.api.model.SchemaService;
51 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
52 import org.opendaylight.yangtools.concepts.ListenerRegistration;
53 import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
54 import org.opendaylight.yangtools.yang.model.api.Module;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
57 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
58 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
59 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.w3c.dom.Document;
63 import org.w3c.dom.Node;
64 import org.w3c.dom.NodeList;
65 import org.xml.sax.SAXException;
66
67 public class NetconfMDSalMappingTest {
68
69     private static final Logger LOG = LoggerFactory.getLogger(NetconfMDSalMappingTest.class);
70
71     private static final String RPC_REPLY_ELEMENT = "rpc-reply";
72     private static final String DATA_ELEMENT = "data";
73
74     private static Document RPC_REPLY_OK = null;
75
76     static {
77         try {
78             RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpc-reply_ok.xml");
79         } catch (Exception e) {
80             LOG.debug("unable to load rpc reply ok.", e);
81             RPC_REPLY_OK = XmlUtil.newDocument();
82         }
83     }
84
85     private CurrentSchemaContext currentSchemaContext = null;
86     private SchemaContext schemaContext = null;
87     private String sessionIdForReporting = "netconf-test-session1";
88
89     private TransactionProvider transactionProvider = null;
90
91
92     @Before
93     public void setUp() throws Exception {
94
95         XMLUnit.setIgnoreWhitespace(true);
96         XMLUnit.setIgnoreAttributeOrder(true);
97
98         this.schemaContext = parseSchemas(getYangSchemas());
99         schemaContext.getModules();
100         SchemaService schemaService = createSchemaService();
101
102         final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
103         final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
104
105         final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
106         datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
107         datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
108
109         ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
110                 16, 16, "CommitFutures");
111
112         ConcurrentDOMDataBroker cdb = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
113         this.transactionProvider = new TransactionProvider(cdb, sessionIdForReporting);
114         this.currentSchemaContext = new CurrentSchemaContext(schemaService);
115
116     }
117
118     @Test
119     public void testEmptyDatastore() throws Exception {
120
121         Document response = getConfigRunning();
122         assertEmptyDatastore(response);
123
124         response = getConfigCandidate();
125         assertEmptyDatastore(response);
126
127         response = get();
128         assertEmptyDatastore(response);
129
130     }
131
132     @Test
133     public void testEditRunning() throws Exception {
134
135         try {
136             edit("messages/mapping/editConfig_running.xml");
137             fail("Should have failed - edit config on running datastore is not supported");
138         } catch (NetconfDocumentedException e) {
139             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
140             assertTrue(e.getErrorTag() == ErrorTag.operation_not_supported);
141             assertTrue(e.getErrorType() == ErrorType.protocol);
142         }
143
144     }
145
146     @Test
147     public void testCandidateTransaction() throws Exception {
148
149         verifyResponse(edit("messages/mapping/editConfig_merge_n1.xml"), RPC_REPLY_OK);
150         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_n1_control.xml"));
151         assertEmptyDatastore(getConfigRunning());
152
153         verifyResponse(discardChanges(), RPC_REPLY_OK);
154         assertEmptyDatastore(getConfigCandidate());
155
156     }
157
158     @Test
159     public void testEditWithCommit() throws Exception {
160
161         verifyResponse(edit("messages/mapping/editConfig_merge_n1.xml"), RPC_REPLY_OK);
162         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_n1_control.xml"));
163
164         verifyResponse(commit(), RPC_REPLY_OK);
165         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_n1_control.xml"));
166
167         deleteDatastore();
168
169     }
170
171     @Test
172     public void testMultipleEditsWithMerge() throws Exception {
173
174         verifyResponse(edit("messages/mapping/editConfig_merge_multiple_1.xml"), RPC_REPLY_OK);
175         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_control_1.xml"));
176         verifyResponse(edit("messages/mapping/editConfig_merge_single_1.xml"), RPC_REPLY_OK);
177         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_control_2.xml"));
178         assertEmptyDatastore(getConfigRunning());
179
180         verifyResponse(commit(), RPC_REPLY_OK);
181         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_control_2.xml"));
182
183         deleteDatastore();
184
185     }
186
187     @Ignore("Xml is not similar")
188     @Test
189     public void testMoreComplexEditConfigs() throws Exception {
190
191         verifyResponse(edit("messages/mapping/editConfig_merge_multiple_1.xml"), RPC_REPLY_OK);
192         verifyResponse(edit("messages/mapping/editConfig_merge_single_1.xml"), RPC_REPLY_OK);
193
194         verifyResponse(edit("messages/mapping/editConfig_merge_multiple_2.xml"), RPC_REPLY_OK);
195         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_after_more_complex_merge.xml"));
196
197         verifyResponse(edit("messages/mapping/editConfig_merge_multiple_3.xml"), RPC_REPLY_OK);
198         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_after_more_complex_merge_2.xml"));
199
200         verifyResponse(edit("messages/mapping/editConfig_merge_multiple_4_replace.xml"), RPC_REPLY_OK);
201         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_after_replace.xml"));
202         verifyResponse(commit(), RPC_REPLY_OK);
203
204         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_after_replace.xml"));
205
206         verifyResponse(edit("messages/mapping/editConfig_replace_default.xml"), RPC_REPLY_OK);
207         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_replace_default_control.xml"));
208         verifyResponse(commit(), RPC_REPLY_OK);
209
210         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_replace_default_control.xml"));
211
212         deleteDatastore();
213
214     }
215
216     @Test
217     public void testLock() throws Exception {
218
219         verifyResponse(lockCandidate(), RPC_REPLY_OK);
220
221         try {
222             lock();
223             fail("Should have failed - locking of running datastore is not supported");
224         } catch (NetconfDocumentedException e) {
225             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
226             assertTrue(e.getErrorTag() == ErrorTag.operation_not_supported);
227             assertTrue(e.getErrorType() == ErrorType.application);
228         }
229     }
230
231     @Test
232     public void testUnlock() throws Exception {
233
234         verifyResponse(unlockCandidate(), RPC_REPLY_OK);
235
236         try {
237             unlock();
238             fail("Should have failed - unlocking of running datastore is not supported");
239         } catch (NetconfDocumentedException e) {
240             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
241             assertTrue(e.getErrorTag() == ErrorTag.operation_not_supported);
242             assertTrue(e.getErrorType() == ErrorType.application);
243         }
244     }
245
246     @Ignore("Xml is not similar")
247     @Test
248     public void testEditWithCreate() throws Exception {
249
250         verifyResponse(edit("messages/mapping/editConfig_create.xml"), RPC_REPLY_OK);
251         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_n1_control.xml"));
252
253         try {
254             edit("messages/mapping/editConfig_create.xml");
255             fail("Create should have failed - data already exists");
256         } catch (NetconfDocumentedException e) {
257             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
258             assertTrue(e.getErrorTag() == ErrorTag.data_exists);
259             assertTrue(e.getErrorType() == ErrorType.protocol);
260         }
261
262         verifyResponse(discardChanges(), RPC_REPLY_OK);
263
264     }
265
266     @Test
267     public void testDeleteNonExisting() throws Exception {
268
269         assertEmptyDatastore(getConfigCandidate());
270         assertEmptyDatastore(getConfigRunning());
271
272         try {
273             edit("messages/mapping/editConfig_delete-root.xml");
274             fail("Delete should have failed - data is missing");
275         } catch (NetconfDocumentedException e) {
276             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
277             assertTrue(e.getErrorTag() == ErrorTag.data_missing);
278             assertTrue(e.getErrorType() == ErrorType.protocol);
279         }
280
281     }
282
283     @Test
284     public void testEditMissingDefaultOperation() throws Exception {
285
286         verifyResponse(edit("messages/mapping/editConfig_merge_missing_default-operation_1.xml"), RPC_REPLY_OK);
287         verifyResponse(edit("messages/mapping/editConfig_merge_missing_default-operation_2.xml"), RPC_REPLY_OK);
288         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_missing_default-operation_control.xml"));
289
290         verifyResponse(commit(), RPC_REPLY_OK);
291         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_missing_default-operation_control.xml"));
292
293         deleteDatastore();
294     }
295
296     private void deleteDatastore() throws Exception{
297         verifyResponse(edit("messages/mapping/editConfig_delete-root.xml"), RPC_REPLY_OK);
298         assertEmptyDatastore(getConfigCandidate());
299
300         verifyResponse(commit(), RPC_REPLY_OK);
301         assertEmptyDatastore(getConfigRunning());
302     }
303
304     private void verifyResponse(Document response, Document template) {
305         DetailedDiff dd = new DetailedDiff(new Diff(response, template));
306         dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
307         assertTrue(dd.similar());
308     }
309
310     private void assertEmptyDatastore(Document response) {
311
312         NodeList nodes = response.getChildNodes();
313         assertTrue(nodes.getLength() == 1);
314
315         assertEquals(nodes.item(0).getLocalName(),RPC_REPLY_ELEMENT);
316
317         NodeList replyNodes = nodes.item(0).getChildNodes();
318         assertTrue(replyNodes.getLength() == 1);
319
320         Node dataNode = replyNodes.item(0);
321         assertEquals(dataNode.getLocalName(), DATA_ELEMENT);
322         assertFalse(dataNode.hasChildNodes());
323
324     }
325
326     private Document commit() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
327         Commit commit = new Commit(sessionIdForReporting, transactionProvider);
328         return executeOperation(commit, "messages/mapping/commit.xml");
329     }
330
331     private Document discardChanges() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
332         DiscardChanges discardOp = new DiscardChanges(sessionIdForReporting, transactionProvider);
333         return executeOperation(discardOp, "messages/mapping/discardChanges.xml");
334     }
335
336     private Document edit(String resource) throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
337         EditConfig editConfig = new EditConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
338         return executeOperation(editConfig, resource);
339     }
340
341     private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
342         Get get = new Get(sessionIdForReporting, currentSchemaContext, transactionProvider);
343         return executeOperation(get, "messages/mapping/get.xml");
344     }
345
346     private Document getConfigRunning() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
347         GetConfig getConfig = new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
348         return executeOperation(getConfig, "messages/mapping/getConfig.xml");
349     }
350
351     private Document getConfigCandidate() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
352         GetConfig getConfig = new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
353         return executeOperation(getConfig, "messages/mapping/getConfig_candidate.xml");
354     }
355
356     private Document lock() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
357         Lock lock = new Lock(sessionIdForReporting);
358         return executeOperation(lock, "messages/mapping/lock.xml");
359     }
360
361     private Document unlock() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
362         Unlock unlock = new Unlock(sessionIdForReporting);
363         return executeOperation(unlock, "messages/mapping/unlock.xml");
364     }
365
366     private Document lockCandidate() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
367         Lock lock = new Lock(sessionIdForReporting);
368         return executeOperation(lock, "messages/mapping/lock_candidate.xml");
369     }
370
371     private Document unlockCandidate() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
372         Unlock unlock = new Unlock(sessionIdForReporting);
373         return executeOperation(unlock, "messages/mapping/unlock_candidate.xml");
374     }
375
376     private Document executeOperation(NetconfOperation op, String filename) throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
377         final Document request = XmlFileLoader.xmlFileToDocument(filename);
378
379         HandlingPriority priority = op.canHandle(request);
380         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
381
382         final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
383
384         LOG.debug("Got response {}" , response);
385
386         return response;
387     }
388
389     private Collection<InputStream> getYangSchemas() {
390         final List<String> schemaPaths = Arrays.asList("/META-INF/yang/config.yang", "/yang/mdsal-netconf-mapping-test.yang");
391         final List<InputStream> schemas = new ArrayList<>();
392
393         for (String schemaPath : schemaPaths) {
394             InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
395             schemas.add(resourceAsStream);
396         }
397
398         return schemas;
399     }
400
401     private SchemaContext parseSchemas(Collection<InputStream> schemas) throws IOException, YangSyntaxErrorException {
402         final YangParserImpl parser = new YangParserImpl();
403         Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(schemas);
404         return parser.parseSources(sources);
405     }
406
407     private SchemaService createSchemaService() {
408         return new SchemaService() {
409
410             @Override
411             public void addModule(Module module) {
412             }
413
414             @Override
415             public void removeModule(Module module) {
416
417             }
418
419             @Override
420             public SchemaContext getSessionContext() {
421                 return schemaContext;
422             }
423
424             @Override
425             public SchemaContext getGlobalContext() {
426                 return schemaContext;
427             }
428
429             @Override
430             public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
431                 listener.onGlobalContextUpdated(getGlobalContext());
432                 return new ListenerRegistration<SchemaContextListener>() {
433                     @Override
434                     public void close() {
435
436                     }
437
438                     @Override
439                     public SchemaContextListener getInstance() {
440                         return listener;
441                     }
442                 };
443             }
444         };
445     }
446 }