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.Mockito.doNothing;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.verify;
20 import static org.mockito.Mockito.verifyNoMoreInteractions;
21 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElement;
22 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
23 import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToElement;
25 import com.google.common.base.Optional;
26 import com.google.common.base.Preconditions;
27 import com.google.common.collect.ImmutableMap;
28 import com.google.common.collect.Lists;
29 import com.google.common.collect.Maps;
30 import com.google.common.collect.Sets;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.math.BigInteger;
35 import java.net.URISyntaxException;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.HashSet;
41 import java.util.List;
43 import java.util.Map.Entry;
45 import javax.management.InstanceAlreadyExistsException;
46 import javax.management.InstanceNotFoundException;
47 import javax.management.ObjectName;
48 import javax.xml.parsers.ParserConfigurationException;
49 import org.custommonkey.xmlunit.AbstractNodeTester;
50 import org.custommonkey.xmlunit.NodeTest;
51 import org.custommonkey.xmlunit.NodeTestException;
52 import org.custommonkey.xmlunit.NodeTester;
53 import org.custommonkey.xmlunit.XMLAssert;
54 import org.custommonkey.xmlunit.XMLUnit;
55 import org.hamcrest.CoreMatchers;
56 import org.junit.Before;
57 import org.junit.Ignore;
58 import org.junit.Test;
59 import org.mockito.Mock;
60 import org.mockito.MockitoAnnotations;
61 import org.opendaylight.controller.config.api.ConflictingVersionException;
62 import org.opendaylight.controller.config.api.ValidationException;
63 import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
64 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
65 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
66 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
67 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
68 import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
69 import org.opendaylight.controller.config.yang.test.impl.ComplexList;
70 import org.opendaylight.controller.config.yang.test.impl.Deep;
71 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
72 import org.opendaylight.controller.config.yang.test.impl.DtoAInner;
73 import org.opendaylight.controller.config.yang.test.impl.DtoAInnerInner;
74 import org.opendaylight.controller.config.yang.test.impl.DtoC;
75 import org.opendaylight.controller.config.yang.test.impl.DtoD;
76 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
77 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
78 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
79 import org.opendaylight.controller.config.yang.test.impl.Peers;
80 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
81 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
82 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
83 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
84 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
85 import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
86 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Lock;
87 import org.opendaylight.controller.netconf.confignetconfconnector.operations.UnLock;
88 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
89 import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
90 import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
91 import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
92 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreServiceImpl;
93 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
94 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
95 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
96 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
97 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
98 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
99 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
100 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
101 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
102 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
103 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
106 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
107 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
108 import org.opendaylight.yangtools.yang.model.api.Module;
109 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
110 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
111 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
114 import org.w3c.dom.Document;
115 import org.w3c.dom.Element;
116 import org.w3c.dom.Node;
117 import org.w3c.dom.NodeList;
118 import org.w3c.dom.Text;
119 import org.w3c.dom.traversal.DocumentTraversal;
120 import org.xml.sax.SAXException;
123 public class NetconfMappingTest extends AbstractConfigTest {
124 private static final Logger LOG = LoggerFactory.getLogger(NetconfMappingTest.class);
126 private static final String INSTANCE_NAME = "instance-from-code";
127 private static final String NETCONF_SESSION_ID = "foo";
128 private static final String TEST_NAMESPACE= "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
129 private NetconfTestImplModuleFactory factory;
130 private DepTestImplModuleFactory factory2;
131 private IdentityTestModuleFactory factory3;
132 private TestImplModuleFactory factory4;
135 YangStoreSnapshot yangStoreSnapshot;
137 NetconfOperationRouter netconfOperationRouter;
139 NetconfOperationServiceSnapshotImpl netconfOperationServiceSnapshot;
141 private TransactionProvider transactionProvider;
144 public void setUp() throws Exception {
145 MockitoAnnotations.initMocks(this);
146 doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
147 doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
148 doNothing().when(netconfOperationServiceSnapshot).close();
150 this.factory = new NetconfTestImplModuleFactory();
151 this.factory2 = new DepTestImplModuleFactory();
152 this.factory3 = new IdentityTestModuleFactory();
153 factory4 = new TestImplModuleFactory();
154 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory, this.factory2,
155 this.factory3, factory4));
157 transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
160 private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException, InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
161 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
163 final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
164 final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
165 setModule(mxBean, transaction, instanceName + "_dep");
168 for (Class<? extends AbstractServiceInterface> sInterface : factory.getImplementedServiceIntefaces()) {
169 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
170 transaction.saveServiceReference(
171 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + instanceName + "_" + i++,
175 transaction.commit();
180 public void testIdentityRefs() throws Exception {
181 edit("netconfMessages/editConfig_identities.xml");
188 protected CodecRegistry getCodecRegistry() {
189 IdentityCodec<?> idCodec = mock(IdentityCodec.class);
190 doReturn(TestIdentity1.class).when(idCodec).deserialize(TestIdentity1.QNAME);
191 doReturn(TestIdentity2.class).when(idCodec).deserialize(TestIdentity2.QNAME);
193 CodecRegistry codecReg = super.getCodecRegistry();
194 doReturn(idCodec).when(codecReg).getIdentityCodec();
199 public void testServicePersistance() throws Exception {
200 createModule(INSTANCE_NAME);
202 edit("netconfMessages/editConfig.xml");
203 Document config = getConfigCandidate();
204 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
205 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
206 "ref_from_code_to_instance-from-code_1"));
209 edit("netconfMessages/editConfig_addServiceName.xml");
210 config = getConfigCandidate();
211 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
212 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
213 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
215 edit("netconfMessages/editConfig_addServiceNameOnTest.xml");
216 config = getConfigCandidate();
217 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
218 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
219 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
222 config = getConfigRunning();
223 assertCorrectRefNamesForDependencies(config);
224 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
225 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
226 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
228 edit("netconfMessages/editConfig_replace_default.xml");
229 config = getConfigCandidate();
230 assertCorrectServiceNames(config, Collections.<String>emptySet());
232 edit("netconfMessages/editConfig_remove.xml");
233 config = getConfigCandidate();
234 assertCorrectServiceNames(config, Collections.<String>emptySet());
237 config = getConfigCandidate();
238 assertCorrectServiceNames(config, Collections.<String>emptySet());
243 public void testUnLock() throws Exception {
244 assertTrue(NetconfMessageUtil.isOKMessage(lockCandidate()));
245 assertTrue(NetconfMessageUtil.isOKMessage(unlockCandidate()));
248 private void assertCorrectRefNamesForDependencies(Document config) throws NodeTestException {
249 NodeList modulesList = config.getElementsByTagName("modules");
250 assertEquals(1, modulesList.getLength());
252 NodeTest nt = new NodeTest((DocumentTraversal) config, modulesList.item(0));
253 NodeTester tester = new AbstractNodeTester() {
254 private int defaultRefNameCount = 0;
255 private int userRefNameCount = 0;
258 public void testText(Text text) throws NodeTestException {
259 if(text.getData().equals("ref_dep2")) {
260 defaultRefNameCount++;
261 } else if(text.getData().equals("ref_dep_user_two")) {
267 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
268 assertEquals(0, defaultRefNameCount);
269 assertEquals(2, userRefNameCount);
272 nt.performTest(tester, Node.TEXT_NODE);
275 private void assertCorrectServiceNames(Document configCandidate, Set<String> refNames) throws NodeTestException {
276 final Set<String> refNames2 = new HashSet<>(refNames);
277 NodeList servicesNodes = configCandidate.getElementsByTagName("services");
278 assertEquals(1, servicesNodes.getLength());
280 NodeTest nt = new NodeTest((DocumentTraversal) configCandidate, servicesNodes.item(0));
281 NodeTester tester = new AbstractNodeTester() {
284 public void testElement(Element element) throws NodeTestException {
285 if(element.getNodeName() != null) {
286 if(element.getNodeName().equals("name")) {
287 String elmText = element.getTextContent();
288 if(refNames2.contains(elmText)) {
289 refNames2.remove(elmText);
291 throw new NodeTestException("Unexpected services defined: " + elmText);
298 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
299 assertEquals(Collections.<String>emptySet(), refNames2);
300 assertTrue(refNames2.toString(), refNames2.isEmpty());
303 nt.performTest(tester, Node.ELEMENT_NODE);
307 public void testConfigNetconfUnionTypes() throws Exception {
309 createModule(INSTANCE_NAME);
311 edit("netconfMessages/editConfig.xml");
313 Document response = getConfigRunning();
314 Element ipElement = readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
315 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
317 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
320 edit("netconfMessages/editConfig_setUnions.xml");
322 response = getConfigRunning();
323 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
324 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">randomStringForUnion</union-test-attr>"));
329 public void testConfigNetconf() throws Exception {
331 createModule(INSTANCE_NAME);
333 edit("netconfMessages/editConfig.xml");
334 Document configCandidate = getConfigCandidate();
335 checkBinaryLeafEdited(configCandidate);
338 // default-operation:none, should not affect binary leaf
339 edit("netconfMessages/editConfig_none.xml");
340 checkBinaryLeafEdited(getConfigCandidate());
344 Document response = getConfigRunning();
346 checkBinaryLeafEdited(response);
347 checkTypeConfigAttribute(response);
348 checkTypedefs(response);
349 checkTestingDeps(response);
351 checkBigDecimal(response);
353 edit("netconfMessages/editConfig_remove.xml");
356 assertXMLEqual(getConfigCandidate(), getConfigRunning());
358 final Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
359 XMLUnit.setIgnoreWhitespace(true);
360 assertXMLEqual(expectedResult, getConfigRunning());
361 assertXMLEqual(expectedResult, getConfigCandidate());
363 edit("netconfMessages/editConfig_none.xml");
365 verify(netconfOperationServiceSnapshot).close();
366 verifyNoMoreInteractions(netconfOperationRouter);
367 verifyNoMoreInteractions(netconfOperationServiceSnapshot);
370 private void checkBigDecimal(Document response) throws NodeTestException, SAXException, IOException {
371 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
373 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
377 private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
379 DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, netconfOperationServiceSnapshot);
380 executeOp(closeOp, "netconfMessages/closeSession.xml");
383 private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
384 NetconfDocumentedException {
385 EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
387 executeOp(editOp, resource);
390 private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
391 Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
392 executeOp(commitOp, "netconfMessages/commit.xml");
395 private Document lockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
396 Lock commitOp = new Lock(NETCONF_SESSION_ID);
397 return executeOp(commitOp, "netconfMessages/lock.xml");
400 private Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
401 UnLock commitOp = new UnLock(NETCONF_SESSION_ID);
402 return executeOp(commitOp, "netconfMessages/unlock.xml");
405 private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
406 NetconfDocumentedException {
407 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
408 configRegistryClient, NETCONF_SESSION_ID);
409 return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
412 private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
413 NetconfDocumentedException {
414 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
415 configRegistryClient, NETCONF_SESSION_ID);
416 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
419 @Ignore("second edit message corrupted")
420 @Test(expected = NetconfDocumentedException.class)
421 public void testConfigNetconfReplaceDefaultEx() throws Exception {
423 createModule(INSTANCE_NAME);
425 edit("netconfMessages/editConfig.xml");
426 edit("netconfMessages/editConfig_replace_default_ex.xml");
430 public void testConfigNetconfReplaceDefault() throws Exception {
432 createModule(INSTANCE_NAME);
434 edit("netconfMessages/editConfig.xml");
436 Document response = getConfigRunning();
437 final int allInstances = response.getElementsByTagName("module").getLength();
439 edit("netconfMessages/editConfig_replace_default.xml");
442 response = getConfigRunning();
444 final int afterReplace = response.getElementsByTagName("module").getLength();
445 assertEquals(4, allInstances);
446 assertEquals(2, afterReplace);
450 public void testSameAttrDifferentNamespaces() throws Exception {
452 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
454 } catch (NetconfDocumentedException e) {
455 String message = e.getMessage();
456 assertContainsString(message, "Element simpleInt present multiple times with different namespaces");
457 assertContainsString(message, TEST_NAMESPACE);
458 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
463 public void testDifferentNamespaceInTO() throws Exception {
465 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
467 } catch (NetconfDocumentedException e) {
468 String message = e.getMessage();
469 assertContainsString(message, "Unrecognised elements");
470 assertContainsString(message, "simple-int2");
471 assertContainsString(message, "dto_d");
476 public void testSameAttrDifferentNamespacesList() throws Exception {
478 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
480 } catch (NetconfDocumentedException e) {
481 String message = e.getMessage();
482 assertContainsString(message, "Element allow-user present multiple times with different namespaces");
483 assertContainsString(message, TEST_NAMESPACE);
484 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
489 public void testTypeNameConfigAttributeMatching() throws Exception {
490 edit("netconfMessages/editConfig.xml");
492 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
495 Document response = getConfigRunning();
496 checkTypeConfigAttribute(response);
499 // TODO add <modules operation="replace"> functionality
500 @Test(expected = NetconfDocumentedException.class)
501 public void testConfigNetconfReplaceModuleEx() throws Exception {
503 createModule(INSTANCE_NAME);
505 edit("netconfMessages/editConfig.xml");
506 edit("netconfMessages/editConfig_replace_module_ex.xml");
510 public void testUnrecognisedConfigElements() throws Exception {
512 String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
513 final int TESTS_COUNT = 8;
515 for (int i = 0; i < TESTS_COUNT; i++) {
516 String file = String.format(format, i + 1);
517 LOG.info("Reading {}", file);
520 } catch (NetconfDocumentedException e) {
521 assertContainsString(e.getMessage(), "Unrecognised elements");
522 assertContainsString(e.getMessage(), "unknownAttribute");
525 fail("Unrecognised test should throw exception " + file);
532 public void testConfigNetconfReplaceModule() throws Exception {
534 createModule(INSTANCE_NAME);
536 edit("netconfMessages/editConfig.xml");
538 Document response = getConfigRunning();
539 final int allInstances = response.getElementsByTagName("instance").getLength();
541 edit("netconfMessages/editConfig_replace_module.xml");
544 response = getConfigRunning();
545 final int afterReplace = response.getElementsByTagName("instance").getLength();
547 assertEquals(4 + 4 /* Instances from services */, allInstances);
548 assertEquals(3 + 3, afterReplace);
551 @Test(expected = NetconfDocumentedException.class)
552 public void testEx() throws Exception {
557 @Test(expected = NetconfDocumentedException.class)
558 public void testEx2() throws Exception {
562 private void discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
563 DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
564 executeOp(discardOp, "netconfMessages/discardChanges.xml");
567 private void checkBinaryLeafEdited(final Document response) throws NodeTestException, SAXException, IOException {
568 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
569 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
572 private void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
574 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
576 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
578 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
580 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
582 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">TWO</extended-enum>"));
584 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ONE</extended-enum>"));
587 private void assertContainsString(String string, String substring) {
588 assertThat(string, CoreMatchers.containsString(substring));
591 private void checkEnum(final Document response) throws Exception {
593 String expectedEnumContent = "TWO";
595 XMLAssert.assertXpathEvaluatesTo(expectedEnumContent,
596 getXpathForNetconfImplSubnode(INSTANCE_NAME,"extended-enum"),
600 private void checkTestingDeps(Document response) {
601 int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
602 assertEquals(2, testingDepsSize);
605 private String getXpathForNetconfImplSubnode(String instanceName, String subnode) {
606 return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply" +
607 "/urn:ietf:params:xml:ns:netconf:base:1.0:data" +
608 "/urn:opendaylight:params:xml:ns:yang:controller:config:modules" +
609 "/module[name='"+instanceName+"']" +
610 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf" +
611 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:"+subnode;
614 private void checkTypeConfigAttribute(Document response) throws Exception {
616 Map<String,String> namesToTypeValues = ImmutableMap.of("instance-from-code", "configAttributeType",
617 "test2", "default-string");
618 for (Entry<String, String> nameToExpectedValue : namesToTypeValues.entrySet()) {
619 XMLAssert.assertXpathEvaluatesTo(nameToExpectedValue.getValue(),
620 getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(),"type"),
625 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
626 final List<InputStream> yangDependencies = getYangs();
628 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
630 YangParserImpl yangParser = new YangParserImpl();
631 final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(yangDependencies).values()));
632 YangStoreServiceImpl yangStoreService = new YangStoreServiceImpl(new SchemaContextProvider() {
634 public SchemaContext getSchemaContext() {
635 return schemaContext ;
638 mBeanEntries.putAll(yangStoreService.getYangStoreSnapshot().getModuleMXBeanEntryMap());
643 private Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() throws Exception {
644 SchemaContext resolveSchemaContext = getSchemaContext();
645 return resolveSchemaContext.getModules();
648 private SchemaContext getSchemaContext() throws Exception {
649 final List<InputStream> yangDependencies = getYangs();
650 YangParserImpl parser = new YangParserImpl();
652 Set<Module> allYangModules = parser.parseYangModelsFromStreams(yangDependencies);
654 return parser.resolveSchemaContext(Sets
655 .newHashSet(allYangModules));
659 public void testConfigNetconfRuntime() throws Exception {
661 createModule(INSTANCE_NAME);
663 edit("netconfMessages/editConfig.xml");
664 checkBinaryLeafEdited(getConfigCandidate());
668 Document response = get();
670 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
672 assertEquals(2, getElementsSize(response, "asdf"));
673 // data from running config
674 assertEquals(2, getElementsSize(response, "simple-short"));
676 assertEquals(8, getElementsSize(response, "inner-running-data"));
677 assertEquals(8, getElementsSize(response, "deep2"));
678 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
679 assertEquals(8 * 4, getElementsSize(response, "deep3"));
680 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
681 assertEquals(8, getElementsSize(response, "inner-running-data-additional", "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
682 assertEquals(8, getElementsSize(response, "deep4"));
685 RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
687 response = executeOp(netconf, "netconfMessages/rpc.xml");
688 assertContainsElementWithText(response, "testarg1");
690 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
691 Document expectedReplyOk = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
692 XMLUnit.setIgnoreWhitespace(true);
693 XMLAssert.assertXMLEqual(expectedReplyOk, response);
695 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
696 assertContainsElementWithText(response, "true");
698 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
699 assertContainsElementWithText(response, "1");
700 assertContainsElementWithText(response, "2");
703 private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
704 Get getOp = new Get(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
705 return executeOp(getOp, "netconfMessages/get.xml");
708 private int getElementsSize(Document response, String elementName) {
709 return response.getElementsByTagName(elementName).getLength();
712 private int getElementsSize(Document response, String elementName, String namespace) {
713 return response.getElementsByTagNameNS(namespace, elementName).getLength();
716 private Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
717 SAXException, IOException, NetconfDocumentedException {
719 final Document request = XmlFileLoader.xmlFileToDocument(filename);
721 LOG.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
722 HandlingPriority priority = op.canHandle(request);
724 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
726 final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
727 LOG.debug("Got response\n{}", XmlUtil.toString(response));
731 private List<InputStream> getYangs() throws FileNotFoundException {
732 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
733 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
734 "/META-INF/yang/test-groups.yang", "/META-INF/yang/ietf-inet-types.yang");
735 final Collection<InputStream> yangDependencies = new ArrayList<>();
736 for (String path : paths) {
737 final InputStream is = Preconditions
738 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
739 yangDependencies.add(is);
741 return Lists.newArrayList(yangDependencies);
744 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, String depName)
745 throws InstanceAlreadyExistsException, InstanceNotFoundException {
746 mxBean.setSimpleInt((long) 44);
747 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
748 final DtoD dtob = getDtoD();
749 mxBean.setDtoD(dtob);
751 final DtoC dtoa = getDtoC();
752 mxBean.setDtoC(dtoa);
753 mxBean.setSimpleBoolean(false);
755 final Peers p1 = new Peers();
758 p1.setSimpleInt3(456);
759 final Peers p2 = new Peers();
761 p2.setPort("port23");
762 p2.setSimpleInt3(456);
763 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
765 mxBean.setSimpleLong(454545L);
766 mxBean.setSimpleLong2(44L);
767 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
768 mxBean.setSimpleByte(new Byte((byte) 4));
769 mxBean.setSimpleShort(new Short((short) 4));
770 mxBean.setSimpleTest(545);
772 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
773 mxBean.setSimpleList(Lists.<Integer> newArrayList());
775 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
777 for (Class<? extends AbstractServiceInterface> sInterface : factory2.getImplementedServiceIntefaces()) {
778 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
779 transaction.saveServiceReference(
780 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + depName + "_" + i++,
784 mxBean.setTestingDep(testingDepOn);
787 private static DtoD getDtoD() {
788 final DtoD dtob = new DtoD();
789 dtob.setSimpleInt1((long) 444);
790 dtob.setSimpleInt2((long) 4444);
791 dtob.setSimpleInt3(454);
792 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
793 final Deep deep = new Deep();
794 deep.setSimpleInt3(4);
795 dtobInner.setDeep(deep);
796 dtobInner.setSimpleInt3(44);
797 dtobInner.setSimpleList(Lists.newArrayList(4));
798 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
799 dtob.setSimpleList(Lists.newArrayList(4));
803 private static DtoC getDtoC() {
804 final DtoC dtoa = new DtoC();
805 // dtoa.setSimpleArg((long) 55);
806 final DtoAInner dtoAInner = new DtoAInner();
807 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
808 dtoAInnerInner.setSimpleArg(456L);
809 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
810 dtoAInner.setSimpleArg(44L);
811 dtoa.setDtoAInner(dtoAInner);