From: Tony Tkacik Date: Tue, 26 Aug 2014 11:03:53 +0000 (+0000) Subject: Merge "Added feature for sal-mdsal-xsql" X-Git-Tag: release/helium~202 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=42fba0edd6478327be64b03747e0d839d11b3363;hp=30712afec4c80c7f3a49788a8f52d27611605698 Merge "Added feature for sal-mdsal-xsql" --- diff --git a/opendaylight/md-sal/model/model-flow-service/src/main/yang/flow-node-inventory.yang b/opendaylight/md-sal/model/model-flow-service/src/main/yang/flow-node-inventory.yang index 605cb9004a..64c3d9c467 100644 --- a/opendaylight/md-sal/model/model-flow-service/src/main/yang/flow-node-inventory.yang +++ b/opendaylight/md-sal/model/model-flow-service/src/main/yang/flow-node-inventory.yang @@ -122,10 +122,15 @@ module flow-node-inventory { uses meter:meter; } } - - - grouping flow-node { + grouping ip-address-grouping { + leaf ip-address { + description "IP address of a flow capable node."; + type inet:ip-address; + } + } + + grouping flow-node { leaf manufacturer { type string; } @@ -145,6 +150,7 @@ module flow-node-inventory { uses tables; uses group:groups; uses meters; + uses ip-address-grouping; // TODO: ports container supported-match-types { @@ -197,7 +203,16 @@ module flow-node-inventory { } } - + + rpc get-node-ip-address { + input { + uses "inv:node-context-ref"; + } + output { + uses ip-address-grouping; + } + } + grouping flow-node-connector { uses port:flow-capable-port; diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java index f843b23f9b..53f96e44f4 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java @@ -9,15 +9,14 @@ package org.opendaylight.controller.md.sal.binding.impl; import com.google.common.base.Objects; import com.google.common.base.Optional; -import java.util.ArrayList; + import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; + import org.opendaylight.controller.md.sal.binding.api.DataChangeListener; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; @@ -88,7 +87,7 @@ public abstract class AbstractForwardedDataBroker implements Delegator> normalized) { Map, DataObject> newMap = new HashMap<>(); - for (Map.Entry> entry : sortedEntries(normalized)) { + for (Map.Entry> entry : normalized.entrySet()) { try { Optional, DataObject>> potential = getCodec().toBinding(entry); if (potential.isPresent()) { @@ -102,38 +101,6 @@ public abstract class AbstractForwardedDataBroker implements Delegator> MAP_ENTRY_COMPARATOR = new Comparator>() { - @Override - public int compare(final Entry left, final Entry right) { - final Iterator li = left.getKey().getPathArguments().iterator(); - final Iterator ri = right.getKey().getPathArguments().iterator(); - - // Iterate until left is exhausted... - while (li.hasNext()) { - if (!ri.hasNext()) { - // Left is deeper - return 1; - } - - li.next(); - ri.next(); - } - - // Check if right is exhausted - return ri.hasNext() ? -1 : 0; - } - }; - - private static Iterable> sortedEntries(final Map map) { - if (!map.isEmpty()) { - ArrayList> entries = new ArrayList<>(map.entrySet()); - Collections.sort(entries, MAP_ENTRY_COMPARATOR); - return entries; - } else { - return Collections.emptySet(); - } - } - protected Set> toBinding(final InstanceIdentifier path, final Set normalized) { Set> hashSet = new HashSet<>(); diff --git a/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/Get.java b/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/Get.java index fa78fa4bd3..3b3f71b0ed 100644 --- a/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/Get.java +++ b/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/Get.java @@ -7,8 +7,7 @@ */ package org.opendaylight.controller.netconf.monitoring; -import com.google.common.collect.Maps; - +import java.util.Collections; import org.opendaylight.controller.netconf.api.NetconfDocumentedException; import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService; import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; @@ -18,36 +17,26 @@ import org.opendaylight.controller.netconf.monitoring.xml.JaxBSerializer; import org.opendaylight.controller.netconf.monitoring.xml.model.NetconfState; import org.opendaylight.controller.netconf.util.mapping.AbstractNetconfOperation; import org.opendaylight.controller.netconf.util.xml.XmlElement; -import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; -import java.util.Map; - public class Get extends AbstractNetconfOperation { private static final Logger logger = LoggerFactory.getLogger(Get.class); private final NetconfMonitoringService netconfMonitor; - public Get(NetconfMonitoringService netconfMonitor) { + public Get(final NetconfMonitoringService netconfMonitor) { super(MonitoringConstants.MODULE_NAME); this.netconfMonitor = netconfMonitor; } - private Element getPlaceholder(Document innerResult) throws NetconfDocumentedException { - try { - XmlElement rootElement = null; - rootElement = XmlElement.fromDomElementWithExpected(innerResult.getDocumentElement(), - XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.RFC4741_TARGET_NAMESPACE); - return rootElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY).getDomElement(); - } catch (RuntimeException e) { - throw new IllegalArgumentException(String.format( - "Input xml in wrong format, Expecting root element %s with child element %s, but was %s", - XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.DATA_KEY, - XmlUtil.toString(innerResult.getDocumentElement())), e); - } + private Element getPlaceholder(final Document innerResult) + throws NetconfDocumentedException { + final XmlElement rootElement = XmlElement.fromDomElementWithExpected( + innerResult.getDocumentElement(), XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.RFC4741_TARGET_NAMESPACE); + return rootElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY).getDomElement(); } @Override @@ -61,7 +50,7 @@ public class Get extends AbstractNetconfOperation { } @Override - public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation) + public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException { if (subsequentOperation.isExecutionTermination()){ throw new NetconfDocumentedException(String.format("Subsequent netconf operation expected by %s", this), @@ -71,29 +60,29 @@ public class Get extends AbstractNetconfOperation { } try { - Document innerResult = subsequentOperation.execute(requestMessage); + final Document innerResult = subsequentOperation.execute(requestMessage); - NetconfState netconfMonitoring = new NetconfState(netconfMonitor); + final NetconfState netconfMonitoring = new NetconfState(netconfMonitor); Element monitoringXmlElement = new JaxBSerializer().toXml(netconfMonitoring); monitoringXmlElement = (Element) innerResult.importNode(monitoringXmlElement, true); - Element monitoringXmlElementPlaceholder = getPlaceholder(innerResult); + final Element monitoringXmlElementPlaceholder = getPlaceholder(innerResult); monitoringXmlElementPlaceholder.appendChild(monitoringXmlElement); return innerResult; - } catch (RuntimeException e) { - String errorMessage = "Get operation for netconf-state subtree failed"; + } catch (final RuntimeException e) { + final String errorMessage = "Get operation for netconf-state subtree failed"; logger.warn(errorMessage, e); - Map info = Maps.newHashMap(); - info.put(NetconfDocumentedException.ErrorSeverity.error.toString(), e.getMessage()); + throw new NetconfDocumentedException(errorMessage, NetconfDocumentedException.ErrorType.application, NetconfDocumentedException.ErrorTag.operation_failed, - NetconfDocumentedException.ErrorSeverity.error, info); + NetconfDocumentedException.ErrorSeverity.error, + Collections.singletonMap(NetconfDocumentedException.ErrorSeverity.error.toString(), e.getMessage())); } } @Override - protected Element handle(Document document, XmlElement message, NetconfOperationChainedExecution subsequentOperation) + protected Element handle(final Document document, final XmlElement message, final NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException { throw new UnsupportedOperationException("Never gets called"); } diff --git a/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringActivator.java b/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringActivator.java index 14c47352a8..9d332c6440 100644 --- a/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringActivator.java +++ b/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringActivator.java @@ -24,7 +24,6 @@ public class NetconfMonitoringActivator implements BundleActivator { public void start(final BundleContext context) { monitor = new NetconfMonitoringServiceTracker(context); monitor.open(); - } @Override diff --git a/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringServiceTracker.java b/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringServiceTracker.java index 920236b9b6..f99ae54e6d 100644 --- a/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringServiceTracker.java +++ b/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringServiceTracker.java @@ -8,6 +8,7 @@ package org.opendaylight.controller.netconf.monitoring.osgi; import com.google.common.base.Preconditions; +import java.util.Hashtable; import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService; import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory; import org.osgi.framework.BundleContext; @@ -17,43 +18,39 @@ import org.osgi.util.tracker.ServiceTracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Dictionary; -import java.util.Hashtable; - public class NetconfMonitoringServiceTracker extends ServiceTracker { private static final Logger logger = LoggerFactory.getLogger(NetconfMonitoringServiceTracker.class); private ServiceRegistration reg; - NetconfMonitoringServiceTracker(BundleContext context) { + NetconfMonitoringServiceTracker(final BundleContext context) { super(context, NetconfMonitoringService.class, null); } @Override - public NetconfMonitoringService addingService(ServiceReference reference) { + public NetconfMonitoringService addingService(final ServiceReference reference) { Preconditions.checkState(reg == null, "Monitoring service was already added"); - NetconfMonitoringService netconfMonitoringService = super.addingService(reference); + final NetconfMonitoringService netconfMonitoringService = super.addingService(reference); final NetconfMonitoringOperationService operationService = new NetconfMonitoringOperationService( netconfMonitoringService); - NetconfOperationServiceFactory factory = new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory( + final NetconfOperationServiceFactory factory = new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory( operationService); - Dictionary props = new Hashtable<>(); - reg = context.registerService(NetconfOperationServiceFactory.class, factory, props); + reg = context.registerService(NetconfOperationServiceFactory.class, factory, new Hashtable()); return netconfMonitoringService; } @Override - public void removedService(ServiceReference reference, - NetconfMonitoringService netconfMonitoringService) { + public void removedService(final ServiceReference reference, + final NetconfMonitoringService netconfMonitoringService) { if(reg!=null) { try { reg.unregister(); - } catch (Exception e) { + } catch (final Exception e) { logger.warn("Ignoring exception while unregistering {}", reg, e); } } diff --git a/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/xml/JaxBSerializer.java b/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/xml/JaxBSerializer.java index 4b07ab090a..962ad17b66 100644 --- a/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/xml/JaxBSerializer.java +++ b/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/xml/JaxBSerializer.java @@ -18,17 +18,17 @@ import javax.xml.transform.dom.DOMResult; public class JaxBSerializer { - public Element toXml(NetconfState monitoringModel) { - DOMResult res = null; + public Element toXml(final NetconfState monitoringModel) { + final DOMResult res; try { - JAXBContext jaxbContext = JAXBContext.newInstance(NetconfState.class); - Marshaller marshaller = jaxbContext.createMarshaller(); + final JAXBContext jaxbContext = JAXBContext.newInstance(NetconfState.class); + final Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); res = new DOMResult(); marshaller.marshal(monitoringModel, res); - } catch (JAXBException e) { + } catch (final JAXBException e) { throw new RuntimeException("Unable to serialize netconf state " + monitoringModel, e); } return ((Document)res.getNode()).getDocumentElement(); diff --git a/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/xml/model/NetconfState.java b/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/xml/model/NetconfState.java index 98bda5833e..8f5a1c029d 100644 --- a/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/xml/model/NetconfState.java +++ b/opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/xml/model/NetconfState.java @@ -28,15 +28,12 @@ public final class NetconfState { private Schemas schemas; private Sessions sessions; - public NetconfState(NetconfMonitoringService monitoringService) { + public NetconfState(final NetconfMonitoringService monitoringService) { this.sessions = monitoringService.getSessions(); this.schemas = monitoringService.getSchemas(); } - public NetconfState() { - } - - + public NetconfState() {} @XmlElementWrapper(name="schemas") @XmlElement(name="schema") @@ -44,7 +41,7 @@ public final class NetconfState { return Collections2.transform(schemas.getSchema(), new Function() { @Nullable @Override - public MonitoringSchema apply(@Nullable Schema input) { + public MonitoringSchema apply(@Nullable final Schema input) { return new MonitoringSchema(input); } }); @@ -56,7 +53,7 @@ public final class NetconfState { return Collections2.transform(sessions.getSession(), new Function() { @Nullable @Override - public MonitoringSession apply(@Nullable Session input) { + public MonitoringSession apply(@Nullable final Session input) { return new MonitoringSession(input); } }); diff --git a/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/GetTest.java b/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/GetTest.java new file mode 100644 index 0000000000..5fceac06dd --- /dev/null +++ b/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/GetTest.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.monitoring; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertTrue; +import static junit.framework.TestCase.fail; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; + +import java.util.Collections; +import org.hamcrest.CoreMatchers; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.opendaylight.controller.netconf.api.NetconfDocumentedException; +import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService; +import org.opendaylight.controller.netconf.mapping.api.HandlingPriority; +import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution; +import org.opendaylight.controller.netconf.util.xml.XmlUtil; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SchemasBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SessionsBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session; +import org.w3c.dom.Document; + +public class GetTest { + + @Mock + private NetconfMonitoringService monitor; + @Mock + private Document request; + @Mock + private NetconfOperationChainedExecution subsequentOperation; + private Document incorrectSubsequentResult; + private Document correctSubsequentResult; + + private Get get; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + incorrectSubsequentResult = XmlUtil.readXmlToDocument(""); + correctSubsequentResult = XmlUtil.readXmlToDocument(""); + + doReturn(new SessionsBuilder().setSession(Collections.emptyList()).build()).when(monitor).getSessions(); + doReturn(new SchemasBuilder().setSchema(Collections.emptyList()).build()).when(monitor).getSchemas(); + doReturn(false).when(subsequentOperation).isExecutionTermination(); + + get = new Get(monitor); + } + + @Test + public void testHandleNoSubsequent() throws Exception { + try { + get.handle(null, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT); + } catch (final NetconfDocumentedException e) { + assertNetconfDocumentedEx(e, NetconfDocumentedException.ErrorSeverity.error, NetconfDocumentedException.ErrorTag.operation_failed, NetconfDocumentedException.ErrorType.application); + return; + } + + fail("Get should fail without subsequent operation"); + } + + @Test + public void testHandleWrongPlaceholder() throws Exception { + doReturn(incorrectSubsequentResult).when(subsequentOperation).execute(request); + try { + get.handle(request, subsequentOperation); + } catch (final NetconfDocumentedException e) { + assertNetconfDocumentedEx(e, NetconfDocumentedException.ErrorSeverity.error, NetconfDocumentedException.ErrorTag.invalid_value, NetconfDocumentedException.ErrorType.application); + return; + } + + fail("Get should fail with wrong xml"); + } + + @Test + public void testHandleRuntimeEx() throws Exception { + doThrow(RuntimeException.class).when(subsequentOperation).execute(request); + try { + get.handle(request, subsequentOperation); + } catch (final NetconfDocumentedException e) { + assertNetconfDocumentedEx(e, NetconfDocumentedException.ErrorSeverity.error, NetconfDocumentedException.ErrorTag.operation_failed, NetconfDocumentedException.ErrorType.application); + assertEquals(1, e.getErrorInfo().size()); + return; + } + + fail("Get should fail with wrong xml"); + } + + @Test + public void testSuccessHandle() throws Exception { + doReturn(correctSubsequentResult).when(subsequentOperation).execute(request); + assertTrue(get.getHandlingPriority().getPriority().get() > HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.getPriority().get()); + final Document result = get.handle(request, subsequentOperation); + assertThat(XmlUtil.toString(result), CoreMatchers.containsString("sessions")); + assertThat(XmlUtil.toString(result), CoreMatchers.containsString("schemas")); + + } + + @Test(expected = UnsupportedOperationException.class) + public void testHandle() throws Exception { + get.handle(null, null, null); + + } + + private void assertNetconfDocumentedEx(final NetconfDocumentedException e, final NetconfDocumentedException.ErrorSeverity severity, final NetconfDocumentedException.ErrorTag errorTag, final NetconfDocumentedException.ErrorType type) { + assertEquals(severity, e.getErrorSeverity()); + assertEquals(errorTag, e.getErrorTag()); + assertEquals(type, e.getErrorType()); + } +} diff --git a/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/xml/JaxBSerializerTest.java b/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/xml/JaxBSerializerTest.java index 02129574da..d0d587fb84 100644 --- a/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/xml/JaxBSerializerTest.java +++ b/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/xml/JaxBSerializerTest.java @@ -7,37 +7,40 @@ */ package org.opendaylight.controller.netconf.monitoring.xml; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + import com.google.common.collect.Lists; +import org.hamcrest.CoreMatchers; import org.junit.Test; import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService; import org.opendaylight.controller.netconf.monitoring.xml.model.NetconfState; +import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.DomainName; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.NetconfTcp; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.Session1; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfSsh; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Transport; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SchemasBuilder; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Sessions; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SessionsBuilder; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.SchemaKey; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.DateAndTime; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.ZeroBasedCounter32; -import org.w3c.dom.Element; - -import java.util.Date; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; public class JaxBSerializerTest { @Test public void testName() throws Exception { - NetconfMonitoringService service = new NetconfMonitoringService() { + final NetconfMonitoringService service = new NetconfMonitoringService() { @Override public Sessions getSessions() { @@ -46,19 +49,54 @@ public class JaxBSerializerTest { @Override public Schemas getSchemas() { - return new SchemasBuilder().setSchema(Lists.newArrayList()).build(); + return new SchemasBuilder().setSchema(Lists.newArrayList(getMockSchema("id", "v1", Yang.class), getMockSchema("id2", "", Yang.class))).build(); } }; - NetconfState model = new NetconfState(service); - Element xml = new JaxBSerializer().toXml(model); + final NetconfState model = new NetconfState(service); + final String xml = XmlUtil.toString(new JaxBSerializer().toXml(model)); + + assertThat(xml, CoreMatchers.containsString( + "\n" + + "yang\n" + + "id\n" + + "NETCONF\n" + + "localhost\n" + + "v1\n" + + "\n")); + + assertThat(xml, CoreMatchers.containsString( + "\n" + + "1\n" + + "0\n" + + "0\n" + + "loginTime\n" + + "0\n" + + "0\n" + + "client\n" + + "address/port\n" + + "ncme:netconf-tcp\n" + + "username\n" + + "")); + } + + private Schema getMockSchema(final String id, final String version, final Class format) { + final Schema mock = mock(Schema.class); + + doReturn(format).when(mock).getFormat(); + doReturn(id).when(mock).getIdentifier(); + doReturn(new Uri("localhost")).when(mock).getNamespace(); + doReturn(version).when(mock).getVersion(); + doReturn(Lists.newArrayList(new Schema.Location(Schema.Location.Enumeration.NETCONF))).when(mock).getLocation(); + doReturn(new SchemaKey(format, id, version)).when(mock).getKey(); + return mock; } - private Session getMockSession(Class transportType) { - Session mocked = mock(Session.class); - Session1 mockedSession1 = mock(Session1.class); + private Session getMockSession(final Class transportType) { + final Session mocked = mock(Session.class); + final Session1 mockedSession1 = mock(Session1.class); doReturn("client").when(mockedSession1).getSessionIdentifier(); doReturn(1L).when(mocked).getSessionId(); - doReturn(new DateAndTime(new Date().toString())).when(mocked).getLoginTime(); + doReturn(new DateAndTime("loginTime")).when(mocked).getLoginTime(); doReturn(new Host(new DomainName("address/port"))).when(mocked).getSourceHost(); doReturn(new ZeroBasedCounter32(0L)).when(mocked).getInBadRpcs(); doReturn(new ZeroBasedCounter32(0L)).when(mocked).getInRpcs(); diff --git a/opendaylight/netconf/netconf-netty-util/pom.xml b/opendaylight/netconf/netconf-netty-util/pom.xml index 80dc1ae0fd..cb8461a299 100644 --- a/opendaylight/netconf/netconf-netty-util/pom.xml +++ b/opendaylight/netconf/netconf-netty-util/pom.xml @@ -64,7 +64,6 @@ org.openexi nagasena-rta - org.osgi org.osgi.core @@ -77,7 +76,10 @@ xmlunit xmlunit - + + org.opendaylight.yangtools + mockito-configuration + diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoder.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoder.java index d765ca8b25..f39e2c425d 100644 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoder.java +++ b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoder.java @@ -53,8 +53,7 @@ public final class NetconfHelloMessageToXMLEncoder extends NetconfMessageToXMLEn Optional headerOptional = ((NetconfHelloMessage) msg) .getAdditionalHeader(); - // If additional header present, serialize it along with netconf hello - // message + // If additional header present, serialize it along with netconf hello message if (headerOptional.isPresent()) { out.writeBytes(headerOptional.get().toFormattedString().getBytes(Charsets.UTF_8)); } diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfXMLToMessageDecoder.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfXMLToMessageDecoder.java index 69c0d53fc1..bfc8d77e17 100644 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfXMLToMessageDecoder.java +++ b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfXMLToMessageDecoder.java @@ -7,26 +7,21 @@ */ package org.opendaylight.controller.netconf.nettyutil.handler; -import java.util.List; - -import org.opendaylight.controller.netconf.api.NetconfMessage; -import org.opendaylight.controller.netconf.util.xml.XmlUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.annotations.VisibleForTesting; - import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; +import java.util.List; +import org.opendaylight.controller.netconf.api.NetconfMessage; +import org.opendaylight.controller.netconf.util.xml.XmlUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public final class NetconfXMLToMessageDecoder extends ByteToMessageDecoder { private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToMessageDecoder.class); @Override - @VisibleForTesting public void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { if (in.readableBytes() != 0) { diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java index eea2b8693a..0548b1d371 100644 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java +++ b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java @@ -8,7 +8,6 @@ package org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication; -import ch.ethz.ssh2.Connection; import java.io.IOException; import org.apache.sshd.ClientSession; @@ -16,8 +15,6 @@ import org.apache.sshd.ClientSession; * Class providing authentication facility to SSH handler. */ public abstract class AuthenticationHandler { - public abstract void authenticate(Connection connection) throws IOException; - public abstract String getUsername(); diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/LoginPassword.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/LoginPassword.java index 553e5359ff..ab94e59a93 100644 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/LoginPassword.java +++ b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/LoginPassword.java @@ -9,15 +9,12 @@ package org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication; import java.io.IOException; - import org.apache.sshd.ClientSession; import org.apache.sshd.client.future.AuthFuture; -import ch.ethz.ssh2.Connection; - /** * Class Providing username/password authentication option to - * {@link org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.SshHandler} + * {@link org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandler} */ public class LoginPassword extends AuthenticationHandler { private final String username; @@ -28,15 +25,6 @@ public class LoginPassword extends AuthenticationHandler { this.password = password; } - @Override - public void authenticate(Connection connection) throws IOException { - final boolean isAuthenticated = connection.authenticateWithPassword(username, password); - - if (!isAuthenticated) { - throw new IOException("Authentication failed."); - } - } - @Override public String getUsername() { return username; diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/virtualsocket/ChannelInputStream.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/virtualsocket/ChannelInputStream.java deleted file mode 100644 index ba65b9ef34..0000000000 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/virtualsocket/ChannelInputStream.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.netconf.nettyutil.handler.ssh.virtualsocket; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandler; -import java.io.IOException; -import java.io.InputStream; - -/** - * Class provides {@link InputStream} functionality to users of virtual socket. - */ -public class ChannelInputStream extends InputStream implements ChannelInboundHandler { - private final Object lock = new Object(); - private final ByteBuf bb = Unpooled.buffer(); - - @Override - public int read(byte b[], int off, int len) throws IOException { - if (b == null) { - throw new NullPointerException(); - } else if (off < 0 || len < 0 || len > b.length - off) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return 0; - } - - int bytesRead = 1; - synchronized (lock) { - int c = read(); - - b[off] = (byte)c; - - if(this.bb.readableBytes() == 0) { - return bytesRead; - } - - int ltr = len-1; - ltr = (ltr <= bb.readableBytes()) ? ltr : bb.readableBytes(); - - bb.readBytes(b, 1, ltr); - bytesRead += ltr; - } - return bytesRead; - } - - @Override - public int read() throws IOException { - synchronized (lock) { - while (this.bb.readableBytes() == 0) { - try { - lock.wait(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(e); - } - } - return this.bb.readByte() & 0xFF; - } - } - - @Override - public int available() throws IOException { - synchronized (lock) { - return this.bb.readableBytes(); - } - } - - public void channelRegistered(ChannelHandlerContext ctx) { - ctx.fireChannelRegistered(); - } - - public void channelUnregistered(ChannelHandlerContext ctx) { - ctx.fireChannelUnregistered(); - } - - public void channelActive(ChannelHandlerContext ctx) { - ctx.fireChannelActive(); - } - - public void channelInactive(ChannelHandlerContext ctx) { - ctx.fireChannelInactive(); - } - - public void channelRead(ChannelHandlerContext ctx, Object o) { - synchronized(lock) { - this.bb.discardReadBytes(); - this.bb.writeBytes((ByteBuf) o); - ((ByteBuf) o).release(); - lock.notifyAll(); - } - } - - public void channelReadComplete(ChannelHandlerContext ctx) { - ctx.fireChannelReadComplete(); - } - - public void userEventTriggered(ChannelHandlerContext ctx, Object o) { - ctx.fireUserEventTriggered(o); - } - - public void channelWritabilityChanged(ChannelHandlerContext ctx) { - ctx.fireChannelWritabilityChanged(); - } - - public void handlerAdded(ChannelHandlerContext ctx) { - } - - public void handlerRemoved(ChannelHandlerContext ctx) { - } - - public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) { - ctx.fireExceptionCaught(throwable); - } -} - diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/virtualsocket/ChannelOutputStream.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/virtualsocket/ChannelOutputStream.java deleted file mode 100644 index 2dc5235f91..0000000000 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/virtualsocket/ChannelOutputStream.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.netconf.nettyutil.handler.ssh.virtualsocket; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelOutboundHandler; -import io.netty.channel.ChannelPromise; - -import java.io.OutputStream; -import java.net.SocketAddress; - -/** - * Class provides {@link OutputStream) functionality to users of virtual socket. - */ -public class ChannelOutputStream extends OutputStream implements ChannelOutboundHandler { - private final Object lock = new Object(); - private ByteBuf buff = Unpooled.buffer(); - private ChannelHandlerContext ctx; - - @Override - public void flush() { - synchronized(lock) { - ctx.writeAndFlush(buff).awaitUninterruptibly(); - buff = Unpooled.buffer(); - } - } - - @Override - public void write(int b) { - synchronized(lock) { - buff.writeByte(b); - } - } - - public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, - ChannelPromise promise) { - ctx.bind(localAddress, promise); - } - - public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, - SocketAddress localAddress, ChannelPromise promise) { - this.ctx = ctx; - ctx.connect(remoteAddress, localAddress, promise); - } - - public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) { - ctx.disconnect(promise); - } - - public void close(ChannelHandlerContext ctx, ChannelPromise promise) { - ctx.close(promise); - } - - public void deregister(ChannelHandlerContext ctx, ChannelPromise channelPromise) { - ctx.deregister(channelPromise); - } - - public void read(ChannelHandlerContext ctx) { - ctx.read(); - } - - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { - // pass - } - - public void flush(ChannelHandlerContext ctx) { - // pass - } - - public void handlerAdded(ChannelHandlerContext ctx) - throws Exception { - } - - public void handlerRemoved(ChannelHandlerContext ctx) - throws Exception { - } - - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - ctx.fireExceptionCaught(cause); - } -} diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/virtualsocket/VirtualSocket.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/virtualsocket/VirtualSocket.java deleted file mode 100644 index 69cce8057e..0000000000 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/virtualsocket/VirtualSocket.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.netconf.nettyutil.handler.ssh.virtualsocket; - -import io.netty.channel.ChannelHandler; -import io.netty.channel.ChannelHandlerContext; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketException; -import java.nio.channels.SocketChannel; - -/** - * Handler class providing Socket functionality to OIO client application. By using VirtualSocket user can - * use OIO application in asynchronous environment and NIO EventLoop. Using VirtualSocket OIO applications - * are able to use full potential of NIO environment. - */ -//TODO: refactor - socket should be created when connection is established -public class VirtualSocket extends Socket implements ChannelHandler { - private static final String INPUT_STREAM = "inputStream"; - private static final String OUTPUT_STREAM = "outputStream"; - - private final ChannelInputStream chais = new ChannelInputStream(); - private final ChannelOutputStream chaos = new ChannelOutputStream(); - private ChannelHandlerContext ctx; - - - public InputStream getInputStream() { - return this.chais; - } - - public OutputStream getOutputStream() { - return this.chaos; - } - - public void handlerAdded(ChannelHandlerContext ctx) { - this.ctx = ctx; - - if (ctx.channel().pipeline().get(OUTPUT_STREAM) == null) { - ctx.channel().pipeline().addFirst(OUTPUT_STREAM, chaos); - } - - if (ctx.channel().pipeline().get(INPUT_STREAM) == null) { - ctx.channel().pipeline().addFirst(INPUT_STREAM, chais); - } - } - - public void handlerRemoved(ChannelHandlerContext ctx) { - if (ctx.channel().pipeline().get(OUTPUT_STREAM) != null) { - ctx.channel().pipeline().remove(OUTPUT_STREAM); - } - - if (ctx.channel().pipeline().get(INPUT_STREAM) != null) { - ctx.channel().pipeline().remove(INPUT_STREAM); - } - } - - public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) { - // TODO exceptionCaught is deprecated transform this handler - ctx.fireExceptionCaught(throwable); - } - - - @Override - public void connect(SocketAddress endpoint) throws IOException {} - - @Override - public void connect(SocketAddress endpoint, int timeout) throws IOException {} - - @Override - public void bind(SocketAddress bindpoint) throws IOException {} - - @Override - public InetAddress getInetAddress() { - InetSocketAddress isa = getInetSocketAddress(); - return isa.getAddress(); - } - - @Override - public InetAddress getLocalAddress() {return null;} - - @Override - public int getPort() { - return getInetSocketAddress().getPort(); - } - - private InetSocketAddress getInetSocketAddress() { - return (InetSocketAddress)getRemoteSocketAddress(); - } - - @Override - public int getLocalPort() {return -1;} - - @Override - public SocketAddress getRemoteSocketAddress() { - return this.ctx.channel().remoteAddress(); - } - - @Override - public SocketAddress getLocalSocketAddress() { - return this.ctx.channel().localAddress(); - } - - @Override - public SocketChannel getChannel() {return null;} - - @Override - public void setTcpNoDelay(boolean on) throws SocketException {} - - @Override - public boolean getTcpNoDelay() throws SocketException {return false;} - - @Override - public void setSoLinger(boolean on, int linger) throws SocketException {} - - @Override - public int getSoLinger() throws SocketException {return -1;} - - @Override - public void sendUrgentData(int data) throws IOException {} - - @Override - public void setOOBInline(boolean on) throws SocketException {} - - @Override - public boolean getOOBInline() throws SocketException {return false;} - - @Override - public synchronized void setSoTimeout(int timeout) throws SocketException {} - - @Override - public synchronized int getSoTimeout() throws SocketException {return -1;} - - @Override - public synchronized void setSendBufferSize(int size) throws SocketException {} - - @Override - public synchronized int getSendBufferSize() throws SocketException {return -1;} - - @Override - public synchronized void setReceiveBufferSize(int size) throws SocketException {} - - @Override - public synchronized int getReceiveBufferSize() throws SocketException {return -1;} - - @Override - public void setKeepAlive(boolean on) throws SocketException {} - - @Override - public boolean getKeepAlive() throws SocketException {return false;} - - @Override - public void setTrafficClass(int tc) throws SocketException {} - - @Override - public int getTrafficClass() throws SocketException {return -1;} - - @Override - public void setReuseAddress(boolean on) throws SocketException {} - - @Override - public boolean getReuseAddress() throws SocketException {return false;} - - @Override - public synchronized void close() throws IOException {} - - @Override - public void shutdownInput() throws IOException {} - - @Override - public void shutdownOutput() throws IOException {} - - @Override - public String toString() { - return "VirtualSocket{" + getInetAddress() + ":" + getPort() + "}"; - } - - @Override - public boolean isConnected() {return false;} - - @Override - public boolean isBound() {return false;} - - @Override - public boolean isClosed() {return false;} - - @Override - public boolean isInputShutdown() {return false;} - - @Override - public boolean isOutputShutdown() {return false;} - - @Override - public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {} -} diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java new file mode 100644 index 0000000000..93475129d2 --- /dev/null +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.nettyutil.handler; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doAnswer; + +import com.google.common.collect.Lists; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants; + +public class ChunkedFramingMechanismEncoderTest { + + private int chunkSize; + @Mock + private ChannelHandlerContext ctx; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + chunkSize = 256; + } + + @Test(expected = IllegalArgumentException.class) + public void testIllegalSize() throws Exception { + new ChunkedFramingMechanismEncoder(10); + } + + @Test(expected = IllegalArgumentException.class) + public void testIllegalSizeMax() throws Exception { + new ChunkedFramingMechanismEncoder(Integer.MAX_VALUE); + } + + @Test + public void testEncode() throws Exception { + final List chunks = Lists.newArrayList(); + doAnswer(new Answer() { + @Override + public Object answer(final InvocationOnMock invocation) throws Throwable { + chunks.add((ByteBuf) invocation.getArguments()[0]); + return null; + } + }).when(ctx).write(anyObject()); + + final ChunkedFramingMechanismEncoder encoder = new ChunkedFramingMechanismEncoder(chunkSize); + final int lastChunkSize = 20; + final ByteBuf src = Unpooled.wrappedBuffer(getByteArray(chunkSize * 4 + lastChunkSize)); + final ByteBuf destination = Unpooled.buffer(); + encoder.encode(ctx, src, destination); + assertEquals(4, chunks.size()); + + final int framingSize = "#256\n".getBytes().length + 1/* new line at end */; + + for (final ByteBuf chunk : chunks) { + assertEquals(chunkSize + framingSize, chunk.readableBytes()); + } + + final int lastFramingSize = "#20\n".length() + NetconfMessageConstants.END_OF_CHUNK.length + 1/* new line at end */; + assertEquals(lastChunkSize + lastFramingSize, destination.readableBytes()); + } + + private byte[] getByteArray(final int size) { + final byte[] bytes = new byte[size]; + for (int i = 0; i < size; i++) { + bytes[i] = 'a'; + } + return bytes; + } +} diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/EOMFramingMechanismEncoderTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/EOMFramingMechanismEncoderTest.java new file mode 100644 index 0000000000..158f3a8701 --- /dev/null +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/EOMFramingMechanismEncoderTest.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.nettyutil.handler; + +import static org.junit.Assert.assertEquals; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import org.junit.Test; +import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants; + +public class EOMFramingMechanismEncoderTest { + + @Test + public void testEncode() throws Exception { + final byte[] content = new byte[50]; + final ByteBuf source = Unpooled.wrappedBuffer(content); + final ByteBuf destination = Unpooled.buffer(); + new EOMFramingMechanismEncoder().encode(null, source, destination); + + assertEquals(Unpooled.wrappedBuffer(source.array(), NetconfMessageConstants.END_OF_MESSAGE), destination); + } +} \ No newline at end of file diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/FramingMechanismHandlerFactoryTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/FramingMechanismHandlerFactoryTest.java new file mode 100644 index 0000000000..4f123f0f09 --- /dev/null +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/FramingMechanismHandlerFactoryTest.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.nettyutil.handler; + +import org.hamcrest.CoreMatchers; +import org.hamcrest.MatcherAssert; +import org.junit.Test; +import org.opendaylight.controller.netconf.util.messages.FramingMechanism; + +public class FramingMechanismHandlerFactoryTest { + + @Test + public void testCreate() throws Exception { + MatcherAssert.assertThat(FramingMechanismHandlerFactory + .createHandler(FramingMechanism.CHUNK), CoreMatchers + .instanceOf(ChunkedFramingMechanismEncoder.class)); + MatcherAssert.assertThat(FramingMechanismHandlerFactory + .createHandler(FramingMechanism.EOM), CoreMatchers + .instanceOf(EOMFramingMechanismEncoder.class)); + } +} \ No newline at end of file diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfChunkAggregatorTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfChunkAggregatorTest.java index e088859e82..a647b9ee17 100644 --- a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfChunkAggregatorTest.java +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfChunkAggregatorTest.java @@ -7,16 +7,16 @@ */ package org.opendaylight.controller.netconf.nettyutil.handler; +import static org.junit.Assert.assertEquals; + import com.google.common.base.Charsets; import com.google.common.collect.Lists; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -import junit.framework.Assert; +import java.util.List; import org.junit.BeforeClass; import org.junit.Test; -import java.util.List; - public class NetconfChunkAggregatorTest { private static final String CHUNKED_MESSAGE = "\n#4\n" + @@ -45,26 +45,26 @@ public class NetconfChunkAggregatorTest { @Test public void testMultipleChunks() throws Exception { - List output = Lists.newArrayList(); - ByteBuf input = Unpooled.copiedBuffer(CHUNKED_MESSAGE.getBytes(Charsets.UTF_8)); + final List output = Lists.newArrayList(); + final ByteBuf input = Unpooled.copiedBuffer(CHUNKED_MESSAGE.getBytes(Charsets.UTF_8)); agr.decode(null, input, output); - Assert.assertEquals(1, output.size()); - ByteBuf chunk = (ByteBuf) output.get(0); + assertEquals(1, output.size()); + final ByteBuf chunk = (ByteBuf) output.get(0); - Assert.assertEquals(EXPECTED_MESSAGE, chunk.toString(Charsets.UTF_8)); + assertEquals(EXPECTED_MESSAGE, chunk.toString(Charsets.UTF_8)); } @Test public void testOneChunks() throws Exception { - List output = Lists.newArrayList(); - ByteBuf input = Unpooled.copiedBuffer(CHUNKED_MESSAGE_ONE.getBytes(Charsets.UTF_8)); + final List output = Lists.newArrayList(); + final ByteBuf input = Unpooled.copiedBuffer(CHUNKED_MESSAGE_ONE.getBytes(Charsets.UTF_8)); agr.decode(null, input, output); - Assert.assertEquals(1, output.size()); - ByteBuf chunk = (ByteBuf) output.get(0); + assertEquals(1, output.size()); + final ByteBuf chunk = (ByteBuf) output.get(0); - Assert.assertEquals(EXPECTED_MESSAGE, chunk.toString(Charsets.UTF_8)); + assertEquals(EXPECTED_MESSAGE, chunk.toString(Charsets.UTF_8)); } diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoderTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoderTest.java new file mode 100644 index 0000000000..00d95df423 --- /dev/null +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoderTest.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.nettyutil.handler; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertThat; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.opendaylight.controller.netconf.api.NetconfMessage; +import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage; +import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader; +import org.opendaylight.controller.netconf.util.xml.XmlUtil; + +public class NetconfHelloMessageToXMLEncoderTest { + + @Mock + private ChannelHandlerContext ctx; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testEncode() throws Exception { + final NetconfMessage msg = new NetconfHelloMessage(XmlUtil.readXmlToDocument(""), + NetconfHelloMessageAdditionalHeader.fromString("[tomas;10.0.0.0:10000;tcp;client;]")); + final ByteBuf destination = Unpooled.buffer(); + new NetconfHelloMessageToXMLEncoder().encode(ctx, msg, destination); + + final String encoded = new String(destination.array()); + assertThat(encoded, containsString("[tomas;10.0.0.0:10000;tcp;client;]")); + assertThat(encoded, containsString("")); + } + + @Test + public void testEncodeNoHeader() throws Exception { + final NetconfMessage msg = new NetconfHelloMessage(XmlUtil.readXmlToDocument("")); + final ByteBuf destination = Unpooled.buffer(); + new NetconfHelloMessageToXMLEncoder().encode(ctx, msg, destination); + + final String encoded = new String(destination.array()); + assertThat(encoded, not(containsString("[tomas;10.0.0.0:10000;tcp;client;]"))); + assertThat(encoded, containsString("")); + } + + @Test(expected = IllegalStateException.class) + public void testEncodeNotHello() throws Exception { + final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument("")); + new NetconfHelloMessageToXMLEncoder().encode(ctx, msg, null); + } +} \ No newline at end of file diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfXMLToHelloMessageDecoderTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfXMLToHelloMessageDecoderTest.java new file mode 100644 index 0000000000..f0c0d6341b --- /dev/null +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfXMLToHelloMessageDecoderTest.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.nettyutil.handler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import java.util.List; +import org.hamcrest.CoreMatchers; +import org.junit.Test; +import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage; +import org.opendaylight.controller.netconf.util.xml.XmlUtil; + +public class NetconfXMLToHelloMessageDecoderTest { + + @Test + public void testDecodeWithHeader() throws Exception { + final ByteBuf src = Unpooled.wrappedBuffer(String.format("%s\n%s", + "[tomas;10.0.0.0:10000;tcp;client;]", "").getBytes()); + final List out = Lists.newArrayList(); + new NetconfXMLToHelloMessageDecoder().decode(null, src, out); + + assertEquals(1, out.size()); + assertThat(out.get(0), CoreMatchers.instanceOf(NetconfHelloMessage.class)); + final NetconfHelloMessage hello = (NetconfHelloMessage) out.get(0); + assertTrue(hello.getAdditionalHeader().isPresent()); + assertEquals("[tomas;10.0.0.0:10000;tcp;client;]\n", hello.getAdditionalHeader().get().toFormattedString()); + assertThat(XmlUtil.toString(hello.getDocument()), CoreMatchers.containsString("".getBytes()); + final List out = Lists.newArrayList(); + new NetconfXMLToHelloMessageDecoder().decode(null, src, out); + + assertEquals(1, out.size()); + assertThat(out.get(0), CoreMatchers.instanceOf(NetconfHelloMessage.class)); + final NetconfHelloMessage hello = (NetconfHelloMessage) out.get(0); + assertFalse(hello.getAdditionalHeader().isPresent()); + } + + @Test + public void testDecodeCaching() throws Exception { + final ByteBuf msg1 = Unpooled.wrappedBuffer("".getBytes()); + final ByteBuf msg2 = Unpooled.wrappedBuffer("".getBytes()); + final ByteBuf src = Unpooled.wrappedBuffer("".getBytes()); + final List out = Lists.newArrayList(); + final NetconfXMLToHelloMessageDecoder decoder = new NetconfXMLToHelloMessageDecoder(); + decoder.decode(null, src, out); + decoder.decode(null, msg1, out); + decoder.decode(null, msg2, out); + + assertEquals(1, out.size()); + + assertEquals(2, Iterables.size(decoder.getPostHelloNetconfMessages())); + } + + @Test(expected = IllegalStateException.class) + public void testDecodeNotHelloReceived() throws Exception { + final ByteBuf msg1 = Unpooled.wrappedBuffer("".getBytes()); + final List out = Lists.newArrayList(); + NetconfXMLToHelloMessageDecoder decoder = new NetconfXMLToHelloMessageDecoder(); + decoder.decode(null, msg1, out); + } +} \ No newline at end of file diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfXMLToMessageDecoderTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfXMLToMessageDecoderTest.java new file mode 100644 index 0000000000..f85a38769f --- /dev/null +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfXMLToMessageDecoderTest.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.nettyutil.handler; + +import static org.junit.Assert.assertEquals; + +import com.google.common.collect.Lists; +import io.netty.buffer.Unpooled; +import java.util.ArrayList; +import org.junit.Test; + +public class NetconfXMLToMessageDecoderTest { + + @Test + public void testDecodeNoMoreContent() throws Exception { + final ArrayList out = Lists.newArrayList(); + new NetconfXMLToMessageDecoder().decode(null, Unpooled.buffer(), out); + assertEquals(0, out.size()); + } + + @Test + public void testDecode() throws Exception { + final ArrayList out = Lists.newArrayList(); + new NetconfXMLToMessageDecoder().decode(null, Unpooled.wrappedBuffer("".getBytes()), out); + assertEquals(1, out.size()); + } +} \ No newline at end of file diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/LoginPasswordTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/LoginPasswordTest.java new file mode 100644 index 0000000000..01df1e3fce --- /dev/null +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/authentication/LoginPasswordTest.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import org.apache.sshd.ClientSession; +import org.apache.sshd.client.future.AuthFuture; +import org.junit.Test; + +public class LoginPasswordTest { + + @Test + public void testLoginPassword() throws Exception { + final LoginPassword loginPassword = new LoginPassword("user", "pwd"); + assertEquals("user", loginPassword.getUsername()); + + final ClientSession session = mock(ClientSession.class); + doNothing().when(session).addPasswordIdentity("pwd"); + doReturn(mock(AuthFuture.class)).when(session).auth(); + loginPassword.authenticate(session); + + verify(session).addPasswordIdentity("pwd"); + verify(session).auth(); + } +} \ No newline at end of file diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronLoadBalancerPoolMemberAware.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronLoadBalancerPoolMemberAware.java index 0a1da77604..69a57748dd 100644 --- a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronLoadBalancerPoolMemberAware.java +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronLoadBalancerPoolMemberAware.java @@ -75,5 +75,5 @@ public interface INeutronLoadBalancerPoolMemberAware { * instance of deleted LoadBalancerPool object * @return void */ - public void NeutronLoadBalancerPoolMemberDeleted(NeutronLoadBalancerPoolMember loadBalancerPoolMember); + public void neutronLoadBalancerPoolMemberDeleted(NeutronLoadBalancerPoolMember loadBalancerPoolMember); }