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;
32 import java.io.FileNotFoundException;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.math.BigInteger;
36 import java.net.URISyntaxException;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.HashSet;
42 import java.util.List;
44 import java.util.Map.Entry;
47 import javax.management.InstanceAlreadyExistsException;
48 import javax.management.InstanceNotFoundException;
49 import javax.management.ObjectName;
50 import javax.xml.parsers.ParserConfigurationException;
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.editconfig.EditConfig;
90 import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
91 import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
92 import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
93 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreServiceImpl;
94 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
95 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
96 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
97 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
98 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
99 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
100 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
101 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
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 logger = 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());
242 private void assertCorrectRefNamesForDependencies(Document config) throws NodeTestException {
243 NodeList modulesList = config.getElementsByTagName("modules");
244 assertEquals(1, modulesList.getLength());
246 NodeTest nt = new NodeTest((DocumentTraversal) config, modulesList.item(0));
247 NodeTester tester = new AbstractNodeTester() {
248 private int defaultRefNameCount = 0;
249 private int userRefNameCount = 0;
252 public void testText(Text text) throws NodeTestException {
253 if(text.getData().equals("ref_dep2")) {
254 defaultRefNameCount++;
255 } else if(text.getData().equals("ref_dep_user_two")) {
261 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
262 assertEquals(0, defaultRefNameCount);
263 assertEquals(2, userRefNameCount);
266 nt.performTest(tester, Node.TEXT_NODE);
269 private void assertCorrectServiceNames(Document configCandidate, Set<String> refNames) throws NodeTestException {
270 final Set<String> refNames2 = new HashSet<>(refNames);
271 NodeList servicesNodes = configCandidate.getElementsByTagName("services");
272 assertEquals(1, servicesNodes.getLength());
274 NodeTest nt = new NodeTest((DocumentTraversal) configCandidate, servicesNodes.item(0));
275 NodeTester tester = new AbstractNodeTester() {
278 public void testElement(Element element) throws NodeTestException {
279 if(element.getNodeName() != null) {
280 if(element.getNodeName().equals("name")) {
281 String elmText = element.getTextContent();
282 if(refNames2.contains(elmText)) {
283 refNames2.remove(elmText);
285 throw new NodeTestException("Unexpected services defined: " + elmText);
292 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
293 assertEquals(Collections.<String>emptySet(), refNames2);
294 assertTrue(refNames2.toString(), refNames2.isEmpty());
297 nt.performTest(tester, Node.ELEMENT_NODE);
301 public void testConfigNetconfUnionTypes() throws Exception {
303 createModule(INSTANCE_NAME);
305 edit("netconfMessages/editConfig.xml");
307 Document response = getConfigRunning();
308 Element ipElement = readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
309 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
311 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
314 edit("netconfMessages/editConfig_setUnions.xml");
316 response = getConfigRunning();
317 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
318 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">randomStringForUnion</union-test-attr>"));
323 public void testConfigNetconf() throws Exception {
325 createModule(INSTANCE_NAME);
327 edit("netconfMessages/editConfig.xml");
328 Document configCandidate = getConfigCandidate();
329 checkBinaryLeafEdited(configCandidate);
332 // default-operation:none, should not affect binary leaf
333 edit("netconfMessages/editConfig_none.xml");
334 checkBinaryLeafEdited(getConfigCandidate());
338 Document response = getConfigRunning();
340 checkBinaryLeafEdited(response);
341 checkTypeConfigAttribute(response);
342 checkTypedefs(response);
343 checkTestingDeps(response);
345 checkBigDecimal(response);
347 edit("netconfMessages/editConfig_remove.xml");
350 assertXMLEqual(getConfigCandidate(), getConfigRunning());
352 final Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
353 XMLUnit.setIgnoreWhitespace(true);
354 assertXMLEqual(expectedResult, getConfigRunning());
355 assertXMLEqual(expectedResult, getConfigCandidate());
357 edit("netconfMessages/editConfig_none.xml");
359 verify(netconfOperationServiceSnapshot).close();
360 verifyNoMoreInteractions(netconfOperationRouter);
361 verifyNoMoreInteractions(netconfOperationServiceSnapshot);
364 private void checkBigDecimal(Document response) throws NodeTestException, SAXException, IOException {
365 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
367 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
371 private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
373 DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, netconfOperationServiceSnapshot);
374 executeOp(closeOp, "netconfMessages/closeSession.xml");
377 private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
378 NetconfDocumentedException {
379 EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
381 executeOp(editOp, resource);
384 private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
385 Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
386 executeOp(commitOp, "netconfMessages/commit.xml");
389 private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
390 NetconfDocumentedException {
391 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
392 configRegistryClient, NETCONF_SESSION_ID);
393 return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
396 private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
397 NetconfDocumentedException {
398 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
399 configRegistryClient, NETCONF_SESSION_ID);
400 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
403 @Ignore("second edit message corrupted")
404 @Test(expected = NetconfDocumentedException.class)
405 public void testConfigNetconfReplaceDefaultEx() throws Exception {
407 createModule(INSTANCE_NAME);
409 edit("netconfMessages/editConfig.xml");
410 edit("netconfMessages/editConfig_replace_default_ex.xml");
414 public void testConfigNetconfReplaceDefault() throws Exception {
416 createModule(INSTANCE_NAME);
418 edit("netconfMessages/editConfig.xml");
420 Document response = getConfigRunning();
421 final int allInstances = response.getElementsByTagName("module").getLength();
423 edit("netconfMessages/editConfig_replace_default.xml");
426 response = getConfigRunning();
428 final int afterReplace = response.getElementsByTagName("module").getLength();
429 assertEquals(4, allInstances);
430 assertEquals(2, afterReplace);
434 public void testSameAttrDifferentNamespaces() throws Exception {
436 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
438 } catch (NetconfDocumentedException e) {
439 String message = e.getMessage();
440 assertContainsString(message, "Element simpleInt present multiple times with different namespaces");
441 assertContainsString(message, TEST_NAMESPACE);
442 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
447 public void testDifferentNamespaceInTO() throws Exception {
449 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
451 } catch (NetconfDocumentedException e) {
452 String message = e.getMessage();
453 assertContainsString(message, "Unrecognised elements");
454 assertContainsString(message, "simple-int2");
455 assertContainsString(message, "dto_d");
460 public void testSameAttrDifferentNamespacesList() throws Exception {
462 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
464 } catch (NetconfDocumentedException e) {
465 String message = e.getMessage();
466 assertContainsString(message, "Element allow-user present multiple times with different namespaces");
467 assertContainsString(message, TEST_NAMESPACE);
468 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
473 public void testTypeNameConfigAttributeMatching() throws Exception {
474 edit("netconfMessages/editConfig.xml");
476 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
479 Document response = getConfigRunning();
480 checkTypeConfigAttribute(response);
483 // TODO add <modules operation="replace"> functionality
484 @Test(expected = NetconfDocumentedException.class)
485 public void testConfigNetconfReplaceModuleEx() throws Exception {
487 createModule(INSTANCE_NAME);
489 edit("netconfMessages/editConfig.xml");
490 edit("netconfMessages/editConfig_replace_module_ex.xml");
494 public void testUnrecognisedConfigElements() throws Exception {
496 String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
497 final int TESTS_COUNT = 8;
499 for (int i = 0; i < TESTS_COUNT; i++) {
500 String file = String.format(format, i + 1);
501 logger.info("Reading {}", file);
504 } catch (NetconfDocumentedException e) {
505 assertContainsString(e.getMessage(), "Unrecognised elements");
506 assertContainsString(e.getMessage(), "unknownAttribute");
509 fail("Unrecognised test should throw exception " + file);
516 public void testConfigNetconfReplaceModule() throws Exception {
518 createModule(INSTANCE_NAME);
520 edit("netconfMessages/editConfig.xml");
522 Document response = getConfigRunning();
523 final int allInstances = response.getElementsByTagName("instance").getLength();
525 edit("netconfMessages/editConfig_replace_module.xml");
528 response = getConfigRunning();
529 final int afterReplace = response.getElementsByTagName("instance").getLength();
531 assertEquals(4 + 4 /* Instances from services */, allInstances);
532 assertEquals(3 + 3, afterReplace);
535 @Test(expected = NetconfDocumentedException.class)
536 public void testEx() throws Exception {
541 @Test(expected = NetconfDocumentedException.class)
542 public void testEx2() throws Exception {
546 private void discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
547 DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
548 executeOp(discardOp, "netconfMessages/discardChanges.xml");
551 private void checkBinaryLeafEdited(final Document response) throws NodeTestException, SAXException, IOException {
552 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
553 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
556 private void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
558 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
560 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
562 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
564 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
566 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">TWO</extended-enum>"));
568 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ONE</extended-enum>"));
571 private void assertContainsString(String string, String substring) {
572 assertThat(string, CoreMatchers.containsString(substring));
575 private void checkEnum(final Document response) throws Exception {
577 String expectedEnumContent = "TWO";
579 XMLAssert.assertXpathEvaluatesTo(expectedEnumContent,
580 getXpathForNetconfImplSubnode(INSTANCE_NAME,"extended-enum"),
584 private void checkTestingDeps(Document response) {
585 int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
586 assertEquals(2, testingDepsSize);
589 private String getXpathForNetconfImplSubnode(String instanceName, String subnode) {
590 return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply" +
591 "/urn:ietf:params:xml:ns:netconf:base:1.0:data" +
592 "/urn:opendaylight:params:xml:ns:yang:controller:config:modules" +
593 "/module[name='"+instanceName+"']" +
594 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf" +
595 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:"+subnode;
598 private void checkTypeConfigAttribute(Document response) throws Exception {
600 Map<String,String> namesToTypeValues = ImmutableMap.of("instance-from-code", "configAttributeType",
601 "test2", "default-string");
602 for (Entry<String, String> nameToExpectedValue : namesToTypeValues.entrySet()) {
603 XMLAssert.assertXpathEvaluatesTo(nameToExpectedValue.getValue(),
604 getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(),"type"),
609 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
610 final List<InputStream> yangDependencies = getYangs();
612 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
614 YangParserImpl yangParser = new YangParserImpl();
615 final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(yangDependencies).values()));
616 YangStoreServiceImpl yangStoreService = new YangStoreServiceImpl(new SchemaContextProvider() {
618 public SchemaContext getSchemaContext() {
619 return schemaContext ;
622 mBeanEntries.putAll(yangStoreService.getYangStoreSnapshot().getModuleMXBeanEntryMap());
627 private Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() throws Exception {
628 SchemaContext resolveSchemaContext = getSchemaContext();
629 return resolveSchemaContext.getModules();
632 private SchemaContext getSchemaContext() throws Exception {
633 final List<InputStream> yangDependencies = getYangs();
634 YangParserImpl parser = new YangParserImpl();
636 Set<Module> allYangModules = parser.parseYangModelsFromStreams(yangDependencies);
638 return parser.resolveSchemaContext(Sets
639 .newHashSet(allYangModules));
643 public void testConfigNetconfRuntime() throws Exception {
645 createModule(INSTANCE_NAME);
647 edit("netconfMessages/editConfig.xml");
648 checkBinaryLeafEdited(getConfigCandidate());
652 Document response = get();
654 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
656 assertEquals(2, getElementsSize(response, "asdf"));
657 // data from running config
658 assertEquals(2, getElementsSize(response, "simple-short"));
660 assertEquals(8, getElementsSize(response, "inner-running-data"));
661 assertEquals(8, getElementsSize(response, "deep2"));
662 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
663 assertEquals(8 * 4, getElementsSize(response, "deep3"));
664 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
665 assertEquals(8, getElementsSize(response, "inner-running-data-additional", "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
666 assertEquals(8, getElementsSize(response, "deep4"));
669 RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
671 response = executeOp(netconf, "netconfMessages/rpc.xml");
672 assertContainsElementWithText(response, "testarg1");
674 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
675 Document expectedReplyOk = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
676 XMLUnit.setIgnoreWhitespace(true);
677 XMLAssert.assertXMLEqual(expectedReplyOk, response);
679 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
680 assertContainsElementWithText(response, "true");
682 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
683 assertContainsElementWithText(response, "1");
684 assertContainsElementWithText(response, "2");
687 private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
688 Get getOp = new Get(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
689 return executeOp(getOp, "netconfMessages/get.xml");
692 private int getElementsSize(Document response, String elementName) {
693 return response.getElementsByTagName(elementName).getLength();
696 private int getElementsSize(Document response, String elementName, String namespace) {
697 return response.getElementsByTagNameNS(namespace, elementName).getLength();
700 private Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
701 SAXException, IOException, NetconfDocumentedException {
703 final Document request = XmlFileLoader.xmlFileToDocument(filename);
705 logger.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
706 HandlingPriority priority = op.canHandle(request);
708 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
710 final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
711 logger.debug("Got response\n{}", XmlUtil.toString(response));
715 private List<InputStream> getYangs() throws FileNotFoundException {
716 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
717 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
718 "/META-INF/yang/ietf-inet-types.yang");
719 final Collection<InputStream> yangDependencies = new ArrayList<>();
720 for (String path : paths) {
721 final InputStream is = Preconditions
722 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
723 yangDependencies.add(is);
725 return Lists.newArrayList(yangDependencies);
728 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, String depName)
729 throws InstanceAlreadyExistsException, InstanceNotFoundException {
730 mxBean.setSimpleInt((long) 44);
731 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
732 final DtoD dtob = getDtoD();
733 mxBean.setDtoD(dtob);
735 final DtoC dtoa = getDtoC();
736 mxBean.setDtoC(dtoa);
737 mxBean.setSimpleBoolean(false);
739 final Peers p1 = new Peers();
742 p1.setSimpleInt3(456);
743 final Peers p2 = new Peers();
745 p2.setPort("port23");
746 p2.setSimpleInt3(456);
747 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
749 mxBean.setSimpleLong(454545L);
750 mxBean.setSimpleLong2(44L);
751 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
752 mxBean.setSimpleByte(new Byte((byte) 4));
753 mxBean.setSimpleShort(new Short((short) 4));
754 mxBean.setSimpleTest(545);
756 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
757 mxBean.setSimpleList(Lists.<Integer> newArrayList());
759 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
761 for (Class<? extends AbstractServiceInterface> sInterface : factory2.getImplementedServiceIntefaces()) {
762 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
763 transaction.saveServiceReference(
764 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + depName + "_" + i++,
768 mxBean.setTestingDep(testingDepOn);
771 private static DtoD getDtoD() {
772 final DtoD dtob = new DtoD();
773 dtob.setSimpleInt1((long) 444);
774 dtob.setSimpleInt2((long) 4444);
775 dtob.setSimpleInt3(454);
776 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
777 final Deep deep = new Deep();
778 deep.setSimpleInt3(4);
779 dtobInner.setDeep(deep);
780 dtobInner.setSimpleInt3(44);
781 dtobInner.setSimpleList(Lists.newArrayList(4));
782 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
783 dtob.setSimpleList(Lists.newArrayList(4));
787 private static DtoC getDtoC() {
788 final DtoC dtoa = new DtoC();
789 // dtoa.setSimpleArg((long) 55);
790 final DtoAInner dtoAInner = new DtoAInner();
791 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
792 dtoAInnerInner.setSimpleArg(456L);
793 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
794 dtoAInner.setSimpleArg(44L);
795 dtoa.setDtoAInner(dtoAInner);