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 java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.math.BigInteger;
29 import java.net.URISyntaxException;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashSet;
35 import java.util.List;
39 import javax.management.InstanceAlreadyExistsException;
40 import javax.management.InstanceNotFoundException;
41 import javax.management.ObjectName;
42 import javax.xml.parsers.ParserConfigurationException;
44 import org.custommonkey.xmlunit.AbstractNodeTester;
45 import org.custommonkey.xmlunit.NodeTest;
46 import org.custommonkey.xmlunit.NodeTestException;
47 import org.custommonkey.xmlunit.NodeTester;
48 import org.custommonkey.xmlunit.XMLAssert;
49 import org.custommonkey.xmlunit.XMLUnit;
50 import org.junit.Before;
51 import org.junit.Ignore;
52 import org.junit.Test;
53 import org.junit.matchers.JUnitMatchers;
54 import org.mockito.Mock;
55 import org.mockito.MockitoAnnotations;
56 import org.opendaylight.controller.config.api.ConflictingVersionException;
57 import org.opendaylight.controller.config.api.ValidationException;
58 import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
59 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
60 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
61 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
62 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
63 import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
64 import org.opendaylight.controller.config.yang.test.impl.ComplexList;
65 import org.opendaylight.controller.config.yang.test.impl.Deep;
66 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
67 import org.opendaylight.controller.config.yang.test.impl.DtoAInner;
68 import org.opendaylight.controller.config.yang.test.impl.DtoAInnerInner;
69 import org.opendaylight.controller.config.yang.test.impl.DtoC;
70 import org.opendaylight.controller.config.yang.test.impl.DtoD;
71 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
72 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
73 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
74 import org.opendaylight.controller.config.yang.test.impl.Peers;
75 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
76 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
77 import org.opendaylight.controller.netconf.api.NetconfOperationRouter;
78 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
79 import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
80 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
81 import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
82 import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
83 import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
84 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreServiceImpl;
85 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
86 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
87 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
88 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
89 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
90 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
91 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
92 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
93 import org.opendaylight.controller.netconf.util.xml.XmlElement;
94 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
95 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
98 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
99 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
100 import org.opendaylight.yangtools.yang.model.api.Module;
101 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
102 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
103 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
104 import org.slf4j.Logger;
105 import org.slf4j.LoggerFactory;
106 import org.w3c.dom.Document;
107 import org.w3c.dom.Element;
108 import org.w3c.dom.Node;
109 import org.w3c.dom.NodeList;
110 import org.w3c.dom.Text;
111 import org.w3c.dom.traversal.DocumentTraversal;
112 import org.xml.sax.SAXException;
114 import com.google.common.base.Optional;
115 import com.google.common.base.Preconditions;
116 import com.google.common.collect.Lists;
117 import com.google.common.collect.Maps;
118 import com.google.common.collect.Sets;
121 public class NetconfMappingTest extends AbstractConfigTest {
122 private static final Logger logger = LoggerFactory.getLogger(NetconfMappingTest.class);
124 private static final String INSTANCE_NAME = "instance-from-code";
125 private static final String NETCONF_SESSION_ID = "foo";
126 private static final String TEST_NAMESPACE= "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
127 private NetconfTestImplModuleFactory factory;
128 private DepTestImplModuleFactory factory2;
129 private IdentityTestModuleFactory factory3;
132 YangStoreSnapshot yangStoreSnapshot;
134 NetconfOperationRouter netconfOperationRouter;
136 NetconfOperationServiceSnapshotImpl netconfOperationServiceSnapshot;
138 private TransactionProvider transactionProvider;
141 public void setUp() throws Exception {
142 MockitoAnnotations.initMocks(this);
143 doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
144 doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
145 doNothing().when(netconfOperationServiceSnapshot).close();
147 this.factory = new NetconfTestImplModuleFactory();
148 this.factory2 = new DepTestImplModuleFactory();
149 this.factory3 = new IdentityTestModuleFactory();
150 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(this.factory, this.factory2,
153 transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
156 private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException, InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
157 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
159 final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
160 final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
161 setModule(mxBean, transaction, instanceName + "_dep");
164 for (Class<? extends AbstractServiceInterface> sInterface : factory.getImplementedServiceIntefaces()) {
165 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
166 transaction.saveServiceReference(
167 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + instanceName + "_" + i++,
171 transaction.commit();
176 public void testIdentityRefs() throws Exception {
177 edit("netconfMessages/editConfig_identities.xml");
184 protected CodecRegistry getCodecRegistry() {
185 IdentityCodec<?> idCodec = mock(IdentityCodec.class);
186 doReturn(TestIdentity1.class).when(idCodec).deserialize(TestIdentity1.QNAME);
187 doReturn(TestIdentity2.class).when(idCodec).deserialize(TestIdentity2.QNAME);
189 CodecRegistry codecReg = super.getCodecRegistry();
190 doReturn(idCodec).when(codecReg).getIdentityCodec();
195 public void testServicePersistance() throws Exception {
196 createModule(INSTANCE_NAME);
198 edit("netconfMessages/editConfig.xml");
199 Document config = getConfigCandidate();
200 assertCorrectServiceNames(config, Sets.newHashSet("ref_test2", "user_to_instance_from_code", "ref_dep_user",
201 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
202 "ref_from_code_to_instance-from-code_1"));
205 edit("netconfMessages/editConfig_addServiceName.xml");
206 config = getConfigCandidate();
207 assertCorrectServiceNames(config, Sets.newHashSet("ref_test2", "user_to_instance_from_code", "ref_dep_user",
208 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
209 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
211 edit("netconfMessages/editConfig_addServiceNameOnTest.xml");
212 config = getConfigCandidate();
213 assertCorrectServiceNames(config, Sets.newHashSet("ref_test2", "user_to_instance_from_code", "ref_dep_user",
214 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
215 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
218 config = getConfigRunning();
219 assertCorrectRefNamesForDependencies(config);
220 assertCorrectServiceNames(config, Sets.newHashSet("ref_test2", "user_to_instance_from_code", "ref_dep_user",
221 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
222 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
224 edit("netconfMessages/editConfig_replace_default.xml");
225 config = getConfigCandidate();
226 assertCorrectServiceNames(config, Sets.newHashSet("ref_dep", "ref_dep2"));
228 edit("netconfMessages/editConfig_remove.xml");
229 config = getConfigCandidate();
230 assertCorrectServiceNames(config, Collections.<String>emptySet());
233 config = getConfigCandidate();
234 assertCorrectServiceNames(config, Collections.<String>emptySet());
238 private void assertCorrectRefNamesForDependencies(Document config) throws NodeTestException {
239 NodeList modulesList = config.getElementsByTagName("modules");
240 assertEquals(1, modulesList.getLength());
242 NodeTest nt = new NodeTest((DocumentTraversal) config, modulesList.item(0));
243 NodeTester tester = new AbstractNodeTester() {
244 private int defaultRefNameCount = 0;
245 private int userRefNameCount = 0;
248 public void testText(Text text) throws NodeTestException {
249 if(text.getData().equals("ref_dep2")) {
250 defaultRefNameCount++;
251 } else if(text.getData().equals("ref_dep_user_two")) {
257 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
258 assertEquals(0, defaultRefNameCount);
259 assertEquals(2, userRefNameCount);
262 nt.performTest(tester, Node.TEXT_NODE);
265 private void assertCorrectServiceNames(Document configCandidate, final Set<String> refNames) throws NodeTestException {
267 NodeList servicesNodes = configCandidate.getElementsByTagName("services");
268 assertEquals(1, servicesNodes.getLength());
270 NodeTest nt = new NodeTest((DocumentTraversal) configCandidate, servicesNodes.item(0));
271 NodeTester tester = new AbstractNodeTester() {
274 public void testElement(Element element) throws NodeTestException {
275 if(element.getNodeName() != null) {
276 if(element.getNodeName().equals("name")) {
277 String elmText = element.getTextContent();
278 if(refNames.contains(elmText)) {
279 refNames.remove(elmText);
282 throw new NodeTestException("Unexpected services defined: " + elmText);
289 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
290 assertTrue(refNames.isEmpty());
293 nt.performTest(tester, Node.ELEMENT_NODE);
297 public void testConfigNetconfUnionTypes() throws Exception {
299 createModule(INSTANCE_NAME);
301 edit("netconfMessages/editConfig.xml");
303 Document response = getConfigRunning();
304 Element ipElement = readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
305 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
307 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
310 edit("netconfMessages/editConfig_setUnions.xml");
312 response = getConfigRunning();
313 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
314 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">randomStringForUnion</union-test-attr>"));
319 public void testConfigNetconf() throws Exception {
321 createModule(INSTANCE_NAME);
323 edit("netconfMessages/editConfig.xml");
324 Document configCandidate = getConfigCandidate();
325 checkBinaryLeafEdited(configCandidate);
328 // default-operation:none, should not affect binary leaf
329 edit("netconfMessages/editConfig_none.xml");
330 checkBinaryLeafEdited(getConfigCandidate());
334 Document response = getConfigRunning();
336 checkBinaryLeafEdited(response);
337 checkTypeConfigAttribute(response);
338 checkTypedefs(response);
339 checkTestingDeps(response);
341 checkBigDecimal(response);
343 edit("netconfMessages/editConfig_remove.xml");
346 assertXMLEqual(getConfigCandidate(), getConfigRunning());
348 final Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
349 XMLUnit.setIgnoreWhitespace(true);
350 assertXMLEqual(expectedResult, getConfigRunning());
351 assertXMLEqual(expectedResult, getConfigCandidate());
353 edit("netconfMessages/editConfig_none.xml");
355 verify(netconfOperationServiceSnapshot).close();
356 verifyNoMoreInteractions(netconfOperationRouter);
357 verifyNoMoreInteractions(netconfOperationServiceSnapshot);
360 private void checkBigDecimal(Document response) throws NodeTestException, SAXException, IOException {
361 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
363 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
367 private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
369 DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, netconfOperationServiceSnapshot);
370 executeOp(closeOp, "netconfMessages/closeSession.xml");
373 private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
374 NetconfDocumentedException {
375 EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
377 executeOp(editOp, resource);
380 private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
381 Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
382 executeOp(commitOp, "netconfMessages/commit.xml");
385 private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
386 NetconfDocumentedException {
387 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
388 configRegistryClient, NETCONF_SESSION_ID);
389 return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
392 private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
393 NetconfDocumentedException {
394 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
395 configRegistryClient, NETCONF_SESSION_ID);
396 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
399 @Ignore("second edit message corrupted")
400 @Test(expected = NetconfDocumentedException.class)
401 public void testConfigNetconfReplaceDefaultEx() throws Exception {
403 createModule(INSTANCE_NAME);
405 edit("netconfMessages/editConfig.xml");
406 edit("netconfMessages/editConfig_replace_default_ex.xml");
410 public void testConfigNetconfReplaceDefault() throws Exception {
412 createModule(INSTANCE_NAME);
414 edit("netconfMessages/editConfig.xml");
416 Document response = getConfigRunning();
417 final int allInstances = response.getElementsByTagName("module").getLength();
419 edit("netconfMessages/editConfig_replace_default.xml");
422 response = getConfigRunning();
424 final int afterReplace = response.getElementsByTagName("module").getLength();
425 assertEquals(4, allInstances);
426 assertEquals(2, afterReplace);
429 @Test(expected = NetconfDocumentedException.class)
430 public void testSameAttrDifferentNamespaces() throws Exception {
432 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
433 } catch (NetconfDocumentedException e) {
434 String message = e.getMessage();
435 assertContainsString(message, "Element simple-long-2 present multiple times with different namespaces");
436 assertContainsString(message, TEST_NAMESPACE);
437 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
442 @Test(expected = NetconfDocumentedException.class)
443 public void testDifferentNamespaceInTO() throws Exception {
445 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
446 } catch (NetconfDocumentedException e) {
447 String message = e.getMessage();
448 assertContainsString(message, "Unrecognised elements");
449 assertContainsString(message, "simple-int2");
450 assertContainsString(message, "dto_d");
455 @Test(expected = NetconfDocumentedException.class)
456 public void testSameAttrDifferentNamespacesList() throws Exception {
458 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
459 } catch (NetconfDocumentedException e) {
460 String message = e.getMessage();
461 assertContainsString(message, "Element binaryLeaf present multiple times with different namespaces");
462 assertContainsString(message, TEST_NAMESPACE);
463 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
469 public void testTypeNameConfigAttributeMatching() throws Exception {
470 edit("netconfMessages/editConfig.xml");
472 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
475 Document response = getConfigRunning();
476 checkTypeConfigAttribute(response);
479 // TODO add <modules operation="replace"> functionality
480 @Test(expected = NetconfDocumentedException.class)
481 public void testConfigNetconfReplaceModuleEx() throws Exception {
483 createModule(INSTANCE_NAME);
485 edit("netconfMessages/editConfig.xml");
486 edit("netconfMessages/editConfig_replace_module_ex.xml");
490 public void testUnrecognisedConfigElements() throws Exception {
492 String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
493 final int TESTS_COUNT = 8;
495 for (int i = 0; i < TESTS_COUNT; i++) {
496 String file = String.format(format, i + 1);
499 } catch (NetconfDocumentedException e) {
500 assertContainsString(e.getMessage(), "Unrecognised elements");
501 assertContainsString(e.getMessage(), "unknownAttribute");
504 fail("Unrecognised test should throw exception " + file);
511 public void testConfigNetconfReplaceModule() throws Exception {
513 createModule(INSTANCE_NAME);
515 edit("netconfMessages/editConfig.xml");
517 Document response = getConfigRunning();
518 final int allInstances = response.getElementsByTagName("instance").getLength();
520 edit("netconfMessages/editConfig_replace_module.xml");
523 response = getConfigRunning();
524 final int afterReplace = response.getElementsByTagName("instance").getLength();
526 assertEquals(4 + 4 /* Instances from services */, allInstances);
527 assertEquals(3 + 3, afterReplace);
530 @Test(expected = NetconfDocumentedException.class)
531 public void testEx() throws Exception {
536 @Test(expected = NetconfDocumentedException.class)
537 public void testEx2() throws Exception {
541 private void discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
542 DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
543 executeOp(discardOp, "netconfMessages/discardChanges.xml");
546 private void checkBinaryLeafEdited(final Document response) throws NodeTestException, SAXException, IOException {
547 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
548 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
551 private void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
553 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
555 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
557 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
559 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
561 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">TWO</extended-enum>"));
563 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ONE</extended-enum>"));
566 private void assertContainsString(String string, String substring) {
567 assertThat(string, JUnitMatchers.containsString(substring));
570 private void checkEnum(final Document response) {
571 XmlElement modulesElement = XmlElement.fromDomElement(response.getDocumentElement()).getOnlyChildElement("data")
572 .getOnlyChildElement("modules");
574 String enumName = "extended-enum";
575 String enumContent = "TWO";
577 for (XmlElement moduleElement : modulesElement.getChildElements("module")) {
578 String name = moduleElement.getOnlyChildElement("prefix:name").getTextContent();
579 if(name.equals(INSTANCE_NAME)) {
580 XmlElement enumAttr = moduleElement.getOnlyChildElement(enumName);
581 assertEquals(enumContent, enumAttr.getTextContent());
586 fail("Enum attribute " + enumName + ":" + enumContent + " not present in " + XmlUtil.toString(response));
589 private void checkTestingDeps(Document response) {
590 int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
591 assertEquals(2, testingDepsSize);
594 private void checkTypeConfigAttribute(Document response) {
596 XmlElement modulesElement = XmlElement.fromDomElement(response.getDocumentElement()).getOnlyChildElement("data")
597 .getOnlyChildElement("modules");
599 List<String> expectedValues = Lists.newArrayList("default-string", "configAttributeType");
600 Set<String> configAttributeType = Sets.newHashSet();
602 for (XmlElement moduleElement : modulesElement.getChildElements("module")) {
603 for (XmlElement type : moduleElement.getChildElements("type")) {
604 if (type.getNamespace() != null) {
605 configAttributeType.add(type.getTextContent());
610 for (String expectedValue : expectedValues) {
611 assertTrue(configAttributeType.contains(expectedValue));
615 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
616 final List<InputStream> yangDependencies = getYangs();
618 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
620 YangParserImpl yangParser = new YangParserImpl();
621 final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(yangDependencies).values()));
622 YangStoreServiceImpl yangStoreService = new YangStoreServiceImpl(new SchemaContextProvider() {
624 public SchemaContext getSchemaContext() {
625 return schemaContext ;
628 mBeanEntries.putAll(yangStoreService.getYangStoreSnapshot().getModuleMXBeanEntryMap());
633 private Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() throws Exception {
634 SchemaContext resolveSchemaContext = getSchemaContext();
635 return resolveSchemaContext.getModules();
638 private SchemaContext getSchemaContext() throws Exception {
639 final List<InputStream> yangDependencies = getYangs();
640 YangParserImpl parser = new YangParserImpl();
642 Set<Module> allYangModules = parser.parseYangModelsFromStreams(yangDependencies);
644 return parser.resolveSchemaContext(Sets
645 .newHashSet(allYangModules));
649 public void testConfigNetconfRuntime() throws Exception {
651 createModule(INSTANCE_NAME);
653 edit("netconfMessages/editConfig.xml");
654 checkBinaryLeafEdited(getConfigCandidate());
658 Document response = get();
660 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
662 assertEquals(2, getElementsSize(response, "asdf"));
663 // data from running config
664 assertEquals(2, getElementsSize(response, "simple-short"));
666 assertEquals(8, getElementsSize(response, "inner-running-data"));
667 assertEquals(8, getElementsSize(response, "deep2"));
668 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
669 assertEquals(8 * 4, getElementsSize(response, "deep3"));
670 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
671 assertEquals(8, getElementsSize(response, "inner-running-data-additional"));
672 assertEquals(8, getElementsSize(response, "deep4"));
675 RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
677 response = executeOp(netconf, "netconfMessages/rpc.xml");
678 assertContainsElementWithText(response, "testarg1");
680 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
681 Document expectedReplyOk = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
682 XMLUnit.setIgnoreWhitespace(true);
683 XMLAssert.assertXMLEqual(expectedReplyOk, response);
685 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
686 assertContainsElementWithText(response, "true");
688 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
689 assertContainsElementWithText(response, "1");
690 assertContainsElementWithText(response, "2");
693 private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
694 Get getOp = new Get(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID, transactionProvider);
695 return executeOp(getOp, "netconfMessages/get.xml");
698 private int getElementsSize(Document response, String elementName) {
699 return response.getElementsByTagName(elementName).getLength();
702 private Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
703 SAXException, IOException, NetconfDocumentedException {
705 final Document request = XmlFileLoader.xmlFileToDocument(filename);
707 logger.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
708 HandlingPriority priority = op.canHandle(request);
710 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
712 final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
713 logger.debug("Got response\n{}", XmlUtil.toString(response));
717 private List<InputStream> getYangs() throws FileNotFoundException {
718 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
719 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
720 "/META-INF/yang/ietf-inet-types.yang");
721 final Collection<InputStream> yangDependencies = new ArrayList<>();
722 for (String path : paths) {
723 final InputStream is = Preconditions
724 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
725 yangDependencies.add(is);
727 return Lists.newArrayList(yangDependencies);
730 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, String depName)
731 throws InstanceAlreadyExistsException, InstanceNotFoundException {
732 mxBean.setSimpleInt((long) 44);
733 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
734 final DtoD dtob = getDtoD();
735 mxBean.setDtoD(dtob);
737 final DtoC dtoa = getDtoC();
738 mxBean.setDtoC(dtoa);
739 mxBean.setSimpleBoolean(false);
741 final Peers p1 = new Peers();
744 p1.setSimpleInt3(456);
745 final Peers p2 = new Peers();
747 p2.setPort("port23");
748 p2.setSimpleInt3(456);
749 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
751 mxBean.setSimpleLong(454545L);
752 mxBean.setSimpleLong2(44L);
753 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
754 mxBean.setSimpleByte(new Byte((byte) 4));
755 mxBean.setSimpleShort(new Short((short) 4));
756 mxBean.setSimpleTest(545);
758 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
759 mxBean.setSimpleList(Lists.<Integer> newArrayList());
761 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
763 for (Class<? extends AbstractServiceInterface> sInterface : factory2.getImplementedServiceIntefaces()) {
764 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
765 transaction.saveServiceReference(
766 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + depName + "_" + i++,
770 mxBean.setTestingDep(testingDepOn);
773 private static DtoD getDtoD() {
774 final DtoD dtob = new DtoD();
775 dtob.setSimpleInt1((long) 444);
776 dtob.setSimpleInt2((long) 4444);
777 dtob.setSimpleInt3(454);
778 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
779 final Deep deep = new Deep();
780 deep.setSimpleInt3(4);
781 dtobInner.setDeep(deep);
782 dtobInner.setSimpleInt3(44);
783 dtobInner.setSimpleList(Lists.newArrayList(4));
784 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
785 dtob.setSimpleList(Lists.newArrayList(4));
789 private static DtoC getDtoC() {
790 final DtoC dtoa = new DtoC();
791 // dtoa.setSimpleArg((long) 55);
792 final DtoAInner dtoAInner = new DtoAInner();
793 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
794 dtoAInnerInner.setSimpleArg(456L);
795 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
796 dtoAInner.setSimpleArg(44L);
797 dtoa.setDtoAInner(dtoAInner);