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 io.netty.channel.Channel;
34 import java.io.FileNotFoundException;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.math.BigInteger;
38 import java.net.URISyntaxException;
39 import java.util.ArrayList;
40 import java.util.Arrays;
41 import java.util.Collection;
42 import java.util.Collections;
43 import java.util.HashSet;
44 import java.util.List;
46 import java.util.Map.Entry;
48 import javax.management.InstanceAlreadyExistsException;
49 import javax.management.InstanceNotFoundException;
50 import javax.management.ObjectName;
51 import javax.xml.parsers.ParserConfigurationException;
52 import org.custommonkey.xmlunit.AbstractNodeTester;
53 import org.custommonkey.xmlunit.NodeTest;
54 import org.custommonkey.xmlunit.NodeTestException;
55 import org.custommonkey.xmlunit.NodeTester;
56 import org.custommonkey.xmlunit.XMLAssert;
57 import org.custommonkey.xmlunit.XMLUnit;
58 import org.hamcrest.CoreMatchers;
59 import org.junit.Before;
60 import org.junit.Ignore;
61 import org.junit.Test;
62 import org.mockito.Mock;
63 import org.mockito.MockitoAnnotations;
64 import org.opendaylight.controller.config.api.ConflictingVersionException;
65 import org.opendaylight.controller.config.api.ValidationException;
66 import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
67 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
68 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
69 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
70 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
71 import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
72 import org.opendaylight.controller.config.yang.test.impl.ComplexList;
73 import org.opendaylight.controller.config.yang.test.impl.Deep;
74 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
75 import org.opendaylight.controller.config.yang.test.impl.DtoAInner;
76 import org.opendaylight.controller.config.yang.test.impl.DtoAInnerInner;
77 import org.opendaylight.controller.config.yang.test.impl.DtoC;
78 import org.opendaylight.controller.config.yang.test.impl.DtoD;
79 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
80 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
81 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
82 import org.opendaylight.controller.config.yang.test.impl.Peers;
83 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
84 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
85 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
86 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
87 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
88 import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
89 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Lock;
90 import org.opendaylight.controller.netconf.confignetconfconnector.operations.UnLock;
91 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
92 import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
93 import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
94 import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
95 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
96 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService;
97 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
98 import org.opendaylight.controller.netconf.impl.NetconfServerSession;
99 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListener;
100 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
101 import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
102 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
103 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
104 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
105 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
106 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
107 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
108 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
109 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
112 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
113 import org.opendaylight.yangtools.yang.model.api.Module;
114 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
115 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
116 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
117 import org.osgi.framework.Filter;
118 import org.osgi.framework.ServiceListener;
119 import org.osgi.framework.ServiceReference;
120 import org.slf4j.Logger;
121 import org.slf4j.LoggerFactory;
122 import org.w3c.dom.Document;
123 import org.w3c.dom.Element;
124 import org.w3c.dom.Node;
125 import org.w3c.dom.NodeList;
126 import org.w3c.dom.Text;
127 import org.w3c.dom.traversal.DocumentTraversal;
128 import org.xml.sax.SAXException;
131 public class NetconfMappingTest extends AbstractConfigTest {
132 private static final Logger LOG = LoggerFactory.getLogger(NetconfMappingTest.class);
134 private static final String INSTANCE_NAME = "instance-from-code";
135 private static final String NETCONF_SESSION_ID = "foo";
136 private static final String TEST_NAMESPACE= "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
137 private NetconfTestImplModuleFactory factory;
138 private DepTestImplModuleFactory factory2;
139 private IdentityTestModuleFactory factory3;
140 private TestImplModuleFactory factory4;
143 YangStoreContext yangStoreSnapshot;
145 NetconfOperationRouter netconfOperationRouter;
147 AggregatedNetconfOperationServiceFactory netconfOperationServiceSnapshot;
149 private AutoCloseable sessionCloseable;
151 private TransactionProvider transactionProvider;
154 public void setUp() throws Exception {
155 MockitoAnnotations.initMocks(this);
158 final Filter filter = mock(Filter.class);
159 doReturn(filter).when(mockedContext).createFilter(anyString());
160 doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
161 doReturn(new ServiceReference<?>[]{}).when(mockedContext).getServiceReferences(anyString(), anyString());
163 doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
164 doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
166 this.factory = new NetconfTestImplModuleFactory();
167 this.factory2 = new DepTestImplModuleFactory();
168 this.factory3 = new IdentityTestModuleFactory();
169 factory4 = new TestImplModuleFactory();
170 doNothing().when(sessionCloseable).close();
172 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory, this.factory2,
173 this.factory3, factory4));
175 transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
178 private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException, InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
179 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
181 final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
182 final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
183 setModule(mxBean, transaction, instanceName + "_dep");
186 for (Class<? extends AbstractServiceInterface> sInterface : factory.getImplementedServiceIntefaces()) {
187 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
188 transaction.saveServiceReference(
189 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + instanceName + "_" + i++,
193 transaction.commit();
198 public void testIdentityRefs() throws Exception {
199 edit("netconfMessages/editConfig_identities.xml");
206 protected BindingRuntimeContext getBindingRuntimeContext() {
207 final BindingRuntimeContext ret = super.getBindingRuntimeContext();
208 doReturn(TestIdentity1.class).when(ret).getIdentityClass(TestIdentity1.QNAME);
209 doReturn(TestIdentity2.class).when(ret).getIdentityClass(TestIdentity2.QNAME);
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 final Channel channel = mock(Channel.class);
395 doReturn("channel").when(channel).toString();
396 final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
397 final NetconfServerSession session =
398 new NetconfServerSession(listener, channel, 1L,
399 NetconfHelloMessageAdditionalHeader.fromString("[netconf;10.12.0.102:48528;ssh;;;;;;]"));
400 DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, sessionCloseable);
401 closeOp.setNetconfSession(session);
402 executeOp(closeOp, "netconfMessages/closeSession.xml");
405 private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
406 NetconfDocumentedException {
407 EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
409 executeOp(editOp, resource);
412 private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
413 Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
414 executeOp(commitOp, "netconfMessages/commit.xml");
417 private Document lockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
418 Lock commitOp = new Lock(NETCONF_SESSION_ID);
419 return executeOp(commitOp, "netconfMessages/lock.xml");
422 private Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
423 UnLock commitOp = new UnLock(NETCONF_SESSION_ID);
424 return executeOp(commitOp, "netconfMessages/unlock.xml");
427 private Document getConfigCandidate() 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_candidate.xml");
434 private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
435 NetconfDocumentedException {
436 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
437 configRegistryClient, NETCONF_SESSION_ID);
438 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
441 @Ignore("second edit message corrupted")
442 @Test(expected = NetconfDocumentedException.class)
443 public void testConfigNetconfReplaceDefaultEx() throws Exception {
445 createModule(INSTANCE_NAME);
447 edit("netconfMessages/editConfig.xml");
448 edit("netconfMessages/editConfig_replace_default_ex.xml");
452 public void testConfigNetconfReplaceDefault() throws Exception {
454 createModule(INSTANCE_NAME);
456 edit("netconfMessages/editConfig.xml");
458 Document response = getConfigRunning();
459 final int allInstances = response.getElementsByTagName("module").getLength();
461 edit("netconfMessages/editConfig_replace_default.xml");
464 response = getConfigRunning();
466 final int afterReplace = response.getElementsByTagName("module").getLength();
467 assertEquals(4, allInstances);
468 assertEquals(2, afterReplace);
472 public void testSameAttrDifferentNamespaces() throws Exception {
474 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
476 } catch (NetconfDocumentedException e) {
477 String message = e.getMessage();
478 assertContainsString(message, "Element simpleInt present multiple times with different namespaces");
479 assertContainsString(message, TEST_NAMESPACE);
480 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
485 public void testDifferentNamespaceInTO() throws Exception {
487 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
489 } catch (NetconfDocumentedException e) {
490 String message = e.getMessage();
491 assertContainsString(message, "Unrecognised elements");
492 assertContainsString(message, "simple-int2");
493 assertContainsString(message, "dto_d");
498 public void testSameAttrDifferentNamespacesList() throws Exception {
500 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
502 } catch (NetconfDocumentedException e) {
503 String message = e.getMessage();
504 assertContainsString(message, "Element allow-user present multiple times with different namespaces");
505 assertContainsString(message, TEST_NAMESPACE);
506 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
511 public void testTypeNameConfigAttributeMatching() throws Exception {
512 edit("netconfMessages/editConfig.xml");
514 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
517 Document response = getConfigRunning();
518 checkTypeConfigAttribute(response);
521 // TODO add <modules operation="replace"> functionality
522 @Test(expected = NetconfDocumentedException.class)
523 public void testConfigNetconfReplaceModuleEx() throws Exception {
525 createModule(INSTANCE_NAME);
527 edit("netconfMessages/editConfig.xml");
528 edit("netconfMessages/editConfig_replace_module_ex.xml");
532 public void testUnrecognisedConfigElements() throws Exception {
534 String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
535 final int TESTS_COUNT = 8;
537 for (int i = 0; i < TESTS_COUNT; i++) {
538 String file = String.format(format, i + 1);
539 LOG.info("Reading {}", file);
542 } catch (NetconfDocumentedException e) {
543 assertContainsString(e.getMessage(), "Unrecognised elements");
544 assertContainsString(e.getMessage(), "unknownAttribute");
547 fail("Unrecognised test should throw exception " + file);
554 public void testConfigNetconfReplaceModule() throws Exception {
556 createModule(INSTANCE_NAME);
558 edit("netconfMessages/editConfig.xml");
560 Document response = getConfigRunning();
561 final int allInstances = response.getElementsByTagName("instance").getLength();
563 edit("netconfMessages/editConfig_replace_module.xml");
566 response = getConfigRunning();
567 final int afterReplace = response.getElementsByTagName("instance").getLength();
569 assertEquals(4 + 4 /* Instances from services */, allInstances);
570 assertEquals(3 + 3, afterReplace);
573 @Test(expected = NetconfDocumentedException.class)
574 public void testEx() throws Exception {
580 public void testEx2() throws Exception {
581 assertContainsElement(discard(), readXmlToElement("<ok xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
584 private Document discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
585 DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
586 return executeOp(discardOp, "netconfMessages/discardChanges.xml");
589 private void checkBinaryLeafEdited(final Document response) throws NodeTestException, SAXException, IOException {
590 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
591 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
594 private void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
596 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
598 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
600 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
602 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
604 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">TWO</extended-enum>"));
606 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ONE</extended-enum>"));
609 private void assertContainsString(String string, String substring) {
610 assertThat(string, CoreMatchers.containsString(substring));
613 private void checkEnum(final Document response) throws Exception {
615 String expectedEnumContent = "TWO";
617 XMLAssert.assertXpathEvaluatesTo(expectedEnumContent,
618 getXpathForNetconfImplSubnode(INSTANCE_NAME,"extended-enum"),
622 private void checkTestingDeps(Document response) {
623 int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
624 assertEquals(2, testingDepsSize);
627 private String getXpathForNetconfImplSubnode(String instanceName, String subnode) {
628 return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply" +
629 "/urn:ietf:params:xml:ns:netconf:base:1.0:data" +
630 "/urn:opendaylight:params:xml:ns:yang:controller:config:modules" +
631 "/module[name='"+instanceName+"']" +
632 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf" +
633 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:"+subnode;
636 private void checkTypeConfigAttribute(Document response) throws Exception {
638 Map<String,String> namesToTypeValues = ImmutableMap.of("instance-from-code", "configAttributeType",
639 "test2", "default-string");
640 for (Entry<String, String> nameToExpectedValue : namesToTypeValues.entrySet()) {
641 XMLAssert.assertXpathEvaluatesTo(nameToExpectedValue.getValue(),
642 getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(),"type"),
647 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
648 final List<InputStream> yangDependencies = getYangs();
650 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
652 YangParserImpl yangParser = new YangParserImpl();
653 final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(yangDependencies).values()));
654 YangStoreService yangStoreService = new YangStoreService(new SchemaContextProvider() {
656 public SchemaContext getSchemaContext() {
657 return schemaContext ;
660 mBeanEntries.putAll(yangStoreService.getModuleMXBeanEntryMap());
665 private Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() throws Exception {
666 SchemaContext resolveSchemaContext = getSchemaContext();
667 return resolveSchemaContext.getModules();
670 private SchemaContext getSchemaContext() throws Exception {
671 final List<InputStream> yangDependencies = getYangs();
672 YangParserImpl parser = new YangParserImpl();
674 Set<Module> allYangModules = parser.parseYangModelsFromStreams(yangDependencies);
676 return parser.resolveSchemaContext(Sets
677 .newHashSet(allYangModules));
681 public void testConfigNetconfRuntime() throws Exception {
683 createModule(INSTANCE_NAME);
685 edit("netconfMessages/editConfig.xml");
686 checkBinaryLeafEdited(getConfigCandidate());
690 Document response = get();
692 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
694 assertEquals(2, getElementsSize(response, "asdf"));
695 // data from running config
696 assertEquals(2, getElementsSize(response, "simple-short"));
698 assertEquals(8, getElementsSize(response, "inner-running-data"));
699 assertEquals(8, getElementsSize(response, "deep2"));
700 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
701 assertEquals(8 * 4, getElementsSize(response, "deep3"));
702 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
703 assertEquals(8, getElementsSize(response, "inner-running-data-additional", "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
704 assertEquals(8, getElementsSize(response, "deep4"));
707 RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
709 response = executeOp(netconf, "netconfMessages/rpc.xml");
710 assertContainsElementWithText(response, "testarg1");
712 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
713 Document expectedReplyOk = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
714 XMLUnit.setIgnoreWhitespace(true);
715 XMLAssert.assertXMLEqual(expectedReplyOk, response);
717 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
718 assertContainsElementWithText(response, "true");
720 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
721 assertContainsElementWithText(response, "1");
722 assertContainsElementWithText(response, "2");
725 private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
726 Get getOp = new Get(transactionProvider, yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
727 return executeOp(getOp, "netconfMessages/get.xml");
730 private int getElementsSize(Document response, String elementName) {
731 return response.getElementsByTagName(elementName).getLength();
734 private int getElementsSize(Document response, String elementName, String namespace) {
735 return response.getElementsByTagNameNS(namespace, elementName).getLength();
738 private Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
739 SAXException, IOException, NetconfDocumentedException {
741 final Document request = XmlFileLoader.xmlFileToDocument(filename);
743 LOG.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
744 HandlingPriority priority = op.canHandle(request);
746 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
748 final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
749 LOG.debug("Got response\n{}", XmlUtil.toString(response));
753 private List<InputStream> getYangs() throws FileNotFoundException {
754 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
755 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
756 "/META-INF/yang/test-groups.yang", "/META-INF/yang/ietf-inet-types.yang");
757 final Collection<InputStream> yangDependencies = new ArrayList<>();
758 for (String path : paths) {
759 final InputStream is = Preconditions
760 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
761 yangDependencies.add(is);
763 return Lists.newArrayList(yangDependencies);
766 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, String depName)
767 throws InstanceAlreadyExistsException, InstanceNotFoundException {
768 mxBean.setSimpleInt((long) 44);
769 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
770 final DtoD dtob = getDtoD();
771 mxBean.setDtoD(dtob);
773 final DtoC dtoa = getDtoC();
774 mxBean.setDtoC(dtoa);
775 mxBean.setSimpleBoolean(false);
777 final Peers p1 = new Peers();
780 p1.setSimpleInt3(456);
781 final Peers p2 = new Peers();
783 p2.setPort("port23");
784 p2.setSimpleInt3(456);
785 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
787 mxBean.setSimpleLong(454545L);
788 mxBean.setSimpleLong2(44L);
789 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
790 mxBean.setSimpleByte(new Byte((byte) 4));
791 mxBean.setSimpleShort(new Short((short) 4));
792 mxBean.setSimpleTest(545);
794 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
795 mxBean.setSimpleList(Lists.<Integer> newArrayList());
797 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
799 for (Class<? extends AbstractServiceInterface> sInterface : factory2.getImplementedServiceIntefaces()) {
800 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
801 transaction.saveServiceReference(
802 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + depName + "_" + i++,
806 mxBean.setTestingDep(testingDepOn);
809 private static DtoD getDtoD() {
810 final DtoD dtob = new DtoD();
811 dtob.setSimpleInt1((long) 444);
812 dtob.setSimpleInt2((long) 4444);
813 dtob.setSimpleInt3(454);
814 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
815 final Deep deep = new Deep();
816 deep.setSimpleInt3(4);
817 dtobInner.setDeep(deep);
818 dtobInner.setSimpleInt3(44);
819 dtobInner.setSimpleList(Lists.newArrayList(4));
820 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
821 dtob.setSimpleList(Lists.newArrayList(4));
825 private static DtoC getDtoC() {
826 final DtoC dtoa = new DtoC();
827 // dtoa.setSimpleArg((long) 55);
828 final DtoAInner dtoAInner = new DtoAInner();
829 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
830 dtoAInnerInner.setSimpleArg(456L);
831 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
832 dtoAInner.setSimpleArg(44L);
833 dtoa.setDtoAInner(dtoAInner);