2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.confignetconfconnector;
11 import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertThat;
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.anyString;
18 import static org.mockito.Mockito.doNothing;
19 import static org.mockito.Mockito.doReturn;
20 import static org.mockito.Mockito.mock;
21 import static org.mockito.Mockito.verify;
22 import static org.mockito.Mockito.verifyNoMoreInteractions;
23 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElement;
24 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
25 import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToElement;
27 import com.google.common.base.Optional;
28 import com.google.common.base.Preconditions;
29 import com.google.common.collect.ImmutableMap;
30 import com.google.common.collect.Lists;
31 import com.google.common.collect.Maps;
32 import com.google.common.collect.Sets;
33 import java.io.FileNotFoundException;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.math.BigInteger;
37 import java.net.URISyntaxException;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.Collection;
41 import java.util.Collections;
42 import java.util.HashSet;
43 import java.util.List;
45 import java.util.Map.Entry;
47 import javax.management.InstanceAlreadyExistsException;
48 import javax.management.InstanceNotFoundException;
49 import javax.management.ObjectName;
50 import javax.xml.parsers.ParserConfigurationException;
51 import org.custommonkey.xmlunit.AbstractNodeTester;
52 import org.custommonkey.xmlunit.NodeTest;
53 import org.custommonkey.xmlunit.NodeTestException;
54 import org.custommonkey.xmlunit.NodeTester;
55 import org.custommonkey.xmlunit.XMLAssert;
56 import org.custommonkey.xmlunit.XMLUnit;
57 import org.hamcrest.CoreMatchers;
58 import org.junit.Before;
59 import org.junit.Ignore;
60 import org.junit.Test;
61 import org.mockito.Mock;
62 import org.mockito.MockitoAnnotations;
63 import org.opendaylight.controller.config.api.ConflictingVersionException;
64 import org.opendaylight.controller.config.api.ValidationException;
65 import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
66 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
67 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
68 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
69 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
70 import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
71 import org.opendaylight.controller.config.yang.test.impl.ComplexList;
72 import org.opendaylight.controller.config.yang.test.impl.Deep;
73 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
74 import org.opendaylight.controller.config.yang.test.impl.DtoAInner;
75 import org.opendaylight.controller.config.yang.test.impl.DtoAInnerInner;
76 import org.opendaylight.controller.config.yang.test.impl.DtoC;
77 import org.opendaylight.controller.config.yang.test.impl.DtoD;
78 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
79 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
80 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
81 import org.opendaylight.controller.config.yang.test.impl.Peers;
82 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
83 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
84 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
85 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
86 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
87 import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
88 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Lock;
89 import org.opendaylight.controller.netconf.confignetconfconnector.operations.UnLock;
90 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
91 import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
92 import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
93 import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
94 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
95 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService;
96 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
97 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
98 import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
99 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
100 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
101 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
102 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
103 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
104 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
105 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
108 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
109 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
110 import org.opendaylight.yangtools.yang.model.api.Module;
111 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
112 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
113 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
114 import org.osgi.framework.Filter;
115 import org.osgi.framework.ServiceListener;
116 import org.osgi.framework.ServiceReference;
117 import org.slf4j.Logger;
118 import org.slf4j.LoggerFactory;
119 import org.w3c.dom.Document;
120 import org.w3c.dom.Element;
121 import org.w3c.dom.Node;
122 import org.w3c.dom.NodeList;
123 import org.w3c.dom.Text;
124 import org.w3c.dom.traversal.DocumentTraversal;
125 import org.xml.sax.SAXException;
128 public class NetconfMappingTest extends AbstractConfigTest {
129 private static final Logger LOG = LoggerFactory.getLogger(NetconfMappingTest.class);
131 private static final String INSTANCE_NAME = "instance-from-code";
132 private static final String NETCONF_SESSION_ID = "foo";
133 private static final String TEST_NAMESPACE= "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
134 private NetconfTestImplModuleFactory factory;
135 private DepTestImplModuleFactory factory2;
136 private IdentityTestModuleFactory factory3;
137 private TestImplModuleFactory factory4;
140 YangStoreContext yangStoreSnapshot;
142 NetconfOperationRouter netconfOperationRouter;
144 AggregatedNetconfOperationServiceFactory netconfOperationServiceSnapshot;
146 private AutoCloseable sessionCloseable;
148 private TransactionProvider transactionProvider;
151 public void setUp() throws Exception {
152 MockitoAnnotations.initMocks(this);
155 final Filter filter = mock(Filter.class);
156 doReturn(filter).when(mockedContext).createFilter(anyString());
157 doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
158 doReturn(new ServiceReference<?>[]{}).when(mockedContext).getServiceReferences(anyString(), anyString());
160 doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
161 doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
163 this.factory = new NetconfTestImplModuleFactory();
164 this.factory2 = new DepTestImplModuleFactory();
165 this.factory3 = new IdentityTestModuleFactory();
166 factory4 = new TestImplModuleFactory();
167 doNothing().when(sessionCloseable).close();
169 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory, this.factory2,
170 this.factory3, factory4));
172 transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
175 private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException, InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
176 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
178 final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
179 final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
180 setModule(mxBean, transaction, instanceName + "_dep");
183 for (Class<? extends AbstractServiceInterface> sInterface : factory.getImplementedServiceIntefaces()) {
184 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
185 transaction.saveServiceReference(
186 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + instanceName + "_" + i++,
190 transaction.commit();
195 public void testIdentityRefs() throws Exception {
196 edit("netconfMessages/editConfig_identities.xml");
203 protected CodecRegistry getCodecRegistry() {
204 IdentityCodec<?> idCodec = mock(IdentityCodec.class);
205 doReturn(TestIdentity1.class).when(idCodec).deserialize(TestIdentity1.QNAME);
206 doReturn(TestIdentity2.class).when(idCodec).deserialize(TestIdentity2.QNAME);
208 CodecRegistry codecReg = super.getCodecRegistry();
209 doReturn(idCodec).when(codecReg).getIdentityCodec();
214 public void testServicePersistance() throws Exception {
215 createModule(INSTANCE_NAME);
217 edit("netconfMessages/editConfig.xml");
218 Document config = getConfigCandidate();
219 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
220 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
221 "ref_from_code_to_instance-from-code_1"));
224 edit("netconfMessages/editConfig_addServiceName.xml");
225 config = getConfigCandidate();
226 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
227 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
228 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
230 edit("netconfMessages/editConfig_addServiceNameOnTest.xml");
231 config = getConfigCandidate();
232 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
233 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
234 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
237 config = getConfigRunning();
238 assertCorrectRefNamesForDependencies(config);
239 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
240 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
241 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
243 edit("netconfMessages/editConfig_replace_default.xml");
244 config = getConfigCandidate();
245 assertCorrectServiceNames(config, Collections.<String>emptySet());
247 edit("netconfMessages/editConfig_remove.xml");
248 config = getConfigCandidate();
249 assertCorrectServiceNames(config, Collections.<String>emptySet());
252 config = getConfigCandidate();
253 assertCorrectServiceNames(config, Collections.<String>emptySet());
258 public void testUnLock() throws Exception {
259 assertTrue(NetconfMessageUtil.isOKMessage(lockCandidate()));
260 assertTrue(NetconfMessageUtil.isOKMessage(unlockCandidate()));
263 private void assertCorrectRefNamesForDependencies(Document config) throws NodeTestException {
264 NodeList modulesList = config.getElementsByTagName("modules");
265 assertEquals(1, modulesList.getLength());
267 NodeTest nt = new NodeTest((DocumentTraversal) config, modulesList.item(0));
268 NodeTester tester = new AbstractNodeTester() {
269 private int defaultRefNameCount = 0;
270 private int userRefNameCount = 0;
273 public void testText(Text text) throws NodeTestException {
274 if(text.getData().equals("ref_dep2")) {
275 defaultRefNameCount++;
276 } else if(text.getData().equals("ref_dep_user_two")) {
282 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
283 assertEquals(0, defaultRefNameCount);
284 assertEquals(2, userRefNameCount);
287 nt.performTest(tester, Node.TEXT_NODE);
290 private void assertCorrectServiceNames(Document configCandidate, Set<String> refNames) throws NodeTestException {
291 final Set<String> refNames2 = new HashSet<>(refNames);
292 NodeList servicesNodes = configCandidate.getElementsByTagName("services");
293 assertEquals(1, servicesNodes.getLength());
295 NodeTest nt = new NodeTest((DocumentTraversal) configCandidate, servicesNodes.item(0));
296 NodeTester tester = new AbstractNodeTester() {
299 public void testElement(Element element) throws NodeTestException {
300 if(element.getNodeName() != null) {
301 if(element.getNodeName().equals("name")) {
302 String elmText = element.getTextContent();
303 if(refNames2.contains(elmText)) {
304 refNames2.remove(elmText);
306 throw new NodeTestException("Unexpected services defined: " + elmText);
313 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
314 assertEquals(Collections.<String>emptySet(), refNames2);
315 assertTrue(refNames2.toString(), refNames2.isEmpty());
318 nt.performTest(tester, Node.ELEMENT_NODE);
322 public void testConfigNetconfUnionTypes() throws Exception {
324 createModule(INSTANCE_NAME);
326 edit("netconfMessages/editConfig.xml");
328 Document response = getConfigRunning();
329 Element ipElement = readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
330 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
332 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
335 edit("netconfMessages/editConfig_setUnions.xml");
337 response = getConfigRunning();
338 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
339 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">randomStringForUnion</union-test-attr>"));
344 public void testConfigNetconf() throws Exception {
346 createModule(INSTANCE_NAME);
348 edit("netconfMessages/editConfig.xml");
349 Document configCandidate = getConfigCandidate();
350 checkBinaryLeafEdited(configCandidate);
353 // default-operation:none, should not affect binary leaf
354 edit("netconfMessages/editConfig_none.xml");
355 checkBinaryLeafEdited(getConfigCandidate());
359 Document response = getConfigRunning();
361 checkBinaryLeafEdited(response);
362 checkTypeConfigAttribute(response);
363 checkTypedefs(response);
364 checkTestingDeps(response);
366 checkBigDecimal(response);
368 edit("netconfMessages/editConfig_remove.xml");
371 assertXMLEqual(getConfigCandidate(), getConfigRunning());
373 final Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
374 XMLUnit.setIgnoreWhitespace(true);
375 assertXMLEqual(expectedResult, getConfigRunning());
376 assertXMLEqual(expectedResult, getConfigCandidate());
378 edit("netconfMessages/editConfig_none.xml");
380 verify(sessionCloseable).close();
381 verifyNoMoreInteractions(netconfOperationRouter);
382 verifyNoMoreInteractions(netconfOperationServiceSnapshot);
385 private void checkBigDecimal(Document response) throws NodeTestException, SAXException, IOException {
386 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
388 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
392 private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
394 DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, sessionCloseable);
395 executeOp(closeOp, "netconfMessages/closeSession.xml");
398 private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
399 NetconfDocumentedException {
400 EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
402 executeOp(editOp, resource);
405 private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
406 Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
407 executeOp(commitOp, "netconfMessages/commit.xml");
410 private Document lockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
411 Lock commitOp = new Lock(NETCONF_SESSION_ID);
412 return executeOp(commitOp, "netconfMessages/lock.xml");
415 private Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
416 UnLock commitOp = new UnLock(NETCONF_SESSION_ID);
417 return executeOp(commitOp, "netconfMessages/unlock.xml");
420 private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
421 NetconfDocumentedException {
422 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
423 configRegistryClient, NETCONF_SESSION_ID);
424 return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
427 private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
428 NetconfDocumentedException {
429 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
430 configRegistryClient, NETCONF_SESSION_ID);
431 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
434 @Ignore("second edit message corrupted")
435 @Test(expected = NetconfDocumentedException.class)
436 public void testConfigNetconfReplaceDefaultEx() throws Exception {
438 createModule(INSTANCE_NAME);
440 edit("netconfMessages/editConfig.xml");
441 edit("netconfMessages/editConfig_replace_default_ex.xml");
445 public void testConfigNetconfReplaceDefault() throws Exception {
447 createModule(INSTANCE_NAME);
449 edit("netconfMessages/editConfig.xml");
451 Document response = getConfigRunning();
452 final int allInstances = response.getElementsByTagName("module").getLength();
454 edit("netconfMessages/editConfig_replace_default.xml");
457 response = getConfigRunning();
459 final int afterReplace = response.getElementsByTagName("module").getLength();
460 assertEquals(4, allInstances);
461 assertEquals(2, afterReplace);
465 public void testSameAttrDifferentNamespaces() throws Exception {
467 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
469 } catch (NetconfDocumentedException e) {
470 String message = e.getMessage();
471 assertContainsString(message, "Element simpleInt present multiple times with different namespaces");
472 assertContainsString(message, TEST_NAMESPACE);
473 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
478 public void testDifferentNamespaceInTO() throws Exception {
480 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
482 } catch (NetconfDocumentedException e) {
483 String message = e.getMessage();
484 assertContainsString(message, "Unrecognised elements");
485 assertContainsString(message, "simple-int2");
486 assertContainsString(message, "dto_d");
491 public void testSameAttrDifferentNamespacesList() throws Exception {
493 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
495 } catch (NetconfDocumentedException e) {
496 String message = e.getMessage();
497 assertContainsString(message, "Element allow-user present multiple times with different namespaces");
498 assertContainsString(message, TEST_NAMESPACE);
499 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
504 public void testTypeNameConfigAttributeMatching() throws Exception {
505 edit("netconfMessages/editConfig.xml");
507 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
510 Document response = getConfigRunning();
511 checkTypeConfigAttribute(response);
514 // TODO add <modules operation="replace"> functionality
515 @Test(expected = NetconfDocumentedException.class)
516 public void testConfigNetconfReplaceModuleEx() throws Exception {
518 createModule(INSTANCE_NAME);
520 edit("netconfMessages/editConfig.xml");
521 edit("netconfMessages/editConfig_replace_module_ex.xml");
525 public void testUnrecognisedConfigElements() throws Exception {
527 String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
528 final int TESTS_COUNT = 8;
530 for (int i = 0; i < TESTS_COUNT; i++) {
531 String file = String.format(format, i + 1);
532 LOG.info("Reading {}", file);
535 } catch (NetconfDocumentedException e) {
536 assertContainsString(e.getMessage(), "Unrecognised elements");
537 assertContainsString(e.getMessage(), "unknownAttribute");
540 fail("Unrecognised test should throw exception " + file);
547 public void testConfigNetconfReplaceModule() throws Exception {
549 createModule(INSTANCE_NAME);
551 edit("netconfMessages/editConfig.xml");
553 Document response = getConfigRunning();
554 final int allInstances = response.getElementsByTagName("instance").getLength();
556 edit("netconfMessages/editConfig_replace_module.xml");
559 response = getConfigRunning();
560 final int afterReplace = response.getElementsByTagName("instance").getLength();
562 assertEquals(4 + 4 /* Instances from services */, allInstances);
563 assertEquals(3 + 3, afterReplace);
566 @Test(expected = NetconfDocumentedException.class)
567 public void testEx() throws Exception {
572 @Test(expected = NetconfDocumentedException.class)
573 public void testEx2() throws Exception {
577 private void discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
578 DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
579 executeOp(discardOp, "netconfMessages/discardChanges.xml");
582 private void checkBinaryLeafEdited(final Document response) throws NodeTestException, SAXException, IOException {
583 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
584 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
587 private void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
589 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
591 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
593 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
595 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
597 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">TWO</extended-enum>"));
599 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ONE</extended-enum>"));
602 private void assertContainsString(String string, String substring) {
603 assertThat(string, CoreMatchers.containsString(substring));
606 private void checkEnum(final Document response) throws Exception {
608 String expectedEnumContent = "TWO";
610 XMLAssert.assertXpathEvaluatesTo(expectedEnumContent,
611 getXpathForNetconfImplSubnode(INSTANCE_NAME,"extended-enum"),
615 private void checkTestingDeps(Document response) {
616 int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
617 assertEquals(2, testingDepsSize);
620 private String getXpathForNetconfImplSubnode(String instanceName, String subnode) {
621 return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply" +
622 "/urn:ietf:params:xml:ns:netconf:base:1.0:data" +
623 "/urn:opendaylight:params:xml:ns:yang:controller:config:modules" +
624 "/module[name='"+instanceName+"']" +
625 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf" +
626 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:"+subnode;
629 private void checkTypeConfigAttribute(Document response) throws Exception {
631 Map<String,String> namesToTypeValues = ImmutableMap.of("instance-from-code", "configAttributeType",
632 "test2", "default-string");
633 for (Entry<String, String> nameToExpectedValue : namesToTypeValues.entrySet()) {
634 XMLAssert.assertXpathEvaluatesTo(nameToExpectedValue.getValue(),
635 getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(),"type"),
640 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
641 final List<InputStream> yangDependencies = getYangs();
643 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
645 YangParserImpl yangParser = new YangParserImpl();
646 final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(yangDependencies).values()));
647 YangStoreService yangStoreService = new YangStoreService(new SchemaContextProvider() {
649 public SchemaContext getSchemaContext() {
650 return schemaContext ;
653 mBeanEntries.putAll(yangStoreService.getModuleMXBeanEntryMap());
658 private Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() throws Exception {
659 SchemaContext resolveSchemaContext = getSchemaContext();
660 return resolveSchemaContext.getModules();
663 private SchemaContext getSchemaContext() throws Exception {
664 final List<InputStream> yangDependencies = getYangs();
665 YangParserImpl parser = new YangParserImpl();
667 Set<Module> allYangModules = parser.parseYangModelsFromStreams(yangDependencies);
669 return parser.resolveSchemaContext(Sets
670 .newHashSet(allYangModules));
674 public void testConfigNetconfRuntime() throws Exception {
676 createModule(INSTANCE_NAME);
678 edit("netconfMessages/editConfig.xml");
679 checkBinaryLeafEdited(getConfigCandidate());
683 Document response = get();
685 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
687 assertEquals(2, getElementsSize(response, "asdf"));
688 // data from running config
689 assertEquals(2, getElementsSize(response, "simple-short"));
691 assertEquals(8, getElementsSize(response, "inner-running-data"));
692 assertEquals(8, getElementsSize(response, "deep2"));
693 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
694 assertEquals(8 * 4, getElementsSize(response, "deep3"));
695 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
696 assertEquals(8, getElementsSize(response, "inner-running-data-additional", "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
697 assertEquals(8, getElementsSize(response, "deep4"));
700 RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
702 response = executeOp(netconf, "netconfMessages/rpc.xml");
703 assertContainsElementWithText(response, "testarg1");
705 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
706 Document expectedReplyOk = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
707 XMLUnit.setIgnoreWhitespace(true);
708 XMLAssert.assertXMLEqual(expectedReplyOk, response);
710 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
711 assertContainsElementWithText(response, "true");
713 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
714 assertContainsElementWithText(response, "1");
715 assertContainsElementWithText(response, "2");
718 private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
719 Get getOp = new Get(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
720 return executeOp(getOp, "netconfMessages/get.xml");
723 private int getElementsSize(Document response, String elementName) {
724 return response.getElementsByTagName(elementName).getLength();
727 private int getElementsSize(Document response, String elementName, String namespace) {
728 return response.getElementsByTagNameNS(namespace, elementName).getLength();
731 private Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
732 SAXException, IOException, NetconfDocumentedException {
734 final Document request = XmlFileLoader.xmlFileToDocument(filename);
736 LOG.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
737 HandlingPriority priority = op.canHandle(request);
739 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
741 final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
742 LOG.debug("Got response\n{}", XmlUtil.toString(response));
746 private List<InputStream> getYangs() throws FileNotFoundException {
747 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
748 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
749 "/META-INF/yang/test-groups.yang", "/META-INF/yang/ietf-inet-types.yang");
750 final Collection<InputStream> yangDependencies = new ArrayList<>();
751 for (String path : paths) {
752 final InputStream is = Preconditions
753 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
754 yangDependencies.add(is);
756 return Lists.newArrayList(yangDependencies);
759 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, String depName)
760 throws InstanceAlreadyExistsException, InstanceNotFoundException {
761 mxBean.setSimpleInt((long) 44);
762 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
763 final DtoD dtob = getDtoD();
764 mxBean.setDtoD(dtob);
766 final DtoC dtoa = getDtoC();
767 mxBean.setDtoC(dtoa);
768 mxBean.setSimpleBoolean(false);
770 final Peers p1 = new Peers();
773 p1.setSimpleInt3(456);
774 final Peers p2 = new Peers();
776 p2.setPort("port23");
777 p2.setSimpleInt3(456);
778 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
780 mxBean.setSimpleLong(454545L);
781 mxBean.setSimpleLong2(44L);
782 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
783 mxBean.setSimpleByte(new Byte((byte) 4));
784 mxBean.setSimpleShort(new Short((short) 4));
785 mxBean.setSimpleTest(545);
787 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
788 mxBean.setSimpleList(Lists.<Integer> newArrayList());
790 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
792 for (Class<? extends AbstractServiceInterface> sInterface : factory2.getImplementedServiceIntefaces()) {
793 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
794 transaction.saveServiceReference(
795 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + depName + "_" + i++,
799 mxBean.setTestingDep(testingDepOn);
802 private static DtoD getDtoD() {
803 final DtoD dtob = new DtoD();
804 dtob.setSimpleInt1((long) 444);
805 dtob.setSimpleInt2((long) 4444);
806 dtob.setSimpleInt3(454);
807 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
808 final Deep deep = new Deep();
809 deep.setSimpleInt3(4);
810 dtobInner.setDeep(deep);
811 dtobInner.setSimpleInt3(44);
812 dtobInner.setSimpleList(Lists.newArrayList(4));
813 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
814 dtob.setSimpleList(Lists.newArrayList(4));
818 private static DtoC getDtoC() {
819 final DtoC dtoa = new DtoC();
820 // dtoa.setSimpleArg((long) 55);
821 final DtoAInner dtoAInner = new DtoAInner();
822 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
823 dtoAInnerInner.setSimpleArg(456L);
824 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
825 dtoAInner.setSimpleArg(44L);
826 dtoa.setDtoAInner(dtoAInner);