Merge "Parents pom distribution"
authorEd Warnicke <eaw@cisco.com>
Fri, 14 Jun 2013 18:53:08 +0000 (18:53 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Fri, 14 Jun 2013 18:53:08 +0000 (18:53 +0000)
454 files changed:
.gitignore
opendaylight/arphandler/src/test/java/org/opendaylight/controller/arphandler/internal/ArphandlerTest.java
opendaylight/clustering/integrationtest/pom.xml
opendaylight/clustering/integrationtest/src/test/resources/logback.xml
opendaylight/clustering/services_implementation/src/main/resources/config/infinispan-config.xml
opendaylight/clustering/test/src/test/java/org/opendaylight/controller/clustering/test/internal/TestClusteringTest.java
opendaylight/commons/concepts/pom.xml
opendaylight/commons/concepts/src/main/java/org/opendaylight/controller/concepts/transform/Acceptor.java
opendaylight/commons/concepts/src/main/java/org/opendaylight/controller/concepts/transform/AggregateTransformer.java
opendaylight/commons/concepts/src/main/java/org/opendaylight/controller/concepts/transform/CompositeClassBasedTransformer.java
opendaylight/commons/concepts/src/main/java/org/opendaylight/controller/concepts/transform/InputClassBasedTransformer.java
opendaylight/commons/concepts/src/main/java/org/opendaylight/controller/concepts/transform/RuleBasedTransformer.java
opendaylight/commons/concepts/src/main/java/org/opendaylight/controller/concepts/transform/SimpleConditionalTransformer.java
opendaylight/commons/concepts/src/main/java/org/opendaylight/controller/concepts/transform/Transformer.java
opendaylight/commons/integrationtest/pom.xml
opendaylight/commons/opendaylight/logback.xml
opendaylight/commons/opendaylight/pom.xml
opendaylight/commons/opendaylight/space_and_tabs_checks.xml [new file with mode: 0644]
opendaylight/commons/parent/README [new file with mode: 0644]
opendaylight/commons/parent/logback.xml [new file with mode: 0644]
opendaylight/commons/parent/pom.xml [new file with mode: 0644]
opendaylight/commons/parent/space_and_tabs_checks.xml [new file with mode: 0644]
opendaylight/commons/parent/sun_coding_style.xml [new file with mode: 0644]
opendaylight/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerImpl.java
opendaylight/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ConfigurationImpl.java
opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationAwareTest.java
opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerAwareTest.java
opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerImplTest.java
opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationImplTest.java
opendaylight/configuration/integrationtest/.gitignore [new file with mode: 0644]
opendaylight/configuration/integrationtest/pom.xml [new file with mode: 0644]
opendaylight/configuration/integrationtest/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationIT.java [new file with mode: 0644]
opendaylight/configuration/integrationtest/src/test/resources/logback.xml [new file with mode: 0644]
opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManager.java
opendaylight/containermanager/implementation/pom.xml
opendaylight/containermanager/implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerImplTest.java
opendaylight/containermanager/implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerManagerTest.java
opendaylight/distribution/opendaylight/pom.xml
opendaylight/distribution/opendaylight/src/assemble/bin.xml
opendaylight/distribution/opendaylight/src/main/resources/configuration/config.ini
opendaylight/distribution/opendaylight/src/main/resources/configuration/logback.xml
opendaylight/distribution/opendaylight/src/main/resources/configuration/tomcat-server.xml
opendaylight/distribution/opendaylight/src/main/resources/run.bat
opendaylight/distribution/p2site/pom.xml
opendaylight/distribution/sdk/pom.xml
opendaylight/distribution/sdk/src/assemble/bin.xml
opendaylight/forwarding/staticrouting/pom.xml
opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IForwardingStaticRouting.java
opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfig.java
opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementation.java
opendaylight/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfigTest.java
opendaylight/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteTest.java
opendaylight/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementationTest.java
opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntry.java
opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntryInstall.java
opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManager.java
opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManagerAware.java
opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroup.java
opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupChangeListener.java
opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupConfig.java
opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupProvider.java
opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/Activator.java
opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerImpl.java
opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java
opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java
opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java
opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java
opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java
opendaylight/hosttracker/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java
opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java
opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java
opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTrackerCallable.java
opendaylight/hosttracker/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerTest.java
opendaylight/hosttracker/integrationtest/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerIT.java
opendaylight/hosttracker_new/api/pom.xml [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/Entity.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDevice.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceListener.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceService.java [new file with mode: 0755]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClass.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassListener.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassifierService.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/SwitchPort.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java [new file with mode: 0644]
opendaylight/hosttracker_new/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/pom.xml [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/AttachmentPoint.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DefaultEntityClassifier.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Device.java [new file with mode: 0755]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndex.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndexInterator.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIterator.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImpl.java [new file with mode: 0755]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceMultiIndex.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndex.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/IndexedEntity.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImplTest.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndexTest.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDevice.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDeviceManager.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifier.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifierMac.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockFlexEntityClassifier.java [new file with mode: 0644]
opendaylight/hosttracker_new/implementation/src/test/resources/logback.xml [new file with mode: 0644]
opendaylight/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/Activator.java
opendaylight/northbound/commons/pom.xml
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/package-info.java
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/utils/NorthboundUtils.java
opendaylight/northbound/flowprogrammer/enunciate.xml
opendaylight/northbound/flowprogrammer/pom.xml
opendaylight/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowConfigs.java
opendaylight/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthbound.java
opendaylight/northbound/flowprogrammer/src/main/resources/WEB-INF/web.xml
opendaylight/northbound/hosttracker/enunciate.xml
opendaylight/northbound/hosttracker/pom.xml
opendaylight/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthbound.java
opendaylight/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/Hosts.java
opendaylight/northbound/hosttracker/src/main/resources/WEB-INF/web.xml
opendaylight/northbound/integrationtest/pom.xml
opendaylight/northbound/integrationtest/src/test/java/org/opendaylight/controller/northbound/integrationtest/NorthboundIT.java
opendaylight/northbound/integrationtest/src/test/resources/tomcat-server.xml
opendaylight/northbound/staticrouting/enunciate.xml
opendaylight/northbound/staticrouting/pom.xml
opendaylight/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutes.java
opendaylight/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthbound.java
opendaylight/northbound/staticrouting/src/main/resources/WEB-INF/web.xml
opendaylight/northbound/statistics/enunciate.xml
opendaylight/northbound/statistics/pom.xml
opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllFlowStatistics.java
opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllPortStatistics.java
opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/FlowStatistics.java
opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/PortStatistics.java
opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthbound.java
opendaylight/northbound/statistics/src/main/resources/WEB-INF/web.xml
opendaylight/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetConfigs.java
opendaylight/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthboundJAXRS.java
opendaylight/northbound/subnets/src/main/resources/WEB-INF/web.xml
opendaylight/northbound/switchmanager/enunciate.xml
opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectors.java
opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/Nodes.java
opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java
opendaylight/northbound/switchmanager/src/main/resources/WEB-INF/web.xml
opendaylight/northbound/switchmanager/src/test/java/org/opendaylight/controller/switchmanager/northbound/SwitchManagerNorthboundTest.java
opendaylight/northbound/topology/enunciate.xml
opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/Topology.java
opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyNorthboundJAXRS.java
opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyUserLinks.java
opendaylight/northbound/topology/src/main/resources/WEB-INF/web.xml
opendaylight/northbound/topology/src/test/java/org/opendaylight/controller/topology/northbound/TopologyTest.java
opendaylight/northboundtest/unit_test_suite/pom.xml
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimInternalListener.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsManager.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IRefreshInternalProvider.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IStatisticsListener.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/ITopologyServiceShimListener.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IController.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageReadWrite.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitch.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/Controller.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/MessageReadWriteService.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/PriorityMessage.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SecureMessageReadWriteService.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DescStatisticsConverter.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DiscoveryService.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerNotifier.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerService.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowStatisticsConverter.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryService.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceHelper.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceShim.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/OFStatisticsManager.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortConverter.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortStatisticsConverter.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadServiceFilter.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServices.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Utils.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Error.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6FlowMod.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Match.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsReply.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsRequest.java
opendaylight/protocol_plugins/stub/pom.xml
opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/Activator.java
opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/FlowProgrammerService.java
opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/InventoryService.java
opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/ReadService.java
opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeConnectorFactory.java
opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeFactory.java
opendaylight/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementation.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Action.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Output.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/PushVlan.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlDst.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlSrc.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlType.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwDst.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwSrc.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwTos.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpDst.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpSrc.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanCfi.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanId.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanPcp.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRoleLevel.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/IResourceAuthorization.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/UserLevel.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Actions.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/AdvertisedBandwidth.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Bandwidth.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Buffers.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Capabilities.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ComponentActivatorAbstractBase.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Config.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerFlow.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/MacAddress.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/PeerBandwidth.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/SupportedBandwidth.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tables.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/discovery/IDiscoveryService.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/Flow.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerService.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginInFlowProgrammerService.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginOutFlowProgrammerService.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IListenInventoryUpdates.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginOutInventoryService.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/Match.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchField.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchType.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BitBufferHelper.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ICMP.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketException.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/RawPacket.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/DataLinkAddress.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/EthernetAddress.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/FlowOnNode.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeConnectorStatistics.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeDescription.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeTableStatistics.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IListenTopoUpdates.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginOutTopologyService.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/TopoEdgeUpdate.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/FilterIterator.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GlobalConstants.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/HexEncode.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IListener.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IPProtocols.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IterableIterator.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ListenerDispatcher.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/MultiIterator.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NetUtils.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/SingletonTask.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Status.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/StatusCode.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/authorization/AuthorizationTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/BitBufferHelperTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/FlowOnNodeTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeConnectorStatisticsTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeDescriptionTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/EtherTypesTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/HexEncodeTest.java
opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Activator.java
opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java
opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/FlowProgrammerService.java
opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Topology.java
opendaylight/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/DataPacketServiceTest.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-api/src/main/java/org/opendaylight/controller/sal/binding/generator/api/BindingGenerator.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/generator/impl/BindingGeneratorImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/BaseYangTypes.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/TypeProviderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/UnionDependencySort.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/AugmentRleativeXPathTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/AugmentedTypeTest.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/BinaryTypeTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenEnumResolvingTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenTypesSubSetTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GeneratedTypesTest.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/UnionTypeDefTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/abstract-topology@2013-02-08.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/augment-abstract-topology@2013-05-03.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/iana-if-type@2012-06-05.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-inet-types@2010-09-24.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-interfaces@2012-11-15.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-yang-types@2010-09-24.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-type-test.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-types@2013-06-13.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/abstract-topology@2013-02-08.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/ietf-inet-types@2010-09-24.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/abstract-topology.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/ietf-inet-types@2010-09-24.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-spi/src/main/java/org/opendaylight/controller/sal/binding/generator/spi/TypeProvider.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/AbstractBaseType.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/BindingGeneratorUtil.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/Types.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/GeneratedTOBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/ClassCodeGenerator.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/Constants.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/EnumGenerator.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/GeneratorJavaFile.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/GeneratorUtil.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/InterfaceGenerator.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/test/java/org/opendaylight/controller/sal/java/api/generator/test/ClassCodeGeneratorTest.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/test/java/org/opendaylight/controller/sal/java/api/generator/test/GeneratorJavaFileTest.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/test/resources/yang/abstract-topology@2013-02-08.yang
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/GeneratedTransferIdentityObject.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/WildcardType.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/GeneratedTOBuilder.java
opendaylight/sal/yang-prototype/code-generator/maven-sal-api-gen-plugin/src/main/java/org/opendaylight/controller/maven/sal/api/gen/plugin/CodeGeneratorImpl.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/java/org/opendaylight/controller/yang2sources/plugin/it/YangToSourcesPluginTestIT.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/AdditionalConfig/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/Correct/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/GenerateTest1/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/GenerateTest2/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/Generator/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/MissingYangInDep/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/NoGenerators/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/NoOutputDir/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/NoYangFiles/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/UnknownGenerator/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin-it/src/test/resources/YangRootNotExist/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/src/main/java/org/opendaylight/controller/yang2sources/plugin/ConfigArg.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/src/main/java/org/opendaylight/controller/yang2sources/plugin/Util.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/src/main/java/org/opendaylight/controller/yang2sources/plugin/YangToSourcesMojo.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/src/main/java/org/opendaylight/controller/yang2sources/plugin/YangToSourcesProcessor.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/src/test/java/org/opendaylight/controller/yang2sources/plugin/GenerateSourcesTest.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/src/test/java/org/opendaylight/controller/yang2sources/plugin/UtilTest.java
opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/src/test/resources/yang/mock.yang [moved from opendaylight/sal/yang-prototype/code-generator/maven-yang-plugin/src/test/resources/mock.yang with 100% similarity]
opendaylight/sal/yang-prototype/code-generator/maven-yang/pom.xml
opendaylight/sal/yang-prototype/code-generator/maven-yang/src/main/java/org/opendaylight/controller/yang2sources/spi/CodeGenerator.java
opendaylight/sal/yang-prototype/code-generator/maven-yang/src/test/java/org/opendaylight/controller/yang2sources/spi/CodeGeneratorTestImpl.java
opendaylight/sal/yang-prototype/code-generator/pom.xml
opendaylight/sal/yang-prototype/code-generator/samples/maven-code-gen-sample/src/main/yang/controller-network.yang
opendaylight/sal/yang-prototype/code-generator/samples/modeling-sample/pom.xml [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/samples/modeling-sample/src/main/yang/sample.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-api/pom.xml
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/pom.xml
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/api/DataNodeContainerBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/api/UsesNodeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/AugmentationSchemaBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/LeafSchemaNodeBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/ModuleBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/RpcDefinitionBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/TypeDefinitionBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/UsesNodeBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/impl/YangParserImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/impl/YangParserListenerImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/ParserUtils.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/TypeConstraints.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/YangModelBuilderUtil.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/java/org/opendaylight/controller/yang/parser/impl/TestUtils.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/java/org/opendaylight/controller/yang/parser/impl/TypesResolutionTest.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/java/org/opendaylight/controller/yang/parser/impl/YangParserNegativeTest.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/java/org/opendaylight/controller/yang/parser/impl/YangParserTest.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/model/testfile1.yang
opendaylight/sal/yang-prototype/yang/pom.xml
opendaylight/sal/yang-prototype/yang/yang-binding/pom.xml
opendaylight/sal/yang-prototype/yang/yang-binding/src/main/java/org/opendaylight/controller/yang/binding/BaseIdentity.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/yang/yang-common/pom.xml
opendaylight/sal/yang-prototype/yang/yang-common/src/main/java/org/opendaylight/controller/yang/common/QName.java
opendaylight/sal/yang-prototype/yang/yang-data-api/pom.xml
opendaylight/sal/yang-prototype/yang/yang-data-util/pom.xml
opendaylight/sal/yang-prototype/yang/yang-model-api/pom.xml
opendaylight/sal/yang-prototype/yang/yang-model-api/src/main/java/org/opendaylight/controller/yang/model/api/LeafSchemaNode.java
opendaylight/sal/yang-prototype/yang/yang-model-util/pom.xml
opendaylight/sal/yang-prototype/yang/yang-model-util/src/main/java/org/opendaylight/controller/yang/model/util/DataNodeIterator.java
opendaylight/sal/yang-prototype/yang/yang-model-util/src/main/java/org/opendaylight/controller/yang/model/util/ExtendedType.java
opendaylight/sal/yang-prototype/yang/yang-model-util/src/main/java/org/opendaylight/controller/yang/model/util/SchemaContextUtil.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/ConfigManager.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/IConfigManager.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBConst.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBUtil.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Client.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Pool.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/PoolMember.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/VIP.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/Activator.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerService.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/ILoadBalancingPolicy.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RandomLBPolicy.java
opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RoundRobinLBPolicy.java
opendaylight/samples/loadbalancer/src/test/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerTest.java
opendaylight/samples/northbound/loadbalancer/enunciate.xml
opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/LoadBalancerNorthbound.java
opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/NBConst.java
opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/Pools.java
opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/VIPs.java
opendaylight/samples/northbound/loadbalancer/src/main/resources/WEB-INF/web.xml
opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleForwardingImpl.java
opendaylight/statisticsmanager/api/pom.xml
opendaylight/statisticsmanager/api/src/main/java/org/opendaylight/controller/statisticsmanager/IStatisticsManager.java
opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/IInventoryListener.java
opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISpanAware.java
opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManager.java
opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Switch.java
opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SwitchConfig.java
opendaylight/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SwitchTest.java
opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerImpl.java
opendaylight/switchmanager/integrationtest/pom.xml
opendaylight/topologymanager/src/main/java/org/opendaylight/controller/topologymanager/TopologyUserLinkConfig.java
opendaylight/topologymanager/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java
opendaylight/topologymanager/src/test/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImplTest.java
opendaylight/usermanager/api/pom.xml [moved from opendaylight/usermanager/pom.xml with 95% similarity]
opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthResponse.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/AuthResponse.java with 100% similarity]
opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthorizationConfig.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/internal/AuthorizationConfig.java with 89% similarity]
opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java with 98% similarity]
opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java with 98% similarity]
opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java with 92% similarity]
opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java with 89% similarity]
opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ServerConfig.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/internal/ServerConfig.java with 94% similarity]
opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/UserConfig.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/internal/UserConfig.java with 98% similarity]
opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthResponseTest.java [moved from opendaylight/usermanager/src/test/java/org/opendaylight/controller/usermanager/AuthResponseTest.java with 99% similarity]
opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthorizationUserConfigTest.java [moved from opendaylight/usermanager/src/test/java/org/opendaylight/controller/usermanager/internal/AuthorizationUserConfigTest.java with 96% similarity]
opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/ServerConfigTest.java [moved from opendaylight/usermanager/src/test/java/org/opendaylight/controller/usermanager/internal/ServerConfigTest.java with 82% similarity]
opendaylight/usermanager/implementation/pom.xml [new file with mode: 0644]
opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/Activator.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/internal/Activator.java with 100% similarity]
opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/AuthenticatedUser.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/internal/AuthenticatedUser.java with 100% similarity]
opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/UserManagerImpl.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/internal/UserManagerImpl.java with 92% similarity]
opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/SessionManager.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/security/SessionManager.java with 97% similarity]
opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/UserSecurityContextRepository.java [moved from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/security/UserSecurityContextRepository.java with 100% similarity]
opendaylight/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/AuthenticatedUserTest.java [new file with mode: 0644]
opendaylight/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java [moved from opendaylight/usermanager/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java with 88% similarity]
opendaylight/usermanager/src/test/java/org/opendaylight/controller/usermanager/internal/AuthenticatedUserTest.java [deleted file]
opendaylight/web/devices/src/main/resources/WEB-INF/Devices-servlet.xml
opendaylight/web/devices/src/main/resources/WEB-INF/web.xml
opendaylight/web/flows/src/main/java/org/opendaylight/controller/flows/web/Flows.java
opendaylight/web/flows/src/main/resources/WEB-INF/Flows-servlet.xml
opendaylight/web/flows/src/main/resources/WEB-INF/web.xml
opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebAdmin.java
opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebUtil.java
opendaylight/web/root/src/main/java/org/opendaylight/controller/web/IDaylightWeb.java
opendaylight/web/root/src/main/resources/WEB-INF/RootGUI-servlet.xml
opendaylight/web/root/src/main/resources/WEB-INF/spring/servlet/security.xml
opendaylight/web/root/src/main/resources/WEB-INF/web.xml
opendaylight/web/topology/src/main/java/org/opendaylight/controller/topology/web/Topology.java
opendaylight/web/topology/src/main/resources/WEB-INF/Topology-servlet.xml
opendaylight/web/topology/src/main/resources/WEB-INF/web.xml
opendaylight/web/topology/src/test/java/org/opendaylight/controller/topology/web/TopologyTest.java
opendaylight/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/Troubleshoot.java
opendaylight/web/troubleshoot/src/main/resources/WEB-INF/Troubleshoot-servlet.xml
opendaylight/web/troubleshoot/src/main/resources/WEB-INF/web.xml

index b92845c8d76fafd514451b1c3dae3e1cbc6f2d4c..d1b82619fd423994f595239f7103389f1534a5eb 100644 (file)
@@ -12,3 +12,4 @@ target
 .project
 .settings
 MANIFEST.MF
+opendaylight/northbound/integrationtest/logs/*
index 5a6641c6857b40a821ea58a5c29202fb8cdb978d..19c8b4d35bd39f8a1c4ad516911ad149cfc5d9a0 100644 (file)
@@ -16,14 +16,14 @@ import org.junit.Assert;
 import org.junit.Test;\r
 \r
 public class ArphandlerTest extends TestCase {\r
-        \r
-       @Test\r
-       public void testArphandlerCreation() {\r
-                       \r
-               ArpHandler ah = null;\r
-               ah = new ArpHandler();\r
-               Assert.assertTrue(ah != null);\r
-                       \r
-       }\r
+\r
+        @Test\r
+        public void testArphandlerCreation() {\r
+\r
+                ArpHandler ah = null;\r
+                ah = new ArpHandler();\r
+                Assert.assertTrue(ah != null);\r
+\r
+        }\r
 \r
 }\r
index 460b09e9dad81856dc5dde0892e073fdf8b2f7f6..52c568203be917dd42c347afbb616b9f907c5b9c 100644 (file)
@@ -32,7 +32,7 @@
       <artifactId>sal.implementation</artifactId>
       <version>0.4.0-SNAPSHOT</version>
     </dependency>
-       <dependency>
+    <dependency>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>clustering.services-implementation</artifactId>
       <version>0.4.0-SNAPSHOT</version>
index 2d63ce57448f88b77a39b1bcb0525b9721c08370..6d9dfda9a365f9a08f9d4ba5b7733f2cb6340ba6 100644 (file)
@@ -1,5 +1,4 @@
 <configuration scan="true">
-
   <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
     <encoder>
       <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
index 03a9b4d93e4ad17c89f41976c9a33a3d20bfc359..2aa3fdb849b6fb02a65eeb5a626ec293a1fd8817 100644 (file)
@@ -19,7 +19,7 @@
     <!--
         Used to register JMX statistics in any available MBean server
     -->
-    <jmxStatistics enabled="true"/>    
+    <jmxStatistics enabled="true"/>
   </default>
   <!-- transactionManagerLookupClass="org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup" -->
   <namedCache name="transactional-type">
index fa00c7f455f90d0b9e1b883dc4c39ea851cb4c59..1142909f8562844075b3cbbf475b2a65d016738e 100644 (file)
@@ -17,51 +17,51 @@ import junit.framework.TestCase;
 \r
 public class TestClusteringTest extends TestCase {\r
 \r
-       @Test\r
-       public void testComplexClass() {\r
-               ComplexClass cc = new ComplexClass("cplxc1");\r
-               Assert.assertTrue(cc.whoAmI().equals("ComplexClass_cplxc1"));\r
-               cc.IAm("cplxc2");\r
-               Assert.assertTrue(cc.whoAmI().equals("ComplexClass_cplxc2"));\r
-       }\r
-               \r
-       @Test\r
-       public void testComplexClass1() {\r
-               ComplexClass1 cc1 = new ComplexClass1("cplxc1a");\r
-               Assert.assertTrue(cc1.whoAmI().equals("ComplexClass1_cplxc1a"));\r
-               cc1.IAm("cplxc1b");\r
-               Assert.assertTrue(cc1.whoAmI().equals("ComplexClass1_cplxc1b"));\r
-       }\r
-               \r
-               \r
-       @Test\r
-       public void testComplexContainer() {\r
-               ComplexContainer cplxcontnr1 = new ComplexContainer("cct1", 5);\r
-               Assert.assertTrue(cplxcontnr1.getIdentity().equals("[ComplexClass_cct1]-[ComplexClass1_cct1]"));\r
-               Assert.assertTrue(cplxcontnr1.getState() == 5);\r
-               \r
-               cplxcontnr1.setIdentity("cct2");\r
-               Assert.assertTrue(cplxcontnr1.getIdentity().equals("[ComplexClass_cct2]-[ComplexClass1_cct2]"));\r
-               \r
-               Assert.assertTrue(cplxcontnr1.toString().equals(\r
-                               "{ID:[ComplexClass_cct2]-[ComplexClass1_cct2],STATE:5}"));\r
-       }\r
-               \r
-       @Test\r
-       public void testStringContainer() {\r
-               StringContainer strcontainer1 = new StringContainer();\r
-               Assert.assertTrue(strcontainer1.getMystring() == null);\r
-               Assert.assertTrue(strcontainer1.hashCode() == 0);\r
-               \r
-               StringContainer strcontainer2 = new StringContainer("foo");\r
-               Assert.assertTrue(strcontainer2.getMystring() != null);\r
-               Assert.assertTrue(strcontainer2.hashCode() != 0);\r
-               \r
-               strcontainer1.setMystring("foo");\r
-               Assert.assertTrue(strcontainer2.equals(strcontainer1));\r
-               \r
-               Assert.assertTrue(strcontainer2.toString().equals("{foo}"));\r
-       }\r
-               \r
+        @Test\r
+        public void testComplexClass() {\r
+                ComplexClass cc = new ComplexClass("cplxc1");\r
+                Assert.assertTrue(cc.whoAmI().equals("ComplexClass_cplxc1"));\r
+                cc.IAm("cplxc2");\r
+                Assert.assertTrue(cc.whoAmI().equals("ComplexClass_cplxc2"));\r
+        }\r
+\r
+        @Test\r
+        public void testComplexClass1() {\r
+                ComplexClass1 cc1 = new ComplexClass1("cplxc1a");\r
+                Assert.assertTrue(cc1.whoAmI().equals("ComplexClass1_cplxc1a"));\r
+                cc1.IAm("cplxc1b");\r
+                Assert.assertTrue(cc1.whoAmI().equals("ComplexClass1_cplxc1b"));\r
+        }\r
+\r
+\r
+        @Test\r
+        public void testComplexContainer() {\r
+                ComplexContainer cplxcontnr1 = new ComplexContainer("cct1", 5);\r
+                Assert.assertTrue(cplxcontnr1.getIdentity().equals("[ComplexClass_cct1]-[ComplexClass1_cct1]"));\r
+                Assert.assertTrue(cplxcontnr1.getState() == 5);\r
+\r
+                cplxcontnr1.setIdentity("cct2");\r
+                Assert.assertTrue(cplxcontnr1.getIdentity().equals("[ComplexClass_cct2]-[ComplexClass1_cct2]"));\r
+\r
+                Assert.assertTrue(cplxcontnr1.toString().equals(\r
+                                "{ID:[ComplexClass_cct2]-[ComplexClass1_cct2],STATE:5}"));\r
+        }\r
+\r
+        @Test\r
+        public void testStringContainer() {\r
+                StringContainer strcontainer1 = new StringContainer();\r
+                Assert.assertTrue(strcontainer1.getMystring() == null);\r
+                Assert.assertTrue(strcontainer1.hashCode() == 0);\r
+\r
+                StringContainer strcontainer2 = new StringContainer("foo");\r
+                Assert.assertTrue(strcontainer2.getMystring() != null);\r
+                Assert.assertTrue(strcontainer2.hashCode() != 0);\r
+\r
+                strcontainer1.setMystring("foo");\r
+                Assert.assertTrue(strcontainer2.equals(strcontainer1));\r
+\r
+                Assert.assertTrue(strcontainer2.toString().equals("{foo}"));\r
+        }\r
+\r
 \r
 }\r
index 802b00e5ccea5bad4268c0a2661b21054d4321db..9f3107d1a8fb666102a069b1daf625484d7e3ec2 100644 (file)
           <manifestLocation>${project.basedir}/META-INF</manifestLocation>\r
         </configuration>\r
       </plugin>\r
+      <plugin>\r
+        <groupId>org.apache.maven.plugins</groupId>\r
+        <artifactId>maven-checkstyle-plugin</artifactId>\r
+        <version>${checkstyle.version}</version>\r
+        <configuration>\r
+          <failsOnError>true</failsOnError>\r
+          <configLocation>${project.parent.parent.basedir}/space_and_tabs_checks.xml</configLocation>\r
+        </configuration>\r
+      </plugin>\r
     </plugins>\r
   </build>\r
   <dependencies>\r
index 9d34dfb8a7d99fafe33806b6748abe41f63f31bc..9e9774e26601891bf215cb5b6994f151c10b7f8d 100644 (file)
@@ -12,7 +12,7 @@ package org.opendaylight.controller.concepts.transform;
 public interface Acceptor<I> {\r
 \r
     /**\r
-     * \r
+     *\r
      * @param input\r
      * @return true if input is accepted.\r
      */\r
index 23bcb563d38844df20971e56e89c03b994116a7b..061a57fc15831b942d952084eb2ad9731a2b24cf 100644 (file)
@@ -10,7 +10,7 @@ package org.opendaylight.controller.concepts.transform;
 \r
 import java.util.Collection;\r
 /**\r
- * \r
+ *\r
  * @author Tony Tkacik\r
  *\r
  * @param <I>\r
index fa6408d3d11ce89ea463c02a14a886aa1b573808..dae949912b96cfe564e018e2b99146597d26d626 100644 (file)
@@ -17,26 +17,26 @@ import java.util.concurrent.ConcurrentHashMap;
 /**\r
  * Transformer which aggregates multiple implementations of\r
  * {@link InputClassBasedTransformer}.\r
- * \r
+ *\r
  * The transformation process is driven by {@link Class} of input. The selection\r
  * of used {@link InputClassBasedTransformer} is done by using the {@link Class}\r
  * of input as a key to select the transformer.\r
- * \r
+ *\r
  * This approach provides quick resolution of transformer, but does not support\r
  * registering a super type of input to provide transformation support for all\r
  * subclasses, one must register a new instance of transformer for each valid\r
  * input class.\r
- * \r
+ *\r
  * If you need more flexible selection of transformation consider using\r
  * {@link CompositeConditionalTransformer} which is slower but most flexible or\r
  * {@link RuleBasedTransformer} which provides declarative approach for\r
  * transformation.\r
- * \r
+ *\r
  * See {@link #transform(Object)} for more information about tranformation\r
  * process.\r
- * \r
+ *\r
  * @author Tony Tkacik <ttkacik@cisco.com>\r
- * \r
+ *\r
  * @param <I>\r
  *            Input super-type\r
  * @param <P>\r
@@ -50,18 +50,18 @@ public abstract class CompositeClassBasedTransformer<I, P> implements
 \r
     /**\r
      * Transforms an input into instance of Product class.\r
-     * \r
+     *\r
      * The final registered transformer is the one which match following\r
      * condition:\r
-     * \r
+     *\r
      * <code>input.getClass() == transformer.getInputClass()</code>\r
-     * \r
+     *\r
      * This means that transformers are not resolved by class hierarchy, only\r
      * selected based on final class of the input. If you need more flexible\r
      * selection of transformation consider using\r
      * {@link CompositeConditionalTransformer} which is slower but more\r
      * flexible.\r
-     * \r
+     *\r
      */\r
     @Override\r
     public P transform(I input) {\r
@@ -76,11 +76,11 @@ public abstract class CompositeClassBasedTransformer<I, P> implements
 \r
     /**\r
      * Registers a new transformer.\r
-     * \r
+     *\r
      * The transformer is registered for class returned by\r
      * {@link InputClassBasedTransformer#getInputClass()}. Only one transformer\r
      * can be registered for particular input class.\r
-     * \r
+     *\r
      */\r
     public void addTransformer(\r
             InputClassBasedTransformer<I, ? extends I, P> transformer)\r
@@ -95,9 +95,9 @@ public abstract class CompositeClassBasedTransformer<I, P> implements
 \r
     /**\r
      * Removes an registered transformer.\r
-     * \r
+     *\r
      * Note: Removal is currently unsupported.\r
-     * \r
+     *\r
      * @param transformer\r
      *            Tranformer to be removed.\r
      * @throws IllegalArgumentException\r
@@ -108,7 +108,7 @@ public abstract class CompositeClassBasedTransformer<I, P> implements
             throws IllegalArgumentException {\r
         throw new UnsupportedOperationException("Not implemented yet");\r
     }\r
-    \r
+\r
     @Override\r
     public Collection<P> transformAll(Collection<? extends I> inputs) {\r
         Collection<P> ret = new ArrayList<P>();\r
index 3e6b39abf529abb28e16797017214094b2d7341a..1ad849bddc1de9e78989d96cfddae8216f6b5ab5 100644 (file)
@@ -10,15 +10,15 @@ package org.opendaylight.controller.concepts.transform;
 \r
 /**\r
  * Input class based transformer\r
- * \r
+ *\r
  * {@link Transformer} which accepts / transforms only specific classes of\r
  * input, and is useful if the selection of transformer should be based on the\r
  * class of the input and there is one-to-one mapping between input class and\r
  * transformer.\r
- * \r
- * \r
+ *\r
+ *\r
  * @author Tony Tkacik\r
- * \r
+ *\r
  * @param <S>\r
  *            Common supertype of input\r
  * @param <I>\r
@@ -31,7 +31,7 @@ public interface InputClassBasedTransformer<S, I extends S, P> extends
 \r
     /**\r
      * Returns an {@link Class} of input which is acceptable for transformation.\r
-     * \r
+     *\r
      * @return {@link Class} of input which is acceptable for transformation.\r
      */\r
     Class<? extends S> getInputClass();\r
index 9f717eaa5bff4a9f63d54f8b9009d10f21a2fcca..820b94a7acd15d1bb0944b16a25e32b930068825 100644 (file)
@@ -12,15 +12,15 @@ import java.util.Set;
 \r
 /**\r
  * Transformer with set of acceptance rules\r
- * \r
+ *\r
  * The transformer provides a set of {@link Acceptor}s, which could be used to\r
  * verify if the input will produce result using the transformer.\r
- * \r
+ *\r
  * The transormer is able to produce result if ANY of associated\r
  * {@link Acceptor}s accepted result.\r
- * \r
+ *\r
  * @author Tony Tkacik\r
- * \r
+ *\r
  * @param <I>\r
  *            Input class for transformation\r
  * @param <P>\r
@@ -31,10 +31,10 @@ public interface RuleBasedTransformer<I, P> extends Transformer<I, P> {
     /**\r
      * Set of {@link Acceptor}, which could be used to verify if the input is\r
      * usable by transformer.\r
-     * \r
+     *\r
      * The transformer is able to produce result if ANY of associated\r
      * {@link Acceptor}s accepted result.\r
-     * \r
+     *\r
      * @return Set of input acceptance rules associated to this transformer.\r
      */\r
     Set<Acceptor<I>> getRules();\r
index 81e43c39d1955cb54485c8977617a98055ea164f..4d0aa03e15cfda28584d4830948e07803dea8bcc 100644 (file)
@@ -10,15 +10,15 @@ package org.opendaylight.controller.concepts.transform;
 \r
 /**\r
  * Simple condition-based transformer\r
- * \r
+ *\r
  * The transformer provides {@link #isAcceptable(Object)} method,\r
  * which could be used to query transformer if the input will produce\r
  * result.\r
- * \r
+ *\r
  * This interface is simplified version of {@link RuleBasedTransformer} - does not\r
  * provide decoupling of Acceptance rule from transformer, and should be used only\r
  * for simple use-cases.\r
- *  \r
+ *\r
  * @author Tony Tkacik\r
  *\r
  * @param <I> Input class for transformation\r
@@ -28,9 +28,9 @@ public interface SimpleConditionalTransformer<I,P> extends Transformer<I, P>, Ac
 \r
 \r
     /**\r
-     * Checks if the input is acceptable \r
+     * Checks if the input is acceptable\r
      * for processing by the transformer.\r
-     * \r
+     *\r
      * @return true it the input is acceptable for processing by transformer.\r
      */\r
     @Override\r
index f80ccfffd84f6369e003bb0e6b177ddda9a15531..18184e122acd1f3e9e0718c2ace54d893c619cea 100644 (file)
@@ -10,7 +10,7 @@ package org.opendaylight.controller.concepts.transform;
 \r
 /**\r
  * Factory which produces product based on input object\r
- * \r
+ *\r
  * @author Tony Tkacik\r
  *\r
  * @param <I> Input\r
@@ -19,7 +19,7 @@ package org.opendaylight.controller.concepts.transform;
 public interface Transformer<I,P> {\r
     /**\r
      * Transforms input into instance of product.\r
-     * \r
+     *\r
      * @param input Input which drives transformation\r
      * @return Instance of product which was created from supplied input.\r
      */\r
index a438ad8393a01cafb336bdb8ef048643d190ea42..89dbb77ecdef2e178d2cdb1898fc3a6fcf5a6b98 100644 (file)
       <version>0.8.0.v201110170705</version>
     </dependency>
   </dependencies>
-  
+
   <build>
     <plugins>
       <plugin>
        <groupId>org.ops4j.pax.exam</groupId>
        <artifactId>maven-paxexam-plugin</artifactId>
+       <version>1.2.4</version>
         <executions>
           <execution>
             <id>generate-config</id>
           </execution>
         </executions>
       </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <version>${checkstyle.version}</version>
+        <configuration>
+          <failsOnError>true</failsOnError>
+          <configLocation>${project.parent.parent.basedir}/space_and_tabs_checks.xml</configLocation>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>properties-maven-plugin</artifactId>
+        <version>${propertymavenplugin.version}</version>
+        <executions>
+          <execution>
+            <goals>
+              <goal>set-system-properties</goal>
+            </goals>
+            <configuration>
+              <properties>
+                <property>
+                  <name>logback.configurationFile</name>
+                  <value>${project.parent.parent.basedir}/logback.xml</value>
+                </property>
+              </properties>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
     </plugins>
   </build>
 </project>
index 043ceef3293cbcc99c9b6e37f972bc34d8619bb4..05e607573e72d9fde8df6d67fbfb0e602073899e 100644 (file)
@@ -1,11 +1,11 @@
 <configuration scan="true">
-  
+
   <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
     <encoder>
       <pattern>%date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n</pattern>
     </encoder>
   </appender>
-  
+
   <root level="error">
     <appender-ref ref="STDOUT" />
   </root>
index 9814b5f91cf1ed0e7d535588cf17cd44329f25f4..142c9d5d6cc44c24d553ac0f89b9b5a2101de706 100644 (file)
@@ -9,10 +9,16 @@
   <artifactId>commons.opendaylight</artifactId>
   <version>1.4.0-SNAPSHOT</version>
   <packaging>pom</packaging>
+  <parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>commons.parent</artifactId>
+    <version>1.0.0-SNAPSHOT</version>
+    <relativePath>../parent</relativePath>
+  </parent>
 
   <properties>
+    <propertymavenplugin.version>1.0-alpha-2</propertymavenplugin.version>
     <sonar.host.url>https://sonar.opendaylight.org/</sonar.host.url>
-    <nexusproxy>http://nexus.opendaylight.org/content</nexusproxy>
     <sitedeploy>dav:http://nexus.opendaylight.org/content/sites/site</sitedeploy>
     <siteplugin>3.2</siteplugin>
     <projectinfo>2.6</projectinfo>
@@ -32,6 +38,7 @@
     <jersey.version>1.17</jersey.version>
     <virgo.version>3.6.0.RELEASE</virgo.version>
     <geminiweb.version>2.2.0.RELEASE</geminiweb.version>
+    <checkstyle.version>2.10</checkstyle.version>
   </properties>
 
   <pluginRepositories>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-checkstyle-plugin</artifactId>
-        <version>2.10</version>
+        <version>${checkstyle.version}</version>
       </plugin>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
       <plugin>
         <groupId>org.codehaus.mojo</groupId>
         <artifactId>properties-maven-plugin</artifactId>
-        <version>1.0-alpha-2</version>
+        <version>${propertymavenplugin.version}</version>
         <executions>
           <execution>
             <goals>
               <properties>
                 <property>
                   <name>logback.configurationFile</name>
-                  <value>${project.parent.relativePath}/logback.xml</value>
+                  <value>${project.parent.basedir}/logback.xml</value>
                 </property>
               </properties>
             </configuration>
           <compilerSource>1.6</compilerSource>
           <compilerCompliance>1.6</compilerCompliance>
           <compilerTargetPlatform>1.6</compilerTargetPlatform>
-          <configFile>${project.parent.relativePath}/sun_coding_style.xml</configFile>
+          <configFile>${project.parent.basedir}/sun_coding_style.xml</configFile>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <version>${checkstyle.version}</version>
+        <executions>
+          <execution>
+            <phase>process-sources</phase>
+            <goals>
+              <goal>check</goal>
+            </goals>
+          </execution>
+        </executions>
+        <configuration>
+          <failsOnError>true</failsOnError>
+          <configLocation>${project.parent.basedir}/space_and_tabs_checks.xml</configLocation>
+          <consoleOutput>true</consoleOutput>
+          <includeTestSourceDirectory>true</includeTestSourceDirectory>
+          <sourceDirectory>${project.basedir}</sourceDirectory>
+          <includes>**\/*.java,**\/*.xml,**\/*.ini,**\/*.sh,**\/*.bat</includes>
         </configuration>
       </plugin>
       <plugin>
                   </action>
                 </pluginExecution>
                 <pluginExecution>
-                       <pluginExecutionFilter>
-                               <groupId>org.ops4j.pax.exam</groupId>
-                               <artifactId>maven-paxexam-plugin</artifactId>
-                               <versionRange>[1.2.4,)</versionRange>
-                               <goals>
-                                       <goal>generate-depends-file</goal>
-                               </goals>
-                       </pluginExecutionFilter>
-                       <action>
-                               <ignore></ignore>
-                       </action>
+                  <pluginExecutionFilter>
+                    <groupId>org.ops4j.pax.exam</groupId>
+                    <artifactId>maven-paxexam-plugin</artifactId>
+                    <versionRange>[1.2.4,)</versionRange>
+                    <goals>
+                      <goal>generate-depends-file</goal>
+                    </goals>
+                  </pluginExecutionFilter>
+                  <action>
+                    <ignore/>
+                  </action>
+                </pluginExecution>
+                <pluginExecution>
+                  <pluginExecutionFilter>
+                    <groupId>org.apache.maven.plugins</groupId>
+                    <artifactId>maven-checkstyle-plugin</artifactId>
+                    <versionRange>[2.0,)</versionRange>
+                    <goals>
+                      <goal>check</goal>
+                    </goals>
+                  </pluginExecutionFilter>
+                  <action>
+                    <ignore/>
+                  </action>
                 </pluginExecution>
               </pluginExecutions>
             </lifecycleMappingMetadata>
diff --git a/opendaylight/commons/opendaylight/space_and_tabs_checks.xml b/opendaylight/commons/opendaylight/space_and_tabs_checks.xml
new file mode 100644 (file)
index 0000000..49a5802
--- /dev/null
@@ -0,0 +1,17 @@
+<?xml version="1.0"?>\r
+<!DOCTYPE module PUBLIC\r
+    "-//Puppy Crawl//DTD Check Configuration 1.2//EN"\r
+    "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">\r
+\r
+<module name="Checker">\r
+    <module name="FileTabCharacter">\r
+        <property name="eachLine" value="true"/>\r
+    </module>\r
+\r
+    <module name="RegexpSingleline">\r
+        <!-- \s matches whitespace character, $ matches end of line. -->\r
+        <property name="format" value="\s+$"/>\r
+        <property name="message" value="Line has trailing spaces."/>\r
+    </module>\r
+\r
+</module>\r
diff --git a/opendaylight/commons/parent/README b/opendaylight/commons/parent/README
new file mode 100644 (file)
index 0000000..4560dd4
--- /dev/null
@@ -0,0 +1,10 @@
+This contains a dummy parent project. The use case of this is for
+example the maven-checkstyle plugin call in commons/opendaylight in
+there the plugin references the spaces_tabs_checks.xml from the
+parent, it works well for all the childs of commons/opendaylight
+artifact but when trying to deploy that one itself it breaks because
+the plugin section will still refer to the parent when there is no
+parent.
+This fake parents allow to still set a parent for the
+commons/opendaylight even if pretty much empty or limited to the bare
+minimum and yet allow the commons/opendaylight to reference a parent.
diff --git a/opendaylight/commons/parent/logback.xml b/opendaylight/commons/parent/logback.xml
new file mode 100644 (file)
index 0000000..05e6075
--- /dev/null
@@ -0,0 +1,12 @@
+<configuration scan="true">
+
+  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+    <encoder>
+      <pattern>%date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n</pattern>
+    </encoder>
+  </appender>
+
+  <root level="error">
+    <appender-ref ref="STDOUT" />
+  </root>
+</configuration>
diff --git a/opendaylight/commons/parent/pom.xml b/opendaylight/commons/parent/pom.xml
new file mode 100644 (file)
index 0000000..a3fb6b4
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+  <prerequisites>
+    <maven>3.0</maven>
+  </prerequisites>
+  <groupId>org.opendaylight.controller</groupId>
+  <artifactId>commons.parent</artifactId>
+  <version>1.0.0-SNAPSHOT</version>
+  <packaging>pom</packaging>
+
+  <properties>
+    <nexusproxy>http://nexus.opendaylight.org/content</nexusproxy>
+  </properties>
+  <distributionManagement>
+    <!-- OpenDayLight Released artifact -->
+    <repository>
+      <id>opendaylight-release</id>
+      <url>${nexusproxy}/repositories/opendaylight.release/</url>
+    </repository>
+    <!-- OpenDayLight Snapshot artifact -->
+    <snapshotRepository>
+      <id>opendaylight-snapshot</id>
+      <url>${nexusproxy}/repositories/opendaylight.snapshot/</url>
+    </snapshotRepository>
+    <!-- Site deployment -->
+    <site>
+      <id>website</id>
+      <url>${sitedeploy}</url>
+    </site>
+  </distributionManagement>
+</project>
diff --git a/opendaylight/commons/parent/space_and_tabs_checks.xml b/opendaylight/commons/parent/space_and_tabs_checks.xml
new file mode 100644 (file)
index 0000000..49a5802
--- /dev/null
@@ -0,0 +1,17 @@
+<?xml version="1.0"?>\r
+<!DOCTYPE module PUBLIC\r
+    "-//Puppy Crawl//DTD Check Configuration 1.2//EN"\r
+    "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">\r
+\r
+<module name="Checker">\r
+    <module name="FileTabCharacter">\r
+        <property name="eachLine" value="true"/>\r
+    </module>\r
+\r
+    <module name="RegexpSingleline">\r
+        <!-- \s matches whitespace character, $ matches end of line. -->\r
+        <property name="format" value="\s+$"/>\r
+        <property name="message" value="Line has trailing spaces."/>\r
+    </module>\r
+\r
+</module>\r
diff --git a/opendaylight/commons/parent/sun_coding_style.xml b/opendaylight/commons/parent/sun_coding_style.xml
new file mode 100644 (file)
index 0000000..f4516b9
--- /dev/null
@@ -0,0 +1,291 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<profiles version="12">
+<profile kind="CodeFormatterProfile" name="SunCodingStyle" version="12">
+<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
+<setting id="org.eclipse.jdt.core.compiler.source" value="1.7"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="8"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="0"/>
+<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
+<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.7"/>
+<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.7"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
+</profile>
+</profiles>
index 3d0c5659d682c96ac874f90ffa43e410abc561d9..9fb0c23b365de5987d56434e698cbeed07861f71 100644 (file)
@@ -51,9 +51,9 @@ public class ConfigurationContainerImpl implements
     }
 
     public int getConfigurationAwareListSize() {
-       return this.configurationAwareList.size();
+        return this.configurationAwareList.size();
     }
-    
+
     public void removeConfigurationContainerAware(
             IConfigurationContainerAware configurationAware) {
         this.configurationAwareList.remove(configurationAware);
@@ -88,16 +88,16 @@ public class ConfigurationContainerImpl implements
 
             Status status = configurationAware.saveConfiguration();
             if (!status.isSuccess()) {
-               success = false;
-               logger.info("Failed to save config for {}",
-                               configurationAware.getClass().getSimpleName());
+                success = false;
+                logger.info("Failed to save config for {}",
+                                configurationAware.getClass().getSimpleName());
             }
         }
         if (success) {
             return new Status(StatusCode.SUCCESS, null);
         } else {
             return new Status(StatusCode.INTERNALERROR,
-                       "Failed to Save All Configurations");
+                        "Failed to Save All Configurations");
         }
     }
 
index ee15b4a9c2bc9f9822d40347dcee5eeb72212c55..20821f10282b038c19202a0f2c9d82839072b08b 100644 (file)
@@ -41,11 +41,11 @@ public class ConfigurationImpl implements IConfigurationService {
     private Set<IConfigurationAware> configurationAwareList = (Set<IConfigurationAware>) Collections
             .synchronizedSet(new HashSet<IConfigurationAware>());
 
-    
+
     public int getConfigurationAwareListSize() {
-       return this.configurationAwareList.size();
+        return this.configurationAwareList.size();
     }
-    
+
     public void addConfigurationAware(IConfigurationAware configurationAware) {
         if (!this.configurationAwareList.contains(configurationAware)) {
             this.configurationAwareList.add(configurationAware);
@@ -81,18 +81,18 @@ public class ConfigurationImpl implements IConfigurationService {
     public Status saveConfigurations() {
         boolean success = true;
         for (IConfigurationAware configurationAware : configurationAwareList) {
-               Status status = configurationAware.saveConfiguration();
+                Status status = configurationAware.saveConfiguration();
             if (!status.isSuccess()) {
-               success = false;
-               logger.info("Failed to save config for {}",
-                               configurationAware.getClass().getName());
+                success = false;
+                logger.info("Failed to save config for {}",
+                                configurationAware.getClass().getName());
             }
         }
         if (success) {
             return new Status(StatusCode.SUCCESS, null);
         } else {
             return new Status(StatusCode.INTERNALERROR,
-                       "Failed to Save All Configurations");
+                        "Failed to Save All Configurations");
         }
     }
 
index e93b467b9af9cb9e606f740d2e6b4054bbf6b614..c9dd5e2f397511fd81e9024aaa5ac0a1e2351ccf 100644 (file)
@@ -22,11 +22,11 @@ import org.opendaylight.controller.sal.utils.Status;
 
 public class ConfigurationAwareTest implements
 IConfigurationAware {
-       
-       @Override
-       public Status saveConfiguration() {
-               return null;
-       }
+
+        @Override
+        public Status saveConfiguration() {
+                return null;
+        }
 
 
 }
index 52f3776e6dcde888f8a7121b2ebafa4c3a25a9c2..c5d6bdc5d685a796d2388a87fb001d67c085fa36 100644 (file)
@@ -23,13 +23,13 @@ import org.opendaylight.controller.sal.utils.Status;
 public class ConfigurationContainerAwareTest implements
          IConfigurationContainerAware {
 
-       
-       
-       
-       @Override
-       public Status saveConfiguration() {
-               return null;
-       }
-       
-       
+
+
+
+        @Override
+        public Status saveConfiguration() {
+                return null;
+        }
+
+
 }
index 1d704a1937a6345c964553156e845c4ad4c8ed03..a82a9f23d8fcbdad031bf2c6e1da86f32960cada 100644 (file)
@@ -14,52 +14,51 @@ import org.opendaylight.controller.configuration.IConfigurationContainerAware;
 
 
 
-public class ConfigurationContainerImplTest { 
-       
-
-       @Test
-       public void testAddRemoveSaveConfiguration() {
-               
-               ConfigurationContainerImpl configurationContainerImpl = new ConfigurationContainerImpl();
-               IConfigurationContainerAware testConfigurationContainerAware = new ConfigurationContainerAwareTest();
-               
-               configurationContainerImpl.addConfigurationContainerAware(testConfigurationContainerAware);
-               configurationContainerImpl.addConfigurationContainerAware(testConfigurationContainerAware);
-               
-               Assert.assertEquals(1, configurationContainerImpl.getConfigurationAwareListSize());
-               
-               IConfigurationContainerAware testConfigurationAware1 = new ConfigurationContainerAwareTest();
-               configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware1);
-               
-               Assert.assertEquals(2, configurationContainerImpl.getConfigurationAwareListSize());
-               
-               IConfigurationContainerAware testConfigurationAware2 = new ConfigurationContainerAwareTest();
-               configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware2);
-               
-               Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
-               
-               IConfigurationContainerAware testConfigurationAware3 = new ConfigurationContainerAwareTest();
-               configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware3);
-               
-               Assert.assertEquals(4, configurationContainerImpl.getConfigurationAwareListSize());
-               
-               configurationContainerImpl.removeConfigurationContainerAware(testConfigurationContainerAware);
-               Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
-               
-               configurationContainerImpl.removeConfigurationContainerAware(testConfigurationContainerAware);
-               Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
-               
-               configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware3);
-               Assert.assertEquals(2, configurationContainerImpl.getConfigurationAwareListSize());
-               
-               configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware2);
-               Assert.assertEquals(1, configurationContainerImpl.getConfigurationAwareListSize());
-               
-               configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware1);
-               Assert.assertEquals(0, configurationContainerImpl.getConfigurationAwareListSize());
-               
-               
-       }
-       
-}
+public class ConfigurationContainerImplTest {
+
+
+        @Test
+        public void testAddRemoveSaveConfiguration() {
+
+                ConfigurationContainerImpl configurationContainerImpl = new ConfigurationContainerImpl();
+                IConfigurationContainerAware testConfigurationContainerAware = new ConfigurationContainerAwareTest();
+
+                configurationContainerImpl.addConfigurationContainerAware(testConfigurationContainerAware);
+                configurationContainerImpl.addConfigurationContainerAware(testConfigurationContainerAware);
+
+                Assert.assertEquals(1, configurationContainerImpl.getConfigurationAwareListSize());
+
+                IConfigurationContainerAware testConfigurationAware1 = new ConfigurationContainerAwareTest();
+                configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware1);
+
+                Assert.assertEquals(2, configurationContainerImpl.getConfigurationAwareListSize());
+
+                IConfigurationContainerAware testConfigurationAware2 = new ConfigurationContainerAwareTest();
+                configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware2);
+
+                Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
 
+                IConfigurationContainerAware testConfigurationAware3 = new ConfigurationContainerAwareTest();
+                configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware3);
+
+                Assert.assertEquals(4, configurationContainerImpl.getConfigurationAwareListSize());
+
+                configurationContainerImpl.removeConfigurationContainerAware(testConfigurationContainerAware);
+                Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
+
+                configurationContainerImpl.removeConfigurationContainerAware(testConfigurationContainerAware);
+                Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize());
+
+                configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware3);
+                Assert.assertEquals(2, configurationContainerImpl.getConfigurationAwareListSize());
+
+                configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware2);
+                Assert.assertEquals(1, configurationContainerImpl.getConfigurationAwareListSize());
+
+                configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware1);
+                Assert.assertEquals(0, configurationContainerImpl.getConfigurationAwareListSize());
+
+
+        }
+
+}
index 71d768d90754c321b370a2926290e88c3502e41b..816c6ce2bdecfe68d9335c45ee6b4c3de1639d26 100644 (file)
@@ -12,52 +12,51 @@ package org.opendaylight.controller.configuration.internal;
 import org.junit.*;
 import org.opendaylight.controller.configuration.IConfigurationAware;
 
-public class ConfigurationImplTest { 
-       
-
-       @Test
-       public void testAddRemoveSaveConfiguration() {
-               
-               ConfigurationImpl configurationImpl = new ConfigurationImpl();
-               IConfigurationAware testConfigurationAware = new ConfigurationAwareTest();
-               
-               configurationImpl.addConfigurationAware(testConfigurationAware);
-               configurationImpl.addConfigurationAware(testConfigurationAware);
-               
-               Assert.assertEquals(1, configurationImpl.getConfigurationAwareListSize());
-               
-               ConfigurationAwareTest testConfigurationAware1 = new ConfigurationAwareTest();
-               configurationImpl.addConfigurationAware(testConfigurationAware1);
-               
-               Assert.assertEquals(2, configurationImpl.getConfigurationAwareListSize());
-               
-               ConfigurationAwareTest testConfigurationAware2 = new ConfigurationAwareTest();
-               configurationImpl.addConfigurationAware(testConfigurationAware2);
-               
-               Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
-               
-               ConfigurationAwareTest testConfigurationAware3 = new ConfigurationAwareTest();
-               configurationImpl.addConfigurationAware(testConfigurationAware3);
-               
-               Assert.assertEquals(4, configurationImpl.getConfigurationAwareListSize());
-               
-               
-               configurationImpl.removeConfigurationAware(testConfigurationAware);
-               Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
-               
-               configurationImpl.removeConfigurationAware(testConfigurationAware);
-               Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
-               
-               configurationImpl.removeConfigurationAware(testConfigurationAware3);
-               Assert.assertEquals(2, configurationImpl.getConfigurationAwareListSize());
-               
-               configurationImpl.removeConfigurationAware(testConfigurationAware1);
-               Assert.assertEquals(1, configurationImpl.getConfigurationAwareListSize());
-               
-               configurationImpl.removeConfigurationAware(testConfigurationAware2);
-               Assert.assertEquals(0, configurationImpl.getConfigurationAwareListSize());
-               
-       }
-       
-}
+public class ConfigurationImplTest {
+
+
+        @Test
+        public void testAddRemoveSaveConfiguration() {
+
+                ConfigurationImpl configurationImpl = new ConfigurationImpl();
+                IConfigurationAware testConfigurationAware = new ConfigurationAwareTest();
+
+                configurationImpl.addConfigurationAware(testConfigurationAware);
+                configurationImpl.addConfigurationAware(testConfigurationAware);
+
+                Assert.assertEquals(1, configurationImpl.getConfigurationAwareListSize());
+
+                ConfigurationAwareTest testConfigurationAware1 = new ConfigurationAwareTest();
+                configurationImpl.addConfigurationAware(testConfigurationAware1);
+
+                Assert.assertEquals(2, configurationImpl.getConfigurationAwareListSize());
+
+                ConfigurationAwareTest testConfigurationAware2 = new ConfigurationAwareTest();
+                configurationImpl.addConfigurationAware(testConfigurationAware2);
+
+                Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
 
+                ConfigurationAwareTest testConfigurationAware3 = new ConfigurationAwareTest();
+                configurationImpl.addConfigurationAware(testConfigurationAware3);
+
+                Assert.assertEquals(4, configurationImpl.getConfigurationAwareListSize());
+
+
+                configurationImpl.removeConfigurationAware(testConfigurationAware);
+                Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
+
+                configurationImpl.removeConfigurationAware(testConfigurationAware);
+                Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize());
+
+                configurationImpl.removeConfigurationAware(testConfigurationAware3);
+                Assert.assertEquals(2, configurationImpl.getConfigurationAwareListSize());
+
+                configurationImpl.removeConfigurationAware(testConfigurationAware1);
+                Assert.assertEquals(1, configurationImpl.getConfigurationAwareListSize());
+
+                configurationImpl.removeConfigurationAware(testConfigurationAware2);
+                Assert.assertEquals(0, configurationImpl.getConfigurationAwareListSize());
+
+        }
+
+}
diff --git a/opendaylight/configuration/integrationtest/.gitignore b/opendaylight/configuration/integrationtest/.gitignore
new file mode 100644 (file)
index 0000000..f92f363
--- /dev/null
@@ -0,0 +1 @@
+configuration
diff --git a/opendaylight/configuration/integrationtest/pom.xml b/opendaylight/configuration/integrationtest/pom.xml
new file mode 100644 (file)
index 0000000..037b435
--- /dev/null
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+  xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+<parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>commons.integrationtest</artifactId>
+    <version>0.5.0-SNAPSHOT</version>
+    <relativePath>../../commons/integrationtest</relativePath>
+  </parent>
+  <artifactId>configuration.integrationtest</artifactId>
+  <version>0.4.0-SNAPSHOT</version>
+   <dependencies>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>protocol_plugins.stub</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>sal</artifactId>
+      <version>0.5.0-SNAPSHOT</version>
+    </dependency>
+     <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>sal.implementation</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>forwardingrulesmanager</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>clustering.services</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>clustering.services-implementation</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>clustering.stub</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>containermanager</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>containermanager.implementation</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>switchmanager</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>switchmanager.implementation</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>configuration</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>configuration.implementation</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+      <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>hosttracker</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>topologymanager</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+  </dependencies>
+</project>
diff --git a/opendaylight/configuration/integrationtest/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationIT.java b/opendaylight/configuration/integrationtest/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationIT.java
new file mode 100644 (file)
index 0000000..8e1f34e
--- /dev/null
@@ -0,0 +1,212 @@
+package org.opendaylight.controller.configuration.internal;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.ops4j.pax.exam.CoreOptions.junitBundles;
+import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
+import static org.ops4j.pax.exam.CoreOptions.options;
+import static org.ops4j.pax.exam.CoreOptions.systemPackages;
+import static org.ops4j.pax.exam.CoreOptions.systemProperty;
+
+import java.io.File;
+
+import javax.inject.Inject;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opendaylight.controller.clustering.services.IClusterServices;
+import org.opendaylight.controller.configuration.IConfigurationService;
+import org.opendaylight.controller.sal.utils.GlobalConstants;
+import org.opendaylight.controller.sal.utils.Status;
+import org.opendaylight.controller.sal.utils.StatusCode;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.junit.Configuration;
+import org.ops4j.pax.exam.junit.PaxExam;
+import org.ops4j.pax.exam.util.PathUtils;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@RunWith(PaxExam.class)
+public class ConfigurationIT {
+    private Logger logger = LoggerFactory
+            .getLogger(ConfigurationIT.class);
+    // get the OSGI bundle context
+    @Inject
+    private BundleContext bc;
+    private IClusterServices clusterService = null;
+    private IConfigurationService configService = null;
+
+    // Configure the OSGi container
+    @Configuration
+    public Option[] config() {
+        return options(
+                systemProperty("logback.configurationFile").value(
+                        "file:" + PathUtils.getBaseDir()
+                                + "/src/test/resources/logback.xml"),
+                // To start OSGi console for inspection remotely
+                systemProperty("osgi.console").value("2401"),
+                // Set the systemPackages (used by clustering)
+                systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"),
+                // List framework bundles
+                mavenBundle("equinoxSDK381", "org.eclipse.equinox.console",
+                        "1.0.0.v20120522-1841"),
+                mavenBundle("equinoxSDK381", "org.eclipse.equinox.util",
+                        "1.0.400.v20120522-2049"),
+                mavenBundle("equinoxSDK381", "org.eclipse.osgi.services",
+                        "3.3.100.v20120522-1822"),
+                mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds",
+                        "1.4.0.v20120522-1841"),
+                mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command",
+                        "0.8.0.v201108120515"),
+                mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime",
+                        "0.8.0.v201108120515"),
+                mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell",
+                        "0.8.0.v201110170705"),
+                // List logger bundles
+                mavenBundle("org.slf4j", "slf4j-api", "1.7.2"),
+                mavenBundle("org.slf4j", "log4j-over-slf4j", "1.7.2"),
+                mavenBundle("ch.qos.logback", "logback-core", "1.0.9"),
+                mavenBundle("ch.qos.logback", "logback-classic", "1.0.9"),
+                mavenBundle("org.apache.commons", "commons-lang3", "3.1"),
+                mavenBundle("org.jboss.spec.javax.transaction",
+                        "jboss-transaction-api_1.1_spec", "1.0.1.Final"),
+                mavenBundle("org.apache.felix",
+                        "org.apache.felix.dependencymanager", "3.1.0"),
+                // List all the bundles on which the test case depends
+                mavenBundle("org.opendaylight.controller", "sal",
+                        "0.5.0-SNAPSHOT"), // SAL connects the protocols
+                                           // plug-ins to other stuff
+                mavenBundle("org.opendaylight.controller",
+                        "sal.implementation", "0.4.0-SNAPSHOT"),
+                mavenBundle("org.opendaylight.controller",
+                        "protocol_plugins.stub", "0.4.0-SNAPSHOT"),
+                // needed bundles by switchmanager
+                mavenBundle("org.opendaylight.controller", "containermanager",
+                        "0.4.0-SNAPSHOT"),
+                mavenBundle("org.opendaylight.controller",
+                        "containermanager.implementation", "0.4.0-SNAPSHOT"),
+                mavenBundle("org.opendaylight.controller", "switchmanager",
+                        "0.4.0-SNAPSHOT"),
+                mavenBundle("org.opendaylight.controller",
+                        "switchmanager.implementation", "0.4.0-SNAPSHOT"),
+                // needed bundles by configuration
+                mavenBundle("org.opendaylight.controller",
+                        "clustering.services", "0.4.0-SNAPSHOT"), // what are
+                                                                  // the
+                                                                  // clustering
+                                                                  // services
+                                                                  // for
+                mavenBundle("org.opendaylight.controller", "clustering.stub",
+                        "0.4.0-SNAPSHOT"),
+                mavenBundle("org.opendaylight.controller",
+                        "clustering.services-implementation", "0.4.0-SNAPSHOT"),
+                mavenBundle("org.opendaylight.controller", "configuration",
+                        "0.4.0-SNAPSHOT"),
+                mavenBundle("org.opendaylight.controller",
+                        "configuration.implementation", "0.4.0-SNAPSHOT"),
+                junitBundles());
+    }
+
+    private String stateToString(int state) {
+        switch (state) {
+        case Bundle.ACTIVE:
+            return "ACTIVE";
+        case Bundle.INSTALLED:
+            return "INSTALLED";
+        case Bundle.RESOLVED:
+            return "RESOLVED";
+        case Bundle.UNINSTALLED:
+            return "UNINSTALLED";
+        default:
+            return "Not CONVERTED";
+        }
+    }
+
+    @Before
+    public void areWeReadyForClustering() {
+        assertNotNull(bc);
+        boolean debugit = false;
+        Bundle b[] = bc.getBundles();
+        for (int i = 0; i < b.length; i++) {
+            int state = b[i].getState();
+            if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
+                logger.debug("Bundle:" + b[i].getSymbolicName() + " state:"
+                        + stateToString(state));
+                debugit = true;
+            }
+        }
+        if (debugit) {
+            logger.debug("Do some debugging because some bundle is unresolved");
+        }
+
+        // Assert if true, if false we are good to go!
+        assertFalse(debugit);
+        ServiceReference r = bc.getServiceReference(IClusterServices.class
+                .getName());
+        if (r != null) {
+            this.clusterService = (IClusterServices) bc.getService(r);
+        }
+        // If StatisticsManager is null, cannot run tests.
+        assertNotNull(this.clusterService);
+
+    }
+
+    @Before
+    public void areWeReadyForConfiguration() {
+        assertNotNull(bc);
+        boolean debugit = false;
+        Bundle b[] = bc.getBundles();
+        for (int i = 0; i < b.length; i++) {
+            int state = b[i].getState();
+            if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
+                logger.debug("Bundle:" + b[i].getSymbolicName() + " state:"
+                        + stateToString(state));
+                debugit = true;
+            }
+        }
+        if (debugit) {
+            logger.debug("Do some debugging because some bundle is unresolved");
+        }
+
+        // Assert if true, if false we are good to go!
+        assertFalse(debugit);
+        ServiceReference r = bc.getServiceReference(IConfigurationService.class
+                .getName());
+        if (r != null) {
+            this.configService = (IConfigurationService) bc.getService(r);
+        }
+        // If StatisticsManager is null, cannot run tests.
+        assertNotNull(this.configService);
+
+    }
+
+    @Test
+    public void saveConfiguration() {
+        File f = new File(GlobalConstants.STARTUPHOME.toString());
+        boolean success = f.exists();
+        if (!success) {
+            success = f.mkdirs();
+        }
+        if(success){
+            Status status = new Status(StatusCode.SUCCESS, null);
+            if (this.configService != null) {
+                status = this.configService.saveConfigurations();
+            }
+            if (status.getCode().equals(StatusCode.SUCCESS)) {
+                Assert.assertTrue("Successfully saved config for "
+                        + configService.getClass().getSimpleName(), status
+                        .getCode().equals(StatusCode.SUCCESS));
+            } else {
+                Assert.assertFalse("Failed to save config for "
+                        + configService.getClass().getSimpleName(), status
+                        .getCode().equals(StatusCode.INTERNALERROR));
+            }
+        }
+    }
+
+}
diff --git a/opendaylight/configuration/integrationtest/src/test/resources/logback.xml b/opendaylight/configuration/integrationtest/src/test/resources/logback.xml
new file mode 100644 (file)
index 0000000..2d63ce5
--- /dev/null
@@ -0,0 +1,13 @@
+<configuration scan="true">
+
+  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+    <encoder>
+      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+      </pattern>
+    </encoder>
+  </appender>
+
+  <root level="error">
+    <appender-ref ref="STDOUT" />
+  </root>
+</configuration>
index f057959ee85f17db5eb071a7f5a99f5bc014797d..b956d76a2e8984241c3aa24e9e3adb0af4385816 100644 (file)
@@ -23,14 +23,14 @@ public interface IContainerManager {
     /**
      * Returns a list of Containers that currently exist.
      *
-     * @return array of String Container names
+     * @return  array of String Container names
      */
     public boolean hasNonDefaultContainer();
 
     /**
      * Returns a list of Containers that currently exist.
      *
-     * @return array of String Container names
+     * @return  array of String Container names
      */
     public List<String> getContainerNames();
 
@@ -39,7 +39,7 @@ public interface IContainerManager {
      * TODO : REMOVE THIS FUNCTION and make Save as a service rather than the
      * current hack of calling individual save routines.
      *
-     * @return status code
+     * @return  status code
      */
     public Status saveContainerConfig();
 }
index 42ff3387f7ff8e2ed7de26976789fde3d8712178..a324fca0d9f838fd905e79b66526cf3a7e7c2bac 100644 (file)
       <artifactId>containermanager</artifactId>
       <version>0.4.0-SNAPSHOT</version>
     </dependency>
-       <dependency>
+    <dependency>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>sal</artifactId>
       <version>0.5.0-SNAPSHOT</version>
-       </dependency> 
+    </dependency>
   </dependencies>
 </project>
index 4bdd6797d6717525a377e7f5c4d7de15ce23bd97..2d6439954a6911cb0078f4b1ec1d25bcb1a1e918 100644 (file)
@@ -20,41 +20,41 @@ import org.opendaylight.controller.sal.utils.NodeCreator;
 \r
 public class ContainerImplTest {\r
 \r
-       @Test\r
-       public void test() {\r
-               \r
-               ContainerImpl container1 = new ContainerImpl();\r
-                               \r
-               //Create Component for init\r
-               ComponentImpl component1 = new ComponentImpl(null, null, null);\r
-               component1.setInterface("serviceTestName", null);\r
-\r
-               //container1 does not have name yet\r
-               container1.init(component1);\r
-               assertNull(container1.getName());\r
-               \r
-               //Sets container1 name to TestName\r
-               Hashtable<String, String> properties = new Hashtable<String, String>();\r
-               properties.put("dummyKey", "dummyValue");\r
-               properties.put("containerName", "TestName");\r
-               component1.setInterface("serviceTestName", properties);\r
-\r
-               container1.init(component1);\r
-               assertEquals("TestName", container1.getName());\r
-               \r
-               //getContainerFlows always returns null for now\r
-               assertNull(container1.getContainerFlows());\r
-               \r
-               //getTag always returns 0 for now\r
-               Node n = NodeCreator.createOFNode(1L);\r
-               assertEquals(0, container1.getTag(n));\r
-               \r
-               //getNodeConnectors always returns null for now\r
-               assertNull(container1.getNodeConnectors());\r
-               \r
-               //getNodes always returns null for now\r
-               assertNull(container1.getNodes());\r
-               \r
-       }\r
+        @Test\r
+        public void test() {\r
+\r
+                ContainerImpl container1 = new ContainerImpl();\r
+\r
+                //Create Component for init\r
+                ComponentImpl component1 = new ComponentImpl(null, null, null);\r
+                component1.setInterface("serviceTestName", null);\r
+\r
+                //container1 does not have name yet\r
+                container1.init(component1);\r
+                assertNull(container1.getName());\r
+\r
+                //Sets container1 name to TestName\r
+                Hashtable<String, String> properties = new Hashtable<String, String>();\r
+                properties.put("dummyKey", "dummyValue");\r
+                properties.put("containerName", "TestName");\r
+                component1.setInterface("serviceTestName", properties);\r
+\r
+                container1.init(component1);\r
+                assertEquals("TestName", container1.getName());\r
+\r
+                //getContainerFlows always returns null for now\r
+                assertNull(container1.getContainerFlows());\r
+\r
+                //getTag always returns 0 for now\r
+                Node n = NodeCreator.createOFNode(1L);\r
+                assertEquals(0, container1.getTag(n));\r
+\r
+                //getNodeConnectors always returns null for now\r
+                assertNull(container1.getNodeConnectors());\r
+\r
+                //getNodes always returns null for now\r
+                assertNull(container1.getNodes());\r
+\r
+        }\r
 \r
 }\r
index b5e7a110977864b45fa49f3e0e0e1bcdd5103913..c7e35a069ca30b4e6a4418cf37c08968979c6786 100644 (file)
@@ -18,21 +18,21 @@ import org.opendaylight.controller.sal.utils.GlobalConstants;
 \r
 public class ContainerManagerTest {\r
 \r
-       @Test\r
-       public void test() {\r
-               ContainerManager cm = new ContainerManager();\r
-               \r
-               cm.init();\r
-               \r
-               ArrayList<String> names = (ArrayList<String>) cm.getContainerNames();\r
-               assertEquals(1, names.size());\r
-               assertEquals(GlobalConstants.DEFAULT.toString(), names.get(0));\r
-               \r
-               assertFalse(cm.hasNonDefaultContainer());\r
-               assertNull(cm.saveContainerConfig());\r
-               \r
-               cm.destroy();\r
-\r
-       }\r
+        @Test\r
+        public void test() {\r
+                ContainerManager cm = new ContainerManager();\r
+\r
+                cm.init();\r
+\r
+                ArrayList<String> names = (ArrayList<String>) cm.getContainerNames();\r
+                assertEquals(1, names.size());\r
+                assertEquals(GlobalConstants.DEFAULT.toString(), names.get(0));\r
+\r
+                assertFalse(cm.hasNonDefaultContainer());\r
+                assertNull(cm.saveContainerConfig());\r
+\r
+                cm.destroy();\r
+\r
+        }\r
 \r
 }\r
index b30241daa8144194d4e072fd45a964c192cbc376..50b34faac847f8a084e44b42cee41d93c2cc3a81 100644 (file)
@@ -38,6 +38,7 @@
     <module>../../clustering/test</module>
     <module>../../configuration/api</module>
     <module>../../configuration/implementation</module>
+    <module>../../configuration/integrationtest</module>
     <module>../../routing/dijkstra_implementation</module>
     <module>../../arphandler</module>
     <module>../../forwardingrulesmanager/api</module>
@@ -46,6 +47,8 @@
     <module>../../hosttracker/api</module>
     <module>../../hosttracker/implementation</module>
     <module>../../hosttracker/integrationtest</module>
+    <module>../../hosttracker_new/api</module>
+    <module>../../hosttracker_new/implementation</module>
     <module>../../containermanager/api</module>
     <module>../../containermanager/implementation</module>
     <module>../../switchmanager/api</module>
@@ -55,7 +58,8 @@
     <module>../../statisticsmanager/implementation</module>
     <module>../../statisticsmanager/integrationtest</module>
     <module>../../topologymanager</module>
-    <module>../../usermanager</module>
+    <module>../../usermanager/api</module>
+    <module>../../usermanager/implementation</module>
     <module>../../security</module>
 
 
     <module>../../samples/northbound/loadbalancer</module>
     <module>../../commons/concepts</module>
     <module>../../commons/integrationtest</module>
-    
+
   </modules>
 
   <build>
index 8c00d7f0fcf8b4b9553e3ea0a1e0b93e83158f3a..67a473581301ef749a8561dc77945aa5640e24d4 100644 (file)
@@ -1,6 +1,6 @@
-<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" 
-  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
   <id>osgipackage</id>
   <formats>
     <format>dir</format>
       <excludes>
         <exclude>org.opendaylight.controller.thirdparty:org.openflow.openflowj</exclude>
         <exclude>org.opendaylight.controller:clustering.stub</exclude>
-               <exclude>org.opendaylight.controller:logging.bridge</exclude>
-               <exclude>org.opendaylight.controller:protocol_plugins.stub</exclude>
-               <exclude>org.opendaylight.controller:*.integrationtest</exclude>
+        <exclude>org.opendaylight.controller:logging.bridge</exclude>
+        <exclude>org.opendaylight.controller:protocol_plugins.stub</exclude>
+        <exclude>org.opendaylight.controller:*.integrationtest</exclude>
+        <exclude>org.opendaylight.controller:hosttracker_new</exclude>
+        <exclude>org.opendaylight.controller:hosttracker_new.implementation</exclude>
       </excludes>
       <binaries>
         <outputDirectory>opendaylight/plugins</outputDirectory>
         <includeDependencies>false</includeDependencies>
       </binaries>
     </moduleSet>
-       <moduleSet>
-         <includes>
-               <include>org.opendaylight.controller:logging.bridge</include>
-         </includes>
-         <binaries>
-               <outputDirectory>opendaylight/lib</outputDirectory>
-               <outputFileNameMapping>
-                 ${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}
-               </outputFileNameMapping>
-               <unpack>false</unpack>
-               <includeDependencies>false</includeDependencies>
-         </binaries>
-       </moduleSet>
+    <moduleSet>
+      <includes>
+        <include>org.opendaylight.controller:logging.bridge</include>
+      </includes>
+      <binaries>
+        <outputDirectory>opendaylight/lib</outputDirectory>
+        <outputFileNameMapping>
+          ${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}
+        </outputFileNameMapping>
+        <unpack>false</unpack>
+        <includeDependencies>false</includeDependencies>
+      </binaries>
+    </moduleSet>
   </moduleSets>
   <dependencySets>
     <dependencySet>
         <exclude>virgomirror:org.eclipse.jdt.core.compiler.batch</exclude>
         <exclude>org.apache.felix:org.apache.felix.fileinstall</exclude>
         <exclude>geminiweb:org.eclipse.virgo.kernel.equinox.extensions</exclude>
-               <exclude>org.slf4j:slf4j-api</exclude>
-               <exclude>ch.qos.logback:logback-core</exclude>
-               <exclude>ch.qos.logback:logback-classic</exclude>
-               <exclude>com.sun.jersey:jersey-core</exclude>
-               <exclude>com.sun.jersey:jersey-json</exclude>
-               <exclude>com.sun.jersey:jersey-server</exclude>
+        <exclude>org.slf4j:slf4j-api</exclude>
+        <exclude>ch.qos.logback:logback-core</exclude>
+        <exclude>ch.qos.logback:logback-classic</exclude>
+        <exclude>com.sun.jersey:jersey-core</exclude>
+        <exclude>com.sun.jersey:jersey-json</exclude>
+        <exclude>com.sun.jersey:jersey-server</exclude>
       </excludes>
       <outputFileNameMapping>
-        ${artifact.groupId}.${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}      
+        ${artifact.groupId}.${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}
       </outputFileNameMapping>
       <unpack>false</unpack>
       <scope>runtime</scope>
         <include>virgomirror:org.eclipse.jdt.core.compiler.batch</include>
         <include>org.apache.felix:org.apache.felix.fileinstall</include>
         <include>geminiweb:org.eclipse.virgo.kernel.equinox.extensions</include>
-               <include>org.slf4j:slf4j-api</include>
-               <include>ch.qos.logback:logback-core</include>
-               <include>ch.qos.logback:logback-classic</include>
-               <include>com.sun.jersey:jersey-core</include>
-               <include>com.sun.jersey:jersey-json</include>
-               <include>com.sun.jersey:jersey-server</include>
+        <include>org.slf4j:slf4j-api</include>
+        <include>ch.qos.logback:logback-core</include>
+        <include>ch.qos.logback:logback-classic</include>
+        <include>com.sun.jersey:jersey-core</include>
+        <include>com.sun.jersey:jersey-json</include>
+        <include>com.sun.jersey:jersey-server</include>
       </includes>
       <useTransitiveDependencies>false</useTransitiveDependencies>
       <outputFileNameMapping>
-        ${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}      
+        ${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}
       </outputFileNameMapping>
       <unpack>false</unpack>
       <scope>runtime</scope>
index a8d7beb49b560c65f0c52c03271b31f3704cd318..460145ee8729d949dd6b0ef664be74d7947dd3ac 100644 (file)
@@ -1,13 +1,13 @@
 osgi.bundles=\
-       reference\:file\:../lib/org.apache.felix.fileinstall-3.1.6.jar@1:start,\
-       reference\:file\:../lib/org.eclipse.jdt.core.compiler.batch-3.8.0.I20120518-2145.jar@1:start,\
-       reference\:file\:../lib/org.eclipse.equinox.ds-1.4.0.v20120522-1841.jar@2:start,\
-       reference\:file\:../lib/org.eclipse.equinox.util-1.0.400.v20120522-2049.jar@2:start,\
-       reference\:file\:../lib/org.eclipse.osgi.services-3.3.100.v20120522-1822@2:start,\
-       reference\:file\:../lib/org.eclipse.equinox.console-1.0.0.v20120522-1841.jar@start,\
-       reference\:file\:../lib/slf4j-api-1.7.2.jar@1:start,\
-       reference\:file\:../lib/logback-classic-1.0.9.jar@1:start,\
-       reference\:file\:../lib/logback-core-1.0.9.jar@1:start,\
+    reference\:file\:../lib/org.apache.felix.fileinstall-3.1.6.jar@1:start,\
+    reference\:file\:../lib/org.eclipse.jdt.core.compiler.batch-3.8.0.I20120518-2145.jar@1:start,\
+    reference\:file\:../lib/org.eclipse.equinox.ds-1.4.0.v20120522-1841.jar@2:start,\
+    reference\:file\:../lib/org.eclipse.equinox.util-1.0.400.v20120522-2049.jar@2:start,\
+    reference\:file\:../lib/org.eclipse.osgi.services-3.3.100.v20120522-1822@2:start,\
+    reference\:file\:../lib/org.eclipse.equinox.console-1.0.0.v20120522-1841.jar@start,\
+    reference\:file\:../lib/slf4j-api-1.7.2.jar@1:start,\
+    reference\:file\:../lib/logback-classic-1.0.9.jar@1:start,\
+    reference\:file\:../lib/logback-core-1.0.9.jar@1:start,\
     reference\:file\:../lib/logging.bridge-0.4.0-SNAPSHOT@1:start,\
     reference\:file\:../lib/jersey-core-1.17.jar@2:start,\
     reference\:file\:../lib/jersey-json-1.17.jar@2:start,\
@@ -19,7 +19,7 @@ osgi.bundles.defaultStartLevel=4
 org.osgi.framework.system.packages.extra=sun.reflect,sun.reflect.misc,sun.misc
 # This is not Eclipse App
 eclipse.ignoreApp=true
-# Don't shutdown equinox if the eclipse App has ended, 
+# Don't shutdown equinox if the eclipse App has ended,
 # which is our case because we are not running any eclipse application
 osgi.noShutdown=true
 # Clean any cached data on restart of the framework
@@ -33,7 +33,7 @@ felix.fileinstall.dir=./plugins
 felix.fileinstall.noInitialDelay=true
 # Auto start the bundles at level 4
 felix.fileinstall.start.level=4
-# Avoid to auto-install following bundles, that means those need 
+# Avoid to auto-install following bundles, that means those need
 # to be started manually or in other way like osgi.bundles
 felix.fileinstall.filter=^(?!org.apache.felix.fileinstall).*
 
@@ -69,7 +69,7 @@ org.eclipse.gemini.web.tomcat.config.path=configuration/tomcat-server.xml
 
 # TLS configuration
 # To enable TLS, set secureChannelEnabled=true and specify the location of controller Java KeyStore and TrustStore files.
-# The Java KeyStore contains controller's private key and certificate. The Java TrustStore contains the trusted certificate 
+# The Java KeyStore contains controller's private key and certificate. The Java TrustStore contains the trusted certificate
 # entries, including switches' Certification Authority (CA) certificates. For example,
 # secureChannelEnabled=true
 # controllerKeyStore=./configuration/ctlKeyStore
index a99d17d37c25de4816fc108da4a0e5879326fa2b..de70a52a3118e60fb450cc1cb57905ce996ad67b 100644 (file)
@@ -54,5 +54,5 @@
   <logger name="org.opendaylight.controller.topologymanager" level="INFO"/>
   <logger name="org.opendaylight.controller.usermanager" level="INFO"/>
   <!-- Web modules -->
-  <logger name="org.opendaylight.controller.web" level="INFO"/>        
+  <logger name="org.opendaylight.controller.web" level="INFO"/>
 </configuration>
index 4be075451e9c31f90260e6e39b7dc43008a47c1f..56d469b59932f591b93cd91eb7e491ab3c683085 100644 (file)
                connectionTimeout="20000"
                redirectPort="8443" />
 
-<!-- 
-       Please remove the comments around the following Connector tag to enable HTTPS Authentication support.
-       Remember to add a valid keystore in the configuration folder.
-       More info : http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration 
+<!--
+        Please remove the comments around the following Connector tag to enable HTTPS Authentication support.
+        Remember to add a valid keystore in the configuration folder.
+        More info : http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
 -->
- <!-- 
+
+ <!--
     <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
                maxThreads="150" scheme="https" secure="true"
                clientAuth="false" sslProtocol="TLS"
             unpackWARs="false" autoDeploy="false"
             deployOnStartup="false" createDirs="false">
         <Realm className="org.opendaylight.controller.security.ControllerCustomRealm" />
-           <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-     
+            <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
+
         <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
-                       prefix="web_access_log_" suffix=".txt" resolveHosts="false"
-                       rotatable="true" fileDateFormat="yyyy-MM"
-                       pattern="%{yyyy-MM-dd HH:mm:ss.SSS z}t - [%a] - %r"/>
-               
+                        prefix="web_access_log_" suffix=".txt" resolveHosts="false"
+                        rotatable="true" fileDateFormat="yyyy-MM"
+                        pattern="%{yyyy-MM-dd HH:mm:ss.SSS z}t - [%a] - %r"/>
+
       </Host>
     </Engine>
   </Service>
index 79a00f33e429db354b34e69a176e9b2a428b595c..6fb9f0655cc4bbfe310dfac27d4354f7160710f3 100644 (file)
@@ -2,7 +2,7 @@
 SETLOCAL
 SETLOCAL ENABLEDELAYEDEXPANSION
 IF EXIST "%JAVA_HOME%" (
-               set basedir=%~dp0
+        set basedir=%~dp0
 REM       Now set the classpath:
                 set cp="!basedir!lib\org.eclipse.osgi-3.8.1.v20120830-144521.jar;!basedir!lib\org.eclipse.virgo.kernel.equinox.extensions-3.6.0.RELEASE.jar;!basedir!lib\org.eclipse.equinox.launcher-1.3.0.v20120522-1813.jar"
 
@@ -19,4 +19,4 @@ REM echo %JAVA_HOME%\bin\java.exe %* -Djava.io.tmpdir=!basedir!work\tmp -Dosgi.i
     ECHO JAVA_HOME environment variable is not set
     PAUSE
 )
-ENDLOCAL
\ No newline at end of file
+ENDLOCAL
index 2efb6747f8c27366d692676dfb413e6dc94ae949..e7c7f4906ed3d0661e784d9c601bd8d67075422a 100644 (file)
@@ -29,7 +29,7 @@
   <artifactId>distribution.p2site</artifactId>
   <version>0.1.0-SNAPSHOT</version>
   <packaging>pom</packaging>
-  
+
   <build>
     <plugins>
       <plugin>
index b4afa61b61214a80c639e45eb11b66bcf891b251..07ba376a566c8c6904bb44f414d8ec16744efd1b 100644 (file)
@@ -38,7 +38,7 @@
     <!-- Northbound common hooks -->
     <module>../../northbound/commons</module>
   </modules>
-  
+
   <build>
     <plugins>
       <plugin>
index bb3c6734f694e6b598e63669c8300da83585a773..b2f45c38c907701fb2c4997a167b2c44b97d6adf 100644 (file)
@@ -1,4 +1,4 @@
-<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" 
+<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
   <id>package</id>
index 80eea57b8f50b31e96fb91aba965b961b9336fcf..ea22c4f1ca4c03952a419c67a05b2a16daea13db 100644 (file)
@@ -70,7 +70,7 @@
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>configuration</artifactId>
       <version>0.4.0-SNAPSHOT</version>
-    </dependency>    
+    </dependency>
     <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
index 5fabb2629de3ca31a96a348fc94478d2e33c698f..0166d279f66528135322f3c8d250ec381bd2de1a 100644 (file)
@@ -12,14 +12,14 @@ package org.opendaylight.controller.forwarding.staticrouting;
 import java.net.InetAddress;
 import java.util.concurrent.ConcurrentMap;
 /**
- * 
+ *
  * This interface provides APIs to configure and manage static routes.
  *
  */
 import org.opendaylight.controller.sal.utils.Status;
 
 /**
- * 
+ *
  * This Interface provides APIs to manage and query the static routes
  *
  */
index 262c0170db9edc27d4885bb7fc1ca8a14e825d12..ceacebffb05cb57a8dfcc8fdf8ea8addc032e168 100644 (file)
@@ -151,18 +151,18 @@ public class StaticRouteConfig implements Serializable {
     public Status isValid() {
         if ((name == null) || (name.trim().length() < 1)) {
             return new Status(StatusCode.BADREQUEST,
-                       "Invalid Static Route name");
+                        "Invalid Static Route name");
         }
         if (!isValidStaticRouteEntry()) {
             return new Status(StatusCode.BADREQUEST,
-                       "Invalid Static Route entry. Please use the " +
-                       "IPAddress/mask format. Default gateway " +
-                       "(0.0.0.0/0) is NOT supported.");
+                        "Invalid Static Route entry. Please use the " +
+                        "IPAddress/mask format. Default gateway " +
+                        "(0.0.0.0/0) is NOT supported.");
         }
         if (!isValidNextHop()) {
             return new Status(StatusCode.BADREQUEST,
-                       "Invalid NextHop IP Address configuration. " +
-                                       "Please use the X.X.X.X format.");
+                        "Invalid NextHop IP Address configuration. " +
+                                        "Please use the X.X.X.X format.");
         }
 
         return new Status(StatusCode.SUCCESS, null);
index 1ac923c15ee266b737e202e62373fad4c8d0bc79..8819be39885d950e9f6aafc7ed4ad737247a2037 100644 (file)
@@ -131,7 +131,7 @@ public class StaticRoutingImplementation implements IfNewHostNotify,
         }
     }
 
-    
+
     private Status saveConfig() {
         // Publish the save config event to the cluster nodes
         configSaveEvent.put(new Date().getTime(), SAVE);
@@ -154,7 +154,7 @@ public class StaticRoutingImplementation implements IfNewHostNotify,
     }
 
     @SuppressWarnings("deprecation")
-       private void allocateCaches() {
+        private void allocateCaches() {
         if (this.clusterContainerService == null) {
             log
                     .info("un-initialized clusterContainerService, can't create cache");
@@ -207,7 +207,7 @@ public class StaticRoutingImplementation implements IfNewHostNotify,
     }
 
     @SuppressWarnings("deprecation")
-       private void destroyCaches() {
+        private void destroyCaches() {
         if (this.clusterContainerService == null) {
             log
                     .info("un-initialized clusterContainerService, can't destroy cache");
@@ -390,16 +390,16 @@ public class StaticRoutingImplementation implements IfNewHostNotify,
             return status;
         }
         if (staticRouteConfigs.get(config.getName()) != null) {
-               return new Status(StatusCode.CONFLICT,
-                               "A valid Static Route configuration with this name " +
-                                               "already exists. Please use a different name");
+                return new Status(StatusCode.CONFLICT,
+                                "A valid Static Route configuration with this name " +
+                                                "already exists. Please use a different name");
         }
         for (StaticRouteConfig s : staticRouteConfigs.values()) {
             if (s.equals(config)) {
-               return new Status(StatusCode.CONFLICT,
-                               "This conflicts with an existing Static Route " +
-                                       "Configuration. Please check the configuration " +
-                                               "and try again");
+                return new Status(StatusCode.CONFLICT,
+                                "This conflicts with an existing Static Route " +
+                                        "Configuration. Please check the configuration " +
+                                                "and try again");
             }
         }
 
@@ -407,7 +407,7 @@ public class StaticRoutingImplementation implements IfNewHostNotify,
         StaticRoute sRoute = new StaticRoute(config);
         staticRoutes.put(config.getName(), sRoute);
         checkAndUpdateListeners(sRoute, true);
-        return status; 
+        return status;
     }
 
     public Status removeStaticRoute(String name) {
@@ -417,8 +417,8 @@ public class StaticRoutingImplementation implements IfNewHostNotify,
             checkAndUpdateListeners(sRoute, false);
             return new Status(StatusCode.SUCCESS, null);
         }
-        return new Status(StatusCode.NOTFOUND, 
-                       "Static Route with name " + name + " is not found");
+        return new Status(StatusCode.NOTFOUND,
+                        "Static Route with name " + name + " is not found");
     }
 
     void setClusterContainerService(IClusterContainerServices s) {
index 84ec54b807ce42a8566a522e8acbd0ba3f338503..7cd085f8961b633028d74718f3c065650b8edc53 100644 (file)
@@ -18,94 +18,93 @@ import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.sal.utils.StatusCode;
 
 public class StaticRouteConfigTest {
-       
-       @Test
-       public void testStaticRouteSetGet() {
-               StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig();
-               staticRouteConfig1.setName("route");
-               staticRouteConfig1.setStaticRoute("10.1.1.2/32");
-               staticRouteConfig1.setNextHop("200.2.2.2");
-               staticRouteConfig1.setNextHopType(NextHopType.IPADDRESS.toString());
-               StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route", "10.1.1.2/32", "200.2.2.2");
-               
-               Assert.assertEquals(staticRouteConfig2.getName(), staticRouteConfig1.getName());
-               Assert.assertEquals(staticRouteConfig2.getStaticRoute(), staticRouteConfig1.getStaticRoute());
-               Assert.assertEquals(staticRouteConfig2.getNextHop(), staticRouteConfig1.getNextHop());
-               Assert.assertEquals("nexthop-ip", staticRouteConfig1.getNextHopType());
-       }
-               
-       @Test
-       public void testStaticRouteisValid() {  
+
+        @Test
+        public void testStaticRouteSetGet() {
+                StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig();
+                staticRouteConfig1.setName("route");
+                staticRouteConfig1.setStaticRoute("10.1.1.2/32");
+                staticRouteConfig1.setNextHop("200.2.2.2");
+                staticRouteConfig1.setNextHopType(NextHopType.IPADDRESS.toString());
+                StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route", "10.1.1.2/32", "200.2.2.2");
+
+                Assert.assertEquals(staticRouteConfig2.getName(), staticRouteConfig1.getName());
+                Assert.assertEquals(staticRouteConfig2.getStaticRoute(), staticRouteConfig1.getStaticRoute());
+                Assert.assertEquals(staticRouteConfig2.getNextHop(), staticRouteConfig1.getNextHop());
+                Assert.assertEquals("nexthop-ip", staticRouteConfig1.getNextHopType());
+        }
+
+        @Test
+        public void testStaticRouteisValid() {
         StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1.1");
-               Status receivedResponse1 = staticRouteConfig1.isValid();
-               Status expectedResponse1 = new Status(StatusCode.SUCCESS, null);
-               Assert.assertEquals(expectedResponse1.toString(), receivedResponse1.toString());
-               
+                Status receivedResponse1 = staticRouteConfig1.isValid();
+                Status expectedResponse1 = new Status(StatusCode.SUCCESS, null);
+                Assert.assertEquals(expectedResponse1.toString(), receivedResponse1.toString());
+
         StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("", "", "100.1.1.1");
-               Status receivedResponse2 = staticRouteConfig2.isValid();
-               Status expectedResponse2 = new Status(StatusCode.BADREQUEST,
-                       "Invalid Static Route name");
-               Assert.assertEquals(expectedResponse2.toString(), receivedResponse2.toString());
+                Status receivedResponse2 = staticRouteConfig2.isValid();
+                Status expectedResponse2 = new Status(StatusCode.BADREQUEST,
+                        "Invalid Static Route name");
+                Assert.assertEquals(expectedResponse2.toString(), receivedResponse2.toString());
 
         StaticRouteConfig staticRouteConfig3 = new StaticRouteConfig("route1", "10.1.1.254", "100.1.1.1");
-               Status receivedResponse3 = staticRouteConfig3.isValid();
-               Status expectedResponse3 = new Status(StatusCode.BADREQUEST,
-                       "Invalid Static Route entry. Please use the " +
-                       "IPAddress/mask format. Default gateway " +
-                       "(0.0.0.0/0) is NOT supported.");
-               Assert.assertEquals(expectedResponse3.toString(), receivedResponse3.toString());
+                Status receivedResponse3 = staticRouteConfig3.isValid();
+                Status expectedResponse3 = new Status(StatusCode.BADREQUEST,
+                        "Invalid Static Route entry. Please use the " +
+                        "IPAddress/mask format. Default gateway " +
+                        "(0.0.0.0/0) is NOT supported.");
+                Assert.assertEquals(expectedResponse3.toString(), receivedResponse3.toString());
 
         StaticRouteConfig staticRouteConfig4 = new StaticRouteConfig("route1", "289.1.1.254/24", "100.1.1.1");
-               Status receivedResponse4 = staticRouteConfig4.isValid();
-               Status expectedResponse4 = new Status(StatusCode.BADREQUEST,
-                       "Invalid Static Route entry. Please use the " +
-                       "IPAddress/mask format. Default gateway " +
-                       "(0.0.0.0/0) is NOT supported.");
-               Assert.assertEquals(expectedResponse4.toString(), receivedResponse4.toString());
-               
+                Status receivedResponse4 = staticRouteConfig4.isValid();
+                Status expectedResponse4 = new Status(StatusCode.BADREQUEST,
+                        "Invalid Static Route entry. Please use the " +
+                        "IPAddress/mask format. Default gateway " +
+                        "(0.0.0.0/0) is NOT supported.");
+                Assert.assertEquals(expectedResponse4.toString(), receivedResponse4.toString());
+
         StaticRouteConfig staticRouteConfig5 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1");
-               Status receivedResponse5 = staticRouteConfig5.isValid();
-               Status expectedResponse5 = new Status(StatusCode.BADREQUEST,
-                       "Invalid NextHop IP Address configuration. " +
-                               "Please use the X.X.X.X format.");
-               Assert.assertEquals(expectedResponse5.toString(), receivedResponse5.toString());
-       }
-       
-       @Test
-       public void testGetStaticRouteIP() {
+                Status receivedResponse5 = staticRouteConfig5.isValid();
+                Status expectedResponse5 = new Status(StatusCode.BADREQUEST,
+                        "Invalid NextHop IP Address configuration. " +
+                                "Please use the X.X.X.X format.");
+                Assert.assertEquals(expectedResponse5.toString(), receivedResponse5.toString());
+        }
+
+        @Test
+        public void testGetStaticRouteIP() {
         StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.0/24", "100.1.1.1");
         InetAddress ip1 = staticRouteConfig1.getStaticRouteIP();
-               Assert.assertEquals("10.1.1.0", ip1.getHostAddress());        
-               
+                Assert.assertEquals("10.1.1.0", ip1.getHostAddress());
+
         StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.0/80", "100.1.1.1");
         InetAddress ip2 = staticRouteConfig2.getStaticRouteIP();
-               Assert.assertEquals(null, ip2);        
+                Assert.assertEquals(null, ip2);
+
+        }
 
-       }
-       
-       @Test
-       public void testGetStaticRouteMask() {
+        @Test
+        public void testGetStaticRouteMask() {
         StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.0/24", "100.1.1.1");
-               Short receivedMaskLen1 = staticRouteConfig1.getStaticRouteMask();
-               Short expectedMaskLen1 = 24;
-               Assert.assertEquals(expectedMaskLen1, receivedMaskLen1);
-
-               StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.0/40", "100.1.1.1");
-               Short receivedMaskLen2 = staticRouteConfig2.getStaticRouteMask();
-               Short expectedMaskLen2 = 0;
-               Assert.assertEquals(expectedMaskLen2, receivedMaskLen2);
-       }
-       
-       @Test 
-       public void testGetNextHopIP() {
+                Short receivedMaskLen1 = staticRouteConfig1.getStaticRouteMask();
+                Short expectedMaskLen1 = 24;
+                Assert.assertEquals(expectedMaskLen1, receivedMaskLen1);
+
+                StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.0/40", "100.1.1.1");
+                Short receivedMaskLen2 = staticRouteConfig2.getStaticRouteMask();
+                Short expectedMaskLen2 = 0;
+                Assert.assertEquals(expectedMaskLen2, receivedMaskLen2);
+        }
+
+        @Test
+        public void testGetNextHopIP() {
         StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1.1");
         InetAddress ip1 = staticRouteConfig1.getNextHopIP();
-               Assert.assertEquals("100.1.1.1", ip1.getHostAddress());                
+                Assert.assertEquals("100.1.1.1", ip1.getHostAddress());
 
-               StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1");
+                StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1");
         InetAddress ip2 = staticRouteConfig2.getNextHopIP();
-               Assert.assertEquals(null, ip2);                
-       }
-       
-}
+                Assert.assertEquals(null, ip2);
+        }
 
+}
index f05b10c9cfb879fc485ed36233c5ce1b2fe33b46..4a497a058c0df7a1bdc5b16c5a0cac656010c8f3 100644 (file)
@@ -23,35 +23,35 @@ import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
 import org.opendaylight.controller.sal.utils.NodeCreator;
 
 public class StaticRouteTest {
-       
-       @Test
-       public void testStaticRouteGetSet() {
-               StaticRoute staticRoute = new StaticRoute();
-               InetAddress networkAddress = null;
-               InetAddress mask = null;
-               InetAddress nextHopAddress = null;
-               try {
-                       networkAddress = InetAddress.getByName("10.1.1.0");
-                       mask = InetAddress.getByName("255.255.255.0");
-                       nextHopAddress = InetAddress.getByName("200.0.0.1");
-                       
-               } catch (UnknownHostException e) {
-                       Assert.assertTrue(false);
-               }
-               staticRoute.setNetworkAddress(networkAddress);
-               Assert.assertEquals(networkAddress.getHostAddress(), staticRoute.getNetworkAddress().getHostAddress());
-               staticRoute.setMask(mask);
-               Assert.assertEquals(mask.getHostAddress(), staticRoute.getMask().getHostAddress());
-               staticRoute.setType(NextHopType.IPADDRESS);
-               Assert.assertEquals("nexthop-ip", staticRoute.getType().toString());
-               staticRoute.setNextHopAddress(nextHopAddress);
-               Assert.assertEquals(nextHopAddress.getHostAddress(), staticRoute.getNextHopAddress().getHostAddress());
-               Node node = NodeCreator.createOFNode(((long)10));
-               staticRoute.setNode(node);
-               Assert.assertEquals(node, staticRoute.getNode());
-               NodeConnector nc0 = NodeConnectorCreator.createOFNodeConnector((short)20, node);
-               staticRoute.setPort(nc0);
-               Assert.assertEquals(nc0, staticRoute.getPort());
+
+        @Test
+        public void testStaticRouteGetSet() {
+                StaticRoute staticRoute = new StaticRoute();
+                InetAddress networkAddress = null;
+                InetAddress mask = null;
+                InetAddress nextHopAddress = null;
+                try {
+                        networkAddress = InetAddress.getByName("10.1.1.0");
+                        mask = InetAddress.getByName("255.255.255.0");
+                        nextHopAddress = InetAddress.getByName("200.0.0.1");
+
+                } catch (UnknownHostException e) {
+                        Assert.assertTrue(false);
+                }
+                staticRoute.setNetworkAddress(networkAddress);
+                Assert.assertEquals(networkAddress.getHostAddress(), staticRoute.getNetworkAddress().getHostAddress());
+                staticRoute.setMask(mask);
+                Assert.assertEquals(mask.getHostAddress(), staticRoute.getMask().getHostAddress());
+                staticRoute.setType(NextHopType.IPADDRESS);
+                Assert.assertEquals("nexthop-ip", staticRoute.getType().toString());
+                staticRoute.setNextHopAddress(nextHopAddress);
+                Assert.assertEquals(nextHopAddress.getHostAddress(), staticRoute.getNextHopAddress().getHostAddress());
+                Node node = NodeCreator.createOFNode(((long)10));
+                staticRoute.setNode(node);
+                Assert.assertEquals(node, staticRoute.getNode());
+                NodeConnector nc0 = NodeConnectorCreator.createOFNodeConnector((short)20, node);
+                staticRoute.setPort(nc0);
+                Assert.assertEquals(nc0, staticRoute.getPort());
         InetAddress ip1 = null;
         HostNodeConnector h1 = null;
         try {
@@ -66,10 +66,10 @@ public class StaticRouteTest {
         }
         staticRoute.setHost(h1);
         Assert.assertEquals(h1, staticRoute.getHost());
-       }
-       
-       @Test
-       public void testStaticRouteComparison() {
+        }
+
+        @Test
+        public void testStaticRouteComparison() {
         StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.0/24", "100.1.1.1");
         StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route2", "10.1.1.0/24", "100.2.1.1");
         StaticRouteConfig staticRouteConfig3 = new StaticRouteConfig("route3", "10.2.1.0/24", "100.3.1.1");
@@ -82,28 +82,28 @@ public class StaticRouteTest {
         Assert.assertTrue(staticRoute1.equals(staticRoute2));
         Assert.assertFalse(staticRoute1.equals(staticRoute3));
         Assert.assertFalse(staticRoute1.equals(staticRoute4));
-        
+
         Assert.assertTrue(staticRoute1.compareTo(staticRoute2) == 0 ? true : false);
         Assert.assertFalse(staticRoute1.compareTo(staticRoute3) == 0 ? true : false);
         Assert.assertTrue(staticRoute1.compareTo(staticRoute4) == 0 ? true : false);
-                       
-       }
-       
-       @Test
-       public void testLongestPrefixMatch() {
+
+        }
+
+        @Test
+        public void testLongestPrefixMatch() {
         StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1.1");
         StaticRoute staticRoute1 = new StaticRoute(staticRouteConfig1);
-               InetAddress ip1 = null;
-               InetAddress ip2 = null;
-               try {
-                       ip1 = InetAddress.getByName("10.1.0.2");
-                       ip2 = InetAddress.getByName("10.1.1.2");
-               } catch (UnknownHostException e) {
-                       Assert.assertTrue(false);
-               }
+                InetAddress ip1 = null;
+                InetAddress ip2 = null;
+                try {
+                        ip1 = InetAddress.getByName("10.1.0.2");
+                        ip2 = InetAddress.getByName("10.1.1.2");
+                } catch (UnknownHostException e) {
+                        Assert.assertTrue(false);
+                }
         InetAddress rxdIp1 = staticRoute1.longestPrefixMatch(ip1);
         InetAddress rxdIp2 = staticRoute1.longestPrefixMatch(ip2);
-               Assert.assertEquals(null, rxdIp1);
-               Assert.assertEquals("10.1.1.0", rxdIp2.getHostAddress());
-       }
+                Assert.assertEquals(null, rxdIp1);
+                Assert.assertEquals("10.1.1.0", rxdIp2.getHostAddress());
+        }
 }
index 4df0590b1da759c74b4274149ce2a537570e7614..4c9d4ab1f3a054f60f00295e3bef8407d0d23bf3 100644 (file)
@@ -13,16 +13,12 @@ import org.junit.Assert;
 import org.junit.Test;
 
 public class StaticRoutingImplementationTest {
-       
-       @Test
-       public void isIPv4AddressValidTest() {
-               StaticRoutingImplementation staticRouteImpl = new StaticRoutingImplementation();
-        Assert.assertTrue(staticRouteImpl.isIPv4AddressValid("192.168.100.0/24"));             
-        Assert.assertFalse(staticRouteImpl.isIPv4AddressValid("192.168.100.0/36"));            
-        Assert.assertFalse(staticRouteImpl.isIPv4AddressValid("192.168.300.0/32"));            
-       }
-}
-
-
-
 
+        @Test
+        public void isIPv4AddressValidTest() {
+                StaticRoutingImplementation staticRouteImpl = new StaticRoutingImplementation();
+        Assert.assertTrue(staticRouteImpl.isIPv4AddressValid("192.168.100.0/24"));
+        Assert.assertFalse(staticRouteImpl.isIPv4AddressValid("192.168.100.0/36"));
+        Assert.assertFalse(staticRouteImpl.isIPv4AddressValid("192.168.300.0/32"));
+        }
+}
index 6aa5b07e2a0e782c81f15de11835758ce1cc4cea..8a055329e1fcebc99c60a904b4dc547779010e56 100644 (file)
@@ -51,7 +51,7 @@ public class FlowEntry implements Cloneable, Serializable {
 
     /**
      * Return the actual Flow contained in this entry
-     * 
+     *
      * @return the flow
      */
     public Flow getFlow() {
@@ -147,12 +147,12 @@ public class FlowEntry implements Cloneable, Serializable {
 
     /**
      * Merges the current Flow with the passed Container Flow
-     * 
+     *
      * Note: Container Flow merging is not an injective function. Be m1 and m2
      * two different matches, and be f() the flow merge function, such that y1 =
      * f(m1) and y2 = f(m2) are the two merged matches, we may have: y1 = y2
-     * 
-     * 
+     *
+     *
      * @param containerFlow
      * @return this merged FlowEntry
      */
index 18255bc021aeffbc4ee5b887d98b19065dd9d08a..311d2f96ac05505fcbbd8d16b3b49c4037df5250 100644 (file)
@@ -17,10 +17,10 @@ import org.opendaylight.controller.sal.core.Node;
  * install, the container flow with which that entry had to be merged and the
  * resultant merged flow entry, which is the one that was eventually installed
  * on the network node
- * 
+ *
  * Note: If the container flow is null, the install entry will be a clone of the
  * original entry
- * 
+ *
  */
 public class FlowEntryInstall {
     private FlowEntry original;
@@ -115,7 +115,7 @@ public class FlowEntryInstall {
     public void setRequestId(long rid) {
         this.requestId = rid;
     }
-    
+
     public long getRequestId() {
         return requestId;
     }
index 087c0bc878b7140e4d409dc14ba5cad1b0b19b5d..b3d0c8acdf535f2f48d77c5940970587bbee954d 100644 (file)
@@ -18,7 +18,7 @@ import org.opendaylight.controller.sal.utils.Status;
 /**
  * Interface that describes methods for installing or removing forwarding rules
  * and to access to the flows database.
- * 
+ *
  */
 public interface IForwardingRulesManager {
 
@@ -27,7 +27,7 @@ public interface IForwardingRulesManager {
      * SDN protocol plugin to install the flow on the network node. Based on the
      * result of this operation FRM will update its database accordingly and
      * will return the proper {@code Status} code.
-     * 
+     *
      * @param flow
      *            the flow entry to install
      * @return the {@code Status} object indicating the result of this action.
@@ -39,7 +39,7 @@ public interface IForwardingRulesManager {
      * protocol plugin to uninstall the flow from the network node. Based on the
      * result of this operation FRM will update its database accordingly and
      * will return the proper {@code Status} code.
-     * 
+     *
      * @param flow
      *            the flow entry to uninstall
      * @return the {@code Status} object indicating the result of this action
@@ -53,7 +53,7 @@ public interface IForwardingRulesManager {
      * modify message depending on the SDN protocol specifications If the
      * current flow is equal to the new one it will be a no op and success code
      * is returned.
-     * 
+     *
      * @param current
      *            the current flow entry to modify
      * @param newone
@@ -72,8 +72,8 @@ public interface IForwardingRulesManager {
      * it, it will request plugin to add the new flow. If the passed entry is
      * not valid an error code is returned. If the existing flow is equal to the
      * passed one it will be a no op and success code is returned.
-     * 
-     * 
+     *
+     *
      * @param newone
      *            the new flow entry to install
      * @return the {@code Status} object indicating the result of this action
@@ -86,7 +86,7 @@ public interface IForwardingRulesManager {
      * SDN protocol plugin to install the flow on the network node. As immediate
      * result of this asynchronous call, FRM will update its flow database as if
      * the flow was successfully installed.
-     * 
+     *
      * @param flow
      *            the flow entry to install
      * @return the status of this request containing the request id associated
@@ -100,7 +100,7 @@ public interface IForwardingRulesManager {
      * SDN protocol plugin to uninstall the flow from the network node. As
      * immediate result of this asynchronous call, FRM will update its flow
      * database as if the flow was successfully installed.
-     * 
+     *
      * @param flow
      *            the flow entry to uninstall
      * @return the status of this request containing the unique id associated to
@@ -115,7 +115,7 @@ public interface IForwardingRulesManager {
      * this message to the network node. It could be a delete + add or a single
      * modify message depending on the SDN protocol specifications. If the
      * current flow is equal to the new one it will be a no op.
-     * 
+     *
      * @param current
      *            the current flow entry to modify
      * @param newone
@@ -136,7 +136,7 @@ public interface IForwardingRulesManager {
      * it, it will request plugin to add the new flow. If the passed entry is
      * not valid a zero request id is returned. If the existing flow is equal to
      * the passed one it will be a no op.
-     * 
+     *
      * @param newone
      *            the new flow entry to install
      * @return the unique id associated to this request. In case of not
@@ -154,7 +154,7 @@ public interface IForwardingRulesManager {
      * blocked until the solicitation response is received from the network node
      * or receive timeout. Otherwise, it is a non-blocking call and does not
      * guarantee the node will respond in any given time.
-     * 
+     *
      * @param node
      *            The network node to solicit a response
      * @param blocking
@@ -166,7 +166,7 @@ public interface IForwardingRulesManager {
 
     /**
      * Check whether the passed flow entry conflicts with the Container flows
-     * 
+     *
      * @param flow
      *            the flow entry to test
      * @return true if conflicts, false otherwise
@@ -176,7 +176,7 @@ public interface IForwardingRulesManager {
     /**
      * Returns the list of Flow entries across network nodes which are part of
      * the same flow group, policy
-     * 
+     *
      * @param group
      *            the group name
      * @return the list of flow entries belonging to the specified group
@@ -186,7 +186,7 @@ public interface IForwardingRulesManager {
     /**
      * Add a list of output port to the flow with the specified name on the
      * specified network node
-     * 
+     *
      * @param node
      *            the network node
      * @param flowName
@@ -200,7 +200,7 @@ public interface IForwardingRulesManager {
     /**
      * Remove a list of output port from the flow with the specified name on the
      * specified network node
-     * 
+     *
      * @param node
      *            the network node
      * @param flowName
@@ -214,7 +214,7 @@ public interface IForwardingRulesManager {
     /**
      * Replace the current output port in the specified flow with the specified
      * one
-     * 
+     *
      * @param node
      *            the network node
      * @param groupName
@@ -229,7 +229,7 @@ public interface IForwardingRulesManager {
 
     /**
      * Returns the output port configured on the specified flow
-     * 
+     *
      * @param node
      *            the network node
      * @param flowName
@@ -242,14 +242,14 @@ public interface IForwardingRulesManager {
      * Returns all the troubleshooting information that applications have set
      * along with the policy they have configured through forwarding rules
      * manger.
-     * 
+     *
      * @return the collection of troubleshooting objects
      */
     public Map<String, Object> getTSPolicyData();
 
     /**
      * Set the troubleshooting information for the policy
-     * 
+     *
      * @param policyname
      *            the flow group name
      * @param o
@@ -262,7 +262,7 @@ public interface IForwardingRulesManager {
     /**
      * Returns the troubleshooting information that was set for the specified
      * policy
-     * 
+     *
      * @param groupName
      *            the flows group name
      * @return the troubleshooting info object
@@ -272,7 +272,7 @@ public interface IForwardingRulesManager {
     /**
      * Returns the specifications of all the flows configured for all the
      * switches on the current container
-     * 
+     *
      * @return the list of flow configurations present in the database
      */
     public List<FlowConfig> getStaticFlows();
@@ -280,7 +280,7 @@ public interface IForwardingRulesManager {
     /**
      * Returns the specifications of all the flows configured for the given
      * switch on the current container
-     * 
+     *
      * @param node
      *            the network node identifier
      * @return the list of {@code FlowConfig} objects
@@ -290,7 +290,7 @@ public interface IForwardingRulesManager {
     /**
      * Returns the specification of the flow configured for the given network
      * node on the current container
-     * 
+     *
      * @param name
      *            the flow name
      * @param n
@@ -302,7 +302,7 @@ public interface IForwardingRulesManager {
     /**
      * Returns the list of names of flows configured for the given Network node
      * on the current container
-     * 
+     *
      * @param node
      *            the network node identifier
      * @return the list of flow names
@@ -311,14 +311,14 @@ public interface IForwardingRulesManager {
 
     /**
      * Returns the list of Node(s) for which a static flow has been configured
-     * 
+     *
      * @return the list of network nodes
      */
     public List<Node> getListNodeWithConfiguredFlows();
 
     /**
      * Save the flow configured so far to file
-     * 
+     *
      * @return the {@code Status} object indicating the result of this action.
      */
     public Status saveConfig();
@@ -326,7 +326,7 @@ public interface IForwardingRulesManager {
     /**
      * Add a flow specified by the {@code FlowConfig} object on the current
      * container
-     * 
+     *
      * @param config
      *            the {@code FlowConfig} object representing the static flow
      * @param restore
@@ -339,7 +339,7 @@ public interface IForwardingRulesManager {
     /**
      * Remove a flow specified by the {@code FlowConfig} object on the current
      * container
-     * 
+     *
      * @param config
      *            the {@code FlowConfig} object representing the static flow
      * @return the {@code Status} object indicating the result of this action
@@ -350,7 +350,7 @@ public interface IForwardingRulesManager {
      * Replace the flow identified by the {@code FlowConfig.name} name for the
      * {@code FlowConfig.node} network node with the new flow specified by
      * {@code FlowConfig} object
-     * 
+     *
      * @param config
      *            the {@code FlowConfig} object
      * @returnthe {@code Status} object indicating the result of this action
@@ -359,7 +359,7 @@ public interface IForwardingRulesManager {
 
     /**
      * Remove the flow specified by name on the passed network node
-     * 
+     *
      * @param name
      *            for the static flow
      * @param node
@@ -372,7 +372,7 @@ public interface IForwardingRulesManager {
      * Toggle the installation status of the specified configured flow If the
      * flow configuration status is active, this call will change the flow
      * status to inactive and vice-versa
-     * 
+     *
      * @param configObject
      *            the {@code FlowConfig} object
      * @return the {@code Status} object indicating the result of this action
@@ -383,7 +383,7 @@ public interface IForwardingRulesManager {
      * Toggle the installation status of the specified configured flow If the
      * flow configuration status is active, this call will change the flow
      * status to inactive and vice-versa
-     * 
+     *
      * @param name
      *            for the static flow
      * @param node
index 43d1b29a7577978e3ae8b76ae021ac91f0ba288c..952b3cdff7bb139890d6e533d6173f7da9f9cfe1 100644 (file)
@@ -11,14 +11,14 @@ package org.opendaylight.controller.forwardingrulesmanager;
 /**
  * The interface which describes the methods forwarding rules manager will call
  * for notifying the listeners of policy installation updates.
- * 
+ *
  */
 public interface IForwardingRulesManagerAware {
 
     /**
      * Inform the listeners that a troubleshooting information was added or
      * removed for the specified policy.
-     * 
+     *
      * @param policyName
      *            the policy affected
      * @param add
@@ -31,7 +31,7 @@ public interface IForwardingRulesManagerAware {
      * Inform listeners that the network node has notified us about a failure in
      * executing the controller generated asynchronous request identified by the
      * passed unique id.
-     * 
+     *
      * @param requestId
      *            the unique id associated with the request which failed to be
      *            executed on the network node
index 5acd3e2ebc28638a656eb7c1705aea2e4f790e3a..95e9b00d14d78dba23bc508b21c1859aea33cfc8 100644 (file)
@@ -14,11 +14,11 @@ import java.util.Set;
 /**
  * PortGroup is a simple data-structure to represent any arbitrary group of
  * ports on a Switch (that is represented using its switch-ID).
- * 
+ *
  * PortGroup is used by PortGroupProvider application to signal a set of ports
  * that represent a configured PortGroupConfig.
- * 
- * 
+ *
+ *
  */
 public class PortGroup {
     private long matrixSwitchId;
@@ -26,7 +26,7 @@ public class PortGroup {
 
     /**
      * PortGroup Constructor using Switch and Ports.
-     * 
+     *
      * @param matrixSwitchId
      *            Switch Id that represents an openflow Switch
      * @param ports
@@ -40,7 +40,7 @@ public class PortGroup {
 
     /**
      * PortGroup Constructor using Switch.
-     * 
+     *
      * @param matrixSwitchId
      *            Switch-Id that represents an openflow Switch
      */
@@ -51,7 +51,7 @@ public class PortGroup {
 
     /**
      * Returns the switchId representing the Switch that makes this PortGroup.
-     * 
+     *
      * @return long switchId
      */
     public long getMatrixSwitchId() {
@@ -60,7 +60,7 @@ public class PortGroup {
 
     /**
      * Assigns a Switch to this PortGroup
-     * 
+     *
      * @param matrixSwitchId
      *            Switch-Id that represents an openflow Switch
      */
@@ -70,7 +70,7 @@ public class PortGroup {
 
     /**
      * Returns the Set of Ports that makes this PortGroup.
-     * 
+     *
      * @return Set of short values representing openflow port-ids.
      */
     public Set<Short> getPorts() {
@@ -79,7 +79,7 @@ public class PortGroup {
 
     /**
      * Assigns a set of openflow ports to this PortGroup
-     * 
+     *
      * @param ports
      *            Set of short values representing openflow port-ids.
      */
@@ -89,7 +89,7 @@ public class PortGroup {
 
     /**
      * Adds a port to this PortGroup
-     * 
+     *
      * @param port
      *            Short value of a openflow port.
      */
index 7c8ade5b897dd72a7bcd954d7e19e5fbba5cc6d5..77ff64014b7e2a05a95e44c2a69a97e9508ef32b 100644 (file)
@@ -15,14 +15,14 @@ import org.opendaylight.controller.sal.core.Node;
 /**
  * PortGroupChangeListener listens to the PortGroup updates provided by the
  * PortGroupProvider.
- * 
- * 
+ *
+ *
  */
 public interface PortGroupChangeListener {
     /**
      * This method is invoked by PortGroupProvider whenever it detects a change
      * in PortGroup membership for a given PortGroupConfig.
-     * 
+     *
      * @param config
      *            Port Group Configuration
      * @param portGroupData
index 164f26484e24cd29eedc54e1707b5df8d63c1951..b45f4898bfd076c8c551f99d6c968f55ce571968 100644 (file)
@@ -16,12 +16,12 @@ import java.util.List;
 /**
  * PortGroupConfig class represents the User's Configuration with a Opaque
  * Regular Expression String that is parsed and handled by PortGroupProvider.
- * 
+ *
  * Typically, the opaque matchString will be a Regular Expression String
  * supported by a particular PortGroupProvider based on Customer requirements.
- * 
- * 
- * 
+ *
+ *
+ *
  */
 public class PortGroupConfig implements Serializable {
     private static final long serialVersionUID = 1L;
@@ -41,7 +41,7 @@ public class PortGroupConfig implements Serializable {
     /**
      * Constructor to create a Port Group Configuration using a Group Name and
      * an Opaque String that is managed by PortGroupProvider.
-     * 
+     *
      * @param name
      *            Group Name representing a Port Group configuration
      * @param matchString
@@ -55,7 +55,7 @@ public class PortGroupConfig implements Serializable {
 
     /**
      * Returns the user configured PortGroup Configuration name.
-     * 
+     *
      * @return Configuration Name
      */
     public String getName() {
@@ -64,7 +64,7 @@ public class PortGroupConfig implements Serializable {
 
     /**
      * Assigns a name to the configuration
-     * 
+     *
      * @param name
      *            configuration name
      */
@@ -74,7 +74,7 @@ public class PortGroupConfig implements Serializable {
 
     /**
      * Returns the Opaque string
-     * 
+     *
      * @return
      */
     public String getMatchString() {
@@ -83,7 +83,7 @@ public class PortGroupConfig implements Serializable {
 
     /**
      * Assigns an opaque String to the Configuration.
-     * 
+     *
      * @param matchString
      *            Opaque string handled by PortGroupProvider
      */
@@ -94,7 +94,7 @@ public class PortGroupConfig implements Serializable {
     /**
      * Returns the names of all the configurable fields in PortGroupConfig. This
      * method is typically used by NorthBound apis.
-     * 
+     *
      * @return List of Field names that can be configured.
      */
     public static List<String> getFieldsNames() {
@@ -113,7 +113,7 @@ public class PortGroupConfig implements Serializable {
      * Returns the names of all the configurable fields in PortGroupConfig in
      * human readable format for UI purposes. This method is typically used by
      * Web/UI apis.
-     * 
+     *
      * @return List of Human readable Strings that corresponds to the
      *         configurable field names.
      */
index 37cbcd17e6c149e57b0daab5da30085ce4d7f985..5a9281aea8da59ebc47a35627661b30ffbf23a5a 100644 (file)
@@ -17,15 +17,15 @@ import org.opendaylight.controller.sal.core.Node;
  * application to implement in order to provide Port Grouping Service. Custom
  * Application that implements this interface will have to handle the opaque
  * match criteria passed to it via PortGroupConfig.
- * 
- * 
- * 
+ *
+ *
+ *
  */
 public interface PortGroupProvider {
     /**
      * This method is invoked by the Controller towards the Provider when a new
      * port group is configured.
-     * 
+     *
      * @param config
      *            New PortGroupConfig object created by user Configuration.
      * @return true if successful. false otherwise.
@@ -35,7 +35,7 @@ public interface PortGroupProvider {
     /**
      * This method is invoked by the Controller towards the Provider when an
      * existing port group is deleted.
-     * 
+     *
      * @param config
      *            Existing Port Group Configuration deleted by the user.
      * @return true if successful. false otherwise.
@@ -47,7 +47,7 @@ public interface PortGroupProvider {
      * Configuration. Its the PortGroupProvider Application's responsibility to
      * manage the Switches & the Set of its Ports that correspond to each of the
      * Configuration and return it to the Controller when requested.
-     * 
+     *
      * @param config
      *            User Configuration
      * @see PortGroupConfig
@@ -61,7 +61,7 @@ public interface PortGroupProvider {
      * PortGroupProvider Application's responsibility to manage the Switches &
      * the Set of its Ports that correspond to each of the Configuration and
      * return it to the Controller when requested.
-     * 
+     *
      * @param config
      *            User Configuration
      * @param matrixSwitchId
@@ -76,7 +76,7 @@ public interface PortGroupProvider {
     /**
      * Registers a Listener for Port Group membership changes based on Custom
      * application algorithm.
-     * 
+     *
      * @param listener
      *            A Controller module that listens to events from the Custom
      *            Port Grouping Application.
@@ -89,7 +89,7 @@ public interface PortGroupProvider {
      * implement Custom Algorithm for Port Grouping. This method exposes the
      * custom algorithm to the user so that the user can configure the
      * matchString regular expression in PortGroupConfig appropriately.
-     * 
+     *
      * @return Usage string.
      */
     public String getApplicationDrivenMatchCriteriaUsage();
@@ -97,7 +97,7 @@ public interface PortGroupProvider {
     /**
      * Returns the name of the Custom Application that implements
      * PortGroupProvider interface.
-     * 
+     *
      * @return Provider Name
      */
     public String getProviderName();
@@ -105,7 +105,7 @@ public interface PortGroupProvider {
     /**
      * Controller uses this method to check with the Provider supports the
      * matchCriteria String configured by the User.
-     * 
+     *
      * @param matchCriteria
      * @return true if the Provider supports the matchCriteria String. false
      *         otherwise.
index d0a370276fa9d17995802e65c29193b911e266dc..969287719db083e747e25099e2f9fafbed50e4ff 100644 (file)
@@ -40,7 +40,7 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function called when the activator starts just after some initializations
      * are done by the ComponentActivatorAbstractBase.
-     * 
+     *
      */
     public void init() {
 
@@ -49,7 +49,7 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function called when the activator stops just before the cleanup done by
      * ComponentActivatorAbstractBase
-     * 
+     *
      */
     public void destroy() {
 
@@ -58,8 +58,8 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function that is used to communicate to dependency manager the list of
      * known implementations for services inside a container
-     * 
-     * 
+     *
+     *
      * @return An array containing all the CLASS objects that will be
      *         instantiated in order to get an fully working implementation
      *         Object
@@ -72,7 +72,7 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function that is called when configuration of the dependencies is
      * required.
-     * 
+     *
      * @param c
      *            dependency manager Component object, used for configuring the
      *            dependencies exported and imported
index 5fbe12bd1ca44218a9629e50489540bd85d83302..db1186e6b753a88e46ff9d2913f801d827764f01 100644 (file)
@@ -135,7 +135,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
      * Adds a flow entry onto the network node It runs various validity checks
      * and derive the final container flows merged entries that will be
      * attempted to be installed
-     * 
+     *
      * @param flowEntry
      *            the original flow entry application requested to add
      * @param async
@@ -144,7 +144,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
      *          will contain the unique id assigned to this request
      */
     private Status addEntry(FlowEntry flowEntry, boolean async) {
-        
+
         // Sanity Check
         if (flowEntry == null || flowEntry.getNode() == null) {
             String msg = "Invalid FlowEntry";
@@ -209,7 +209,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
                  * complication for now and assume we will always deal with
                  * one flow only per request
                  */
-                succeded = ret;   
+                succeded = ret;
             } else {
                 error = ret;
                 log.warn("Failed to install the entry: {}. The failure is: {}",
@@ -228,7 +228,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
      * flow entry is congruent with all the N container flows, then the output
      * install entry list will contain N entries. If the output list is empty,
      * it means the passed flow entry conflicts with all the container flows.
-     * 
+     *
      * @param cFlowList
      *            The list of container flows
      * @return the list of container flow merged entries good to be installed on
@@ -260,7 +260,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
     /**
      * Modify a flow entry with a new one It runs various validity check and
      * derive the final container flows merged flow entries to work with
-     * 
+     *
      * @param currentFlowEntry
      * @param newFlowEntry
      * @param async
@@ -335,13 +335,13 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
          * This is only possible when the new entry and current entry have
          * different match. In this scenario the modification would ultimately
          * be handled as a remove and add operations in the protocol plugin.
-         * 
+         *
          * Also, if any of the new flow entries would clash with an existing
          * one, we cannot proceed with the modify operation, because it would
          * fail for some entries and leave stale entries on the network node.
          * Modify path can be taken only if it can be performed completely, for
          * all entries.
-         * 
+         *
          * So, for the above two cases, to simplify, let's decouple the modify
          * in: 1) remove current entries 2) install new entries
          */
@@ -384,7 +384,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
              * (and might be wrong) that the same container flows that were
              * satisfied by the current entries are the same that are satisfied
              * by the new entries. Let's take the risk for now.
-             * 
+             *
              * Note: modification has to be complete. If any entry modification
              * fails, we need to stop, restore the already modified entries, and
              * declare failure.
@@ -440,7 +440,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
      * This is the function that modifies the final container flows merged
      * entries on the network node and update the database. It expects that all
      * the validity checks are passed
-     * 
+     *
      * @param currentEntries
      * @param newEntries
      * @param async
@@ -451,7 +451,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
     private Status modifyEntryInternal(FlowEntryInstall currentEntries,
             FlowEntryInstall newEntries, boolean async) {
         // Modify the flow on the network node
-        Status status = (async)? 
+        Status status = (async)?
                 programmer.modifyFlowAsync(currentEntries.getNode(),
                         currentEntries.getInstall().getFlow(), newEntries.getInstall()
                                 .getFlow()) :
@@ -481,7 +481,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
     /**
      * Remove a flow entry. If the entry is not present in the software view
      * (entry or node not present), it return successfully
-     * 
+     *
      * @param flowEntry
      *          the flow entry to remove
      * @param async
@@ -554,7 +554,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
      * This is the function that removes the final container flows merged entry
      * from the network node and update the database. It expects that all the
      * validity checks are passed
-     * 
+     *
      * @param entry
      *            the flow entry to remove
      * @param async
@@ -572,7 +572,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
                         .getInstall().getFlow()) :
                 programmer.removeFlow(entry.getNode(), entry
                         .getInstall().getFlow());
+
 
         if (!status.isSuccess()) {
             log.warn(
@@ -593,7 +593,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
      * on the network node and updates the database. It expects that all the
      * validity and conflict checks are passed. That means it does not check
      * whether this flow would conflict or overwrite an existing one.
-     * 
+     *
      * @param entry
      *            the flow entry to install
      * @param async
@@ -631,7 +631,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
      * means that if the function returns true, the passed flow entry is
      * congruent with at least one container flow, hence it is good to be
      * installed on this container.
-     * 
+     *
      * @param flowEntry
      * @return true if flow conflicts with all the container flows, false
      *         otherwise
@@ -837,7 +837,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
         }
         return status;
     }
-    
+
     @Override
     public Status modifyFlowEntry(FlowEntry currentFlowEntry,
             FlowEntry newFlowEntry) {
@@ -908,13 +908,13 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
         }
     }
 
-    
+
     /**
      * Try to find in the database if a Flow with the same Match and priority of
      * the passed one already exists for the specified network node. Flow,
      * priority and network node are all specified in the FlowEntry If found,
      * the respective FlowEntryInstall Object is returned
-     * 
+     *
      * @param flowEntry
      *            the FlowEntry to be tested against the ones installed
      * @param looseCheck
@@ -1409,9 +1409,9 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
          * multiple entry configuration (PortGroup) and hardware installation is
          * NOT done directly on this event. 3. The User prefers to retain the
          * configuration in Controller and skip hardware installation.
-         * 
+         *
          * Hence it is safe to update the StaticFlow DB at this point.
-         * 
+         *
          * Note : For the case of PortGrouping, it is essential to have this DB
          * populated before the PortGroupListeners can query for the DB
          * triggered using portGroupChanged event...
@@ -1924,7 +1924,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
 
     /**
      * Remove from the databases all the flows installed on the node
-     * 
+     *
      * @param node
      */
     private synchronized void cleanDatabaseForNode(Node node) {
@@ -2210,7 +2210,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
-     * 
+     *
      */
     void init() {
         frmAware = Collections
@@ -2245,7 +2245,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
         destroyCaches();
@@ -2254,7 +2254,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
     /**
      * Function called by dependency manager after "init ()" is called and after
      * the services provided by the class are registered in the service registry
-     * 
+     *
      */
     void start() {
         /*
@@ -2270,7 +2270,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
      * Function called by the dependency manager before the services exported by
      * the component are unregistered, this will be followed by a "destroy ()"
      * calls
-     * 
+     *
      */
     void stop() {
     }
@@ -2541,8 +2541,8 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
         /*
          *  If this was for a flow install, remove the corresponding entry
          *  from the software view. If it was a Looking for the rid going through the
-         *  software database. 
-         *  TODO: A more efficient rid <->  FlowEntryInstall mapping will 
+         *  software database.
+         *  TODO: A more efficient rid <->  FlowEntryInstall mapping will
          *  have to be added in future
          */
         Set<FlowEntryInstall> entries = nodeFlows.get(node);
@@ -2559,7 +2559,7 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
                 this.updateLocalDatabase(target, false);
             }
         }
-        
+
         // Notify listeners
         if (frmAware != null) {
             synchronized (frmAware) {
@@ -2573,19 +2573,19 @@ public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
             }
         }
     }
-    
+
     @Override
     public Status solicitStatusResponse(Node node, boolean blocking) {
         Status rv = new Status(StatusCode.INTERNALERROR);
-        
+
         if (this.programmer != null) {
             if (blocking) {
                 rv = programmer.syncSendBarrierMessage(node);
             } else {
-                rv = programmer.asyncSendBarrierMessage(node);                
+                rv = programmer.asyncSendBarrierMessage(node);
             }
         }
-        
+
         return rv;
     }
 }
index cb15fb09fd7e4e040013d8835730a7cd1c7a111c..51d68d87b43ab2ca19769bbd31455c141a4736fe 100644 (file)
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
  *
@@ -12,21 +11,21 @@ package org.opendaylight.controller.hosttracker;
 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
 
 /**
- * This interface defines the method to notify detected Host on the
- * network. The information includes Host's IP address, MAC address,
- * switch ID, port, and VLAN.
+ * This interface defines the method to notify detected Host on the network. The
+ * information includes Host's IP address, MAC address, switch ID, port, and
+ * VLAN.
  *
  */
 
 public interface IfHostListener {
     /**
-     * Learns  new Hosts. Called by ArpHandler and implemented in
-     * HostTracker.java. If a Host is learned for the first time then
-     * adds it to the local database and informs other applications
-     * of coming up a new Host. For the hosts which it has already
-     * learned, it refreshes them.
+     * Learns new Hosts. Called by ArpHandler and implemented in
+     * HostTracker.java. If a Host is learned for the first time then adds it to
+     * the local database and informs other applications of coming up a new
+     * Host. For the hosts which it has already learned, it refreshes them.
      *
-     * @param host             Host info encapsulated in HostNodeConnector class
+     * @param host
+     *            Host info encapsulated in HostNodeConnector class
      */
     public void hostListener(HostNodeConnector host);
 }
index 554da42f4a7b0323cf4fb49f0843d2fe57248e57..995ee575152f35f4f93bfe4983df771245af7d08 100644 (file)
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
  *
@@ -13,29 +12,31 @@ import java.net.InetAddress;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.Future;
-import org.opendaylight.controller.sal.core.NodeConnector;
+
 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
+import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.utils.Status;
 
 /**
- * This interface defines the methods to retrieve information about
- * learned Hosts. Also provides methods to statically add/remove
- * Hosts from the local database.
+ * This interface defines the methods to retrieve information about learned
+ * Hosts. Also provides methods to statically add/remove Hosts from the local
+ * database.
  *
  */
 
 public interface IfIptoHost {
     /**
-     * Applications call this interface methods to determine IP address to MAC binding and its
-     * connectivity to an OpenFlow switch in term of Node, Port, and VLAN. These
-     * bindings are learned dynamically as well as can be added statically through
-     * Northbound APIs. If a binding is unknown, then an ARP request is initiated
-     * immediately to discover the host.
+     * Applications call this interface methods to determine IP address to MAC
+     * binding and its connectivity to an OpenFlow switch in term of Node, Port,
+     * and VLAN. These bindings are learned dynamically as well as can be added
+     * statically through Northbound APIs. If a binding is unknown, then an ARP
+     * request is initiated immediately to discover the host.
      *
-     * @param networkAddress   IP Address of the Host encapsulated in class InetAddress
-     * @return                                 {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
-     *                                                         Class that contains the Host info such as its MAC address,
-     *                                                         Switch ID, port, VLAN. If Host is not found, returns NULL
+     * @param networkAddress
+     *            IP Address of the Host encapsulated in class InetAddress
+     * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+     *         Class that contains the Host info such as its MAC address, Switch
+     *         ID, port, VLAN. If Host is not found, returns NULL
      */
     public HostNodeConnector hostFind(InetAddress networkAddress);
 
@@ -43,10 +44,11 @@ public interface IfIptoHost {
      * Checks the local Host Database to see if a Host has been learned for a
      * given IP address.
      *
-     * @param networkAddress   IP Address of the Host encapsulated in class InetAddress
-     * @return                                 {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
-     *                                                         Class that contains the Host info such as its MAC address,
-     *                                                         Switch ID, port, VLAN. If Host is not found, returns NULL
+     * @param networkAddress
+     *            IP Address of the Host encapsulated in class InetAddress
+     * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+     *         Class that contains the Host info such as its MAC address, Switch
+     *         ID, port, VLAN. If Host is not found, returns NULL
      *
      */
     public HostNodeConnector hostQuery(InetAddress networkAddress);
@@ -55,73 +57,82 @@ public interface IfIptoHost {
      * Initiates an immediate discovery of the Host for a given IP address. This
      * provides for the calling applications to block on the host discovery.
      *
-     * @param networkAddress           IP address encapsulated in InetAddress class
-     * @return                                         Future {@link org.opendaylight.controller.hosttracker.HostTrackerCallable}
+     * @param networkAddress
+     *            IP address encapsulated in InetAddress class
+     * @return Future
+     *         {@link org.opendaylight.controller.hosttracker.HostTrackerCallable}
      */
     public Future<HostNodeConnector> discoverHost(InetAddress networkAddress);
 
     /**
-     * Returns the Network Hierarchy for a given Host. This API is typically used by
-     * applications like Hadoop for Rack Awareness functionality.
+     * Returns the Network Hierarchy for a given Host. This API is typically
+     * used by applications like Hadoop for Rack Awareness functionality.
      *
-     * @param                                  IP address of the Host encapsulated in InetAddress class
-     * @return                                 List of String ArrayList containing the Hierarchies.
+     * @param IP
+     *            address of the Host encapsulated in InetAddress class
+     * @return List of String ArrayList containing the Hierarchies.
      */
     public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress);
 
     /**
-     * Returns all the the Hosts either learned dynamically or added statically via
-     * Northbound APIs.
+     * Returns all the the Hosts either learned dynamically or added statically
+     * via Northbound APIs.
      *
-     * @return                                 Set of {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}.
-     *                                                         Class that contains the Host info such as its MAC address,
-     *                                                         Switch ID, port, VLAN.
+     * @return Set of
+     *         {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+     *         . Class that contains the Host info such as its MAC address,
+     *         Switch ID, port, VLAN.
      */
     public Set<HostNodeConnector> getAllHosts();
 
     /**
-     * Returns all the "Active Hosts" learned "Statically" via Northbound APIs. These Hosts
-     * are categorized as "Active" because the Switch and Port they are connected to, are in
-     * up state.
+     * Returns all the "Active Hosts" learned "Statically" via Northbound APIs.
+     * These Hosts are categorized as "Active" because the Switch and Port they
+     * are connected to, are in up state.
      *
-     * @return                                 Set of {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}.
-     *                                                         Class that contains the Host info such as MAC address,
-     *                                                         Switch ID, port, VLAN. If Host is not found, returns NULL
+     * @return Set of
+     *         {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+     *         . Class that contains the Host info such as MAC address, Switch
+     *         ID, port, VLAN. If Host is not found, returns NULL
      */
     public Set<HostNodeConnector> getActiveStaticHosts();
 
     /**
-     * Returns all the "Inactive Hosts" learned "Statically" via Northbound APIs. These Hosts
-     * are categorized as "Inactive" because either the Switch or the Port they are connected
-     * to, is in down state.
+     * Returns all the "Inactive Hosts" learned "Statically" via Northbound
+     * APIs. These Hosts are categorized as "Inactive" because either the Switch
+     * or the Port they are connected to, is in down state.
      *
-     * @return                                 Set of HostNodeConnector {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}.
-     *                                                         HostNodeConnector is Class that
-     *                                                         contains the Host info such as its MAC address, OpenFlowNode
-     *                                                         ID, port, VLAN.
+     * @return Set of HostNodeConnector
+     *         {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+     *         . HostNodeConnector is Class that contains the Host info such as
+     *         its MAC address, OpenFlowNode ID, port, VLAN.
      */
     public Set<HostNodeConnector> getInactiveStaticHosts();
 
     /**
-     * Hosts can be learned dynamically or added statically. This method allows the addition
-     * of a Host to the local database statically.
+     * Hosts can be learned dynamically or added statically. This method allows
+     * the addition of a Host to the local database statically.
      *
-     * @param networkAddress           IP Address of the Host
-     * @param dataLayerAddress         MAC Address of the Host
-     * @param nc                                   NodeConnector to which the host is attached
-     * @param vlan                                     VLAN the host belongs to
-     * @return                                         The status object as described in {@code Status}
-     *                                                                 indicating the result of this action.
+     * @param networkAddress
+     *            IP Address of the Host
+     * @param dataLayerAddress
+     *            MAC Address of the Host
+     * @param nc
+     *            NodeConnector to which the host is attached
+     * @param vlan
+     *            VLAN the host belongs to
+     * @return The status object as described in {@code Status} indicating the
+     *         result of this action.
      */
     public Status addStaticHost(String networkAddress, String dataLayerAddress,
-                                NodeConnector nc, String vlan);
+            NodeConnector nc, String vlan);
 
     /**
      * Allows the deletion of statically learned Host
      *
      * @param networkAddress
-     * @return                                         The status object as described in {@code Status}
-     *                                                                 indicating the result of this action.
+     * @return The status object as described in {@code Status} indicating the
+     *         result of this action.
      */
     public Status removeStaticHost(String networkAddress);
 }
index 88db0811d7c56e40fe565ec407e1772907434028..ef900e475ecc68b580e1a6946ef09470f36054fd 100644 (file)
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
  *
@@ -12,25 +11,27 @@ package org.opendaylight.controller.hosttracker;
 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
 
 /**
- * This Interface defines the methods for client applications of
- * Host Tracker to get notifications when a new host is learned or 
- * existing host is removed from the network.
+ * This Interface defines the methods for client applications of Host Tracker to
+ * get notifications when a new host is learned or existing host is removed from
+ * the network.
  *
  */
 public interface IfNewHostNotify {
     /**
      * Notifies the HostTracker Clients that a new Host has been learned
      *
-     * @param host             Host Info encapsulated in HostNodeConnector class
+     * @param host
+     *            Host Info encapsulated in HostNodeConnector class
      */
     public void notifyHTClient(HostNodeConnector host);
 
     /**
-     * Notifies the HostTracker Clients that a Host which was learned in
-     * the past has been removed either due to switch/port down event or
-     * due to ARP Aging
+     * Notifies the HostTracker Clients that a Host which was learned in the
+     * past has been removed either due to switch/port down event or due to ARP
+     * Aging
      *
-     * @param host             Host Info encapsulated in HostNodeConnector class
+     * @param host
+     *            Host Info encapsulated in HostNodeConnector class
      */
     public void notifyHTClientHostRemoved(HostNodeConnector host);
 }
index 243da05869a5edd4ec7d41eedccf61b2b5e1079f..8345b5adbceb4b12d8cf03b25f330513d829ce0c 100644 (file)
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
  *
@@ -19,14 +18,13 @@ import javax.xml.bind.annotation.XmlAccessorType;
 import javax.xml.bind.annotation.XmlElement;
 import javax.xml.bind.annotation.XmlRootElement;
 
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
 import org.opendaylight.controller.sal.core.ConstructionException;
 import org.opendaylight.controller.sal.core.Host;
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.packet.address.EthernetAddress;
 
-@XmlRootElement(name="host")
+@XmlRootElement(name = "host")
 @XmlAccessorType(XmlAccessType.NONE)
 public class HostNodeConnector extends Host {
     private static final long serialVersionUID = 1L;
@@ -173,13 +171,10 @@ public class HostNodeConnector extends Host {
         return !Arrays.equals(emptyArray, macaddr);
     }
 
-    /* (non-Javadoc)
-     * @see java.lang.Object#toString()
-     */
     @Override
     public String toString() {
-        return "HostNodeConnector[" + ReflectionToStringBuilder.toString(this)
-                + "]";
+        return "HostNodeConnector [nodeConnector=" + nodeConnector + ", vlan="
+                + vlan + ", staticHost=" + staticHost + "]";
     }
 
     public boolean isV4Host() {
index 5ea7fb0e49d2a7b7d87718df43c4ee52162334b3..abe75180cf676bdeab08d7fe0f5166d6bfa57c97 100644 (file)
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
  *
 package org.opendaylight.controller.hosttracker.hostAware;
 
 import java.net.InetAddress;
-import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
-
 
 /**
- * This Interface  defines the methods to trigger the discovery of
- * a Host and to probe if a learned Host is still in the network.
+ * This Interface defines the methods to trigger the discovery of a Host and to
+ * probe if a learned Host is still in the network.
  *
  *
  *
  */
 public interface IHostFinder {
     /**
-     * This method initiates the discovery of a host based on its IP address. This is triggered
-     * by query of an application to the HostTracker. The requested IP address
-     * doesn't exist in the local database at this point.
+     * This method initiates the discovery of a host based on its IP address.
+     * This is triggered by query of an application to the HostTracker. The
+     * requested IP address doesn't exist in the local database at this point.
      *
-     * @param networkAddress   IP Address encapsulated in InetAddress class
+     * @param networkAddress
+     *            IP Address encapsulated in InetAddress class
      *
      */
     public void find(InetAddress networkAddress);
 
     /**
-     * This method is called by HostTracker to see if a learned Host is still in the network.
-     * Used mostly for ARP Aging.
+     * This method is called by HostTracker to see if a learned Host is still in
+     * the network. Used mostly for ARP Aging.
      *
-     * @param host                     The Host that needs to be probed
+     * @param host
+     *            The Host that needs to be probed
      */
     public void probe(HostNodeConnector host);
 }
index c29e5b16453407e8999bdbaec21cd9eabc9185a5..bdccc99c9c52d29801bf43c7a7ebff602a207c65 100644 (file)
@@ -1,4 +1,3 @@
-\r
 /*\r
  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.\r
  *\r
@@ -26,64 +25,73 @@ import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
 import org.opendaylight.controller.sal.core.NodeConnector;\r
 import org.opendaylight.controller.sal.utils.NodeCreator;\r
 \r
-\r
 public class HostNodeConnectorTest extends TestCase {\r
 \r
-       @Test\r
-       public void testHostNodeConnector() throws UnknownHostException {\r
-               HostNodeConnector hostnodeconnector_1, hostnodeconnector_2, hostnodeconnector_3;\r
-               InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8");\r
-               InetAddress hostIP_2 = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0");\r
-               InetAddress hostIP_3 = InetAddress.getByName("192.168.0.28");\r
-               byte[] hostMAC_2 = new byte[]{(byte)0x11,(byte)0x22,(byte)0x33,(byte)0x22,(byte)0x22,(byte)0x22};\r
-               byte[] hostMAC_3 = new byte[]{(byte)0x11,(byte)0x22,(byte)0x33,(byte)0x33,(byte)0x33,(byte)0x33};\r
-               \r
-               Node node  = NodeCreator.createOFNode(1L);\r
-               NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector((short) 2, node);\r
-               NodeConnector nc2 = NodeConnectorCreator.createOFNodeConnector((short) 1, node);\r
-               \r
-               try {\r
-                       hostnodeconnector_1 = new HostNodeConnector(hostIP_1);\r
-                       Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1));\r
-                       Assert.assertTrue(hostnodeconnector_1.isV4Host());\r
-                       Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1));\r
-               } catch (ConstructionException e) {\r
-                       Assert.assertTrue(false);\r
-               }\r
-               \r
-               try {\r
-                       hostnodeconnector_2 = new HostNodeConnector(\r
-                               hostMAC_2, hostIP_2, nc1, (short)2);\r
-                       Assert.assertTrue(hostnodeconnector_2.isV6Host());\r
-                       Assert.assertTrue(hostnodeconnector_2.getnodeConnector().equals(nc1));\r
-                       Assert.assertTrue(hostnodeconnector_2.getnodeconnectorNode().equals(node));\r
-                        Assert.assertTrue(node.equals(hostnodeconnector_2.getnodeconnectorNode()));\r
-               } catch (ConstructionException e) {\r
-                       Assert.assertTrue(false);\r
-               }\r
-               \r
-               try {\r
-                       hostnodeconnector_3 = new HostNodeConnector(\r
-                                       new EthernetAddress(hostMAC_3), hostIP_3, nc2, (short)3);\r
-                       byte[] hostMAC_3_rb = hostnodeconnector_3.getDataLayerAddressBytes();\r
-                       HostNodeConnector  hostnodeconnector_3rb = new HostNodeConnector(\r
-                                       new EthernetAddress(hostMAC_3_rb), hostIP_3, nc2, (short)3);\r
-                       Assert.assertTrue(hostnodeconnector_3.equals(hostnodeconnector_3rb));\r
-                       \r
-                       Assert.assertTrue(hostnodeconnector_3.getVlan() == (short)3);\r
-                       \r
-                       hostnodeconnector_3.setStaticHost(true);\r
-                       Assert.assertTrue(hostnodeconnector_3.isStaticHost());\r
-                       \r
-                       Assert.assertTrue(hostnodeconnector_3.isRewriteEnabled());\r
-                       \r
-                       hostnodeconnector_3.initArpSendCountDown().setArpSendCountDown((short) 10);\r
-                       Assert.assertTrue(hostnodeconnector_3.getArpSendCountDown() == (short)10);\r
-                       \r
-               } catch (ConstructionException e) {\r
-                       Assert.assertTrue(false);\r
-               }\r
-               \r
-       }\r
+    @Test\r
+    public void testHostNodeConnector() throws UnknownHostException {\r
+        HostNodeConnector hostnodeconnector_1, hostnodeconnector_2, hostnodeconnector_3;\r
+        InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8");\r
+        InetAddress hostIP_2 = InetAddress\r
+                .getByName("2001:420:281:1004:e123:e688:d655:a1b0");\r
+        InetAddress hostIP_3 = InetAddress.getByName("192.168.0.28");\r
+        byte[] hostMAC_2 = new byte[] { (byte) 0x11, (byte) 0x22, (byte) 0x33,\r
+                (byte) 0x22, (byte) 0x22, (byte) 0x22 };\r
+        byte[] hostMAC_3 = new byte[] { (byte) 0x11, (byte) 0x22, (byte) 0x33,\r
+                (byte) 0x33, (byte) 0x33, (byte) 0x33 };\r
+\r
+        Node node = NodeCreator.createOFNode(1L);\r
+        NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector(\r
+                (short) 2, node);\r
+        NodeConnector nc2 = NodeConnectorCreator.createOFNodeConnector(\r
+                (short) 1, node);\r
+\r
+        try {\r
+            hostnodeconnector_1 = new HostNodeConnector(hostIP_1);\r
+            Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1));\r
+            Assert.assertTrue(hostnodeconnector_1.isV4Host());\r
+            Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1));\r
+        } catch (ConstructionException e) {\r
+            Assert.assertTrue(false);\r
+        }\r
+\r
+        try {\r
+            hostnodeconnector_2 = new HostNodeConnector(hostMAC_2, hostIP_2,\r
+                    nc1, (short) 2);\r
+            Assert.assertTrue(hostnodeconnector_2.isV6Host());\r
+            Assert.assertTrue(hostnodeconnector_2.getnodeConnector()\r
+                    .equals(nc1));\r
+            Assert.assertTrue(hostnodeconnector_2.getnodeconnectorNode()\r
+                    .equals(node));\r
+            Assert.assertTrue(node.equals(hostnodeconnector_2\r
+                    .getnodeconnectorNode()));\r
+        } catch (ConstructionException e) {\r
+            Assert.assertTrue(false);\r
+        }\r
+\r
+        try {\r
+            hostnodeconnector_3 = new HostNodeConnector(new EthernetAddress(\r
+                    hostMAC_3), hostIP_3, nc2, (short) 3);\r
+            byte[] hostMAC_3_rb = hostnodeconnector_3\r
+                    .getDataLayerAddressBytes();\r
+            HostNodeConnector hostnodeconnector_3rb = new HostNodeConnector(\r
+                    new EthernetAddress(hostMAC_3_rb), hostIP_3, nc2, (short) 3);\r
+            Assert.assertTrue(hostnodeconnector_3.equals(hostnodeconnector_3rb));\r
+\r
+            Assert.assertTrue(hostnodeconnector_3.getVlan() == (short) 3);\r
+\r
+            hostnodeconnector_3.setStaticHost(true);\r
+            Assert.assertTrue(hostnodeconnector_3.isStaticHost());\r
+\r
+            Assert.assertTrue(hostnodeconnector_3.isRewriteEnabled());\r
+\r
+            hostnodeconnector_3.initArpSendCountDown().setArpSendCountDown(\r
+                    (short) 10);\r
+            Assert.assertTrue(hostnodeconnector_3.getArpSendCountDown() == (short) 10);\r
+\r
+        } catch (ConstructionException e) {\r
+            Assert.assertTrue(false);\r
+        }\r
+\r
+    }\r
 \r
 }\r
index ef88fa2e1660a2cf4f495c43f6a8c2fa8b0d86b7..65cb8225c856ef9d5c0a693284e3266e72c0a2ae 100644 (file)
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
  *
 package org.opendaylight.controller.hosttracker.internal;
 
 import org.apache.felix.dm.Component;
-import org.opendaylight.controller.hosttracker.internal.HostTracker;
+import org.opendaylight.controller.clustering.services.IClusterContainerServices;
 import org.opendaylight.controller.hosttracker.IfHostListener;
 import org.opendaylight.controller.hosttracker.IfIptoHost;
 import org.opendaylight.controller.hosttracker.IfNewHostNotify;
 import org.opendaylight.controller.hosttracker.hostAware.IHostFinder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.opendaylight.controller.clustering.services.IClusterContainerServices;
 import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase;
 import org.opendaylight.controller.switchmanager.IInventoryListener;
 import org.opendaylight.controller.switchmanager.ISwitchManager;
 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
 import org.opendaylight.controller.topologymanager.ITopologyManager;
 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class Activator extends ComponentActivatorAbstractBase {
     protected static final Logger logger = LoggerFactory
             .getLogger(Activator.class);
 
     /**
-     * Function called when the activator starts just after some
-     * initializations are done by the
-     * ComponentActivatorAbstractBase.
+     * Function called when the activator starts just after some initializations
+     * are done by the ComponentActivatorAbstractBase.
      *
      */
     public void init() {
     }
 
     /**
-     * Function called when the activator stops just before the
-     * cleanup done by ComponentActivatorAbstractBase
+     * Function called when the activator stops just before the cleanup done by
+     * ComponentActivatorAbstractBase
      *
      */
     public void destroy() {
     }
 
     /**
-     * Function that is used to communicate to dependency manager the
-     * list of known implementations for services inside a container
+     * Function that is used to communicate to dependency manager the list of
+     * known implementations for services inside a container
      *
      *
      * @return An array containing all the CLASS objects that will be
-     * instantiated in order to get an fully working implementation
-     * Object
+     *         instantiated in order to get an fully working implementation
+     *         Object
      */
     public Object[] getImplementations() {
         Object[] res = { HostTracker.class };
@@ -62,57 +58,64 @@ public class Activator extends ComponentActivatorAbstractBase {
     }
 
     /**
-     * Function that is called when configuration of the dependencies
-     * is required.
+     * Function that is called when configuration of the dependencies is
+     * required.
      *
-     * @param c dependency manager Component object, used for
-     * configuring the dependencies exported and imported
-     * @param imp Implementation class that is being configured,
-     * needed as long as the same routine can configure multiple
-     * implementations
-     * @param containerName The containerName being configured, this allow
-     * also optional per-container different behavior if needed, usually
-     * should not be the case though.
+     * @param c
+     *            dependency manager Component object, used for configuring the
+     *            dependencies exported and imported
+     * @param imp
+     *            Implementation class that is being configured, needed as long
+     *            as the same routine can configure multiple implementations
+     * @param containerName
+     *            The containerName being configured, this allow also optional
+     *            per-container different behavior if needed, usually should not
+     *            be the case though.
      */
     public void configureInstance(Component c, Object imp, String containerName) {
         if (imp.equals(HostTracker.class)) {
             // export the service
-            c.setInterface(new String[] { ISwitchManagerAware.class.getName(),
-                    IInventoryListener.class.getName(),
-                    IfIptoHost.class.getName(), IfHostListener.class.getName(),
-                    ITopologyManagerAware.class.getName() }, null);
+            c.setInterface(
+                    new String[] { ISwitchManagerAware.class.getName(),
+                            IInventoryListener.class.getName(),
+                            IfIptoHost.class.getName(),
+                            IfHostListener.class.getName(),
+                            ITopologyManagerAware.class.getName() }, null);
 
-            c.add(createContainerServiceDependency(containerName).setService(
-                    ISwitchManager.class).setCallbacks("setSwitchManager",
-                    "unsetSwitchManager").setRequired(false));
-            c.add(createContainerServiceDependency(containerName).setService(
-                    IClusterContainerServices.class).setCallbacks(
-                    "setClusterContainerService",
-                    "unsetClusterContainerService").setRequired(true));
-            c.add(createContainerServiceDependency(containerName).setService(
-                    IHostFinder.class).setCallbacks("setArpHandler",
-                    "unsetArpHandler").setRequired(false));
-            c.add(createContainerServiceDependency(containerName).setService(
-                    ITopologyManager.class).setCallbacks("setTopologyManager",
-                    "unsetTopologyManager").setRequired(false));
-            c.add(createContainerServiceDependency(containerName).setService(
-                    IfNewHostNotify.class).setCallbacks("setnewHostNotify",
-                    "unsetnewHostNotify").setRequired(false));
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(ISwitchManager.class)
+                    .setCallbacks("setSwitchManager", "unsetSwitchManager")
+                    .setRequired(false));
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(IClusterContainerServices.class)
+                    .setCallbacks("setClusterContainerService",
+                            "unsetClusterContainerService").setRequired(true));
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(IHostFinder.class)
+                    .setCallbacks("setArpHandler", "unsetArpHandler")
+                    .setRequired(false));
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(ITopologyManager.class)
+                    .setCallbacks("setTopologyManager", "unsetTopologyManager")
+                    .setRequired(false));
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(IfNewHostNotify.class)
+                    .setCallbacks("setnewHostNotify", "unsetnewHostNotify")
+                    .setRequired(false));
         }
     }
 
     /**
-     * Method which tells how many Global implementations are
-     * supported by the bundle. This way we can tune the number of
-     * components created. This components will be created ONLY at the
-     * time of bundle startup and will be destroyed only at time of
-     * bundle destruction, this is the major difference with the
-     * implementation retrieved via getImplementations where all of
-     * them are assumed to be in a container !
+     * Method which tells how many Global implementations are supported by the
+     * bundle. This way we can tune the number of components created. This
+     * components will be created ONLY at the time of bundle startup and will be
+     * destroyed only at time of bundle destruction, this is the major
+     * difference with the implementation retrieved via getImplementations where
+     * all of them are assumed to be in a container !
      *
      *
-     * @return The list of implementations the bundle will support,
-     * in Global version
+     * @return The list of implementations the bundle will support, in Global
+     *         version
      */
     protected Object[] getGlobalImplementations() {
         return null;
@@ -121,10 +124,13 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Configure the dependency for a given instance Global
      *
-     * @param c Component assigned for this instance, this will be
-     * what will be used for configuration
-     * @param imp implementation to be configured
-     * @param containerName container on which the configuration happens
+     * @param c
+     *            Component assigned for this instance, this will be what will
+     *            be used for configuration
+     * @param imp
+     *            implementation to be configured
+     * @param containerName
+     *            container on which the configuration happens
      */
     protected void configureGlobalInstance(Component c, Object imp) {
         if (imp.equals(HostTracker.class)) {
index f8534e98101702b6ce1039714eb9a647392cf85f..707a7761389c1b0dcf3d6c6cc4706c95c944f96f 100644 (file)
@@ -33,11 +33,11 @@ import org.opendaylight.controller.clustering.services.CacheConfigException;
 import org.opendaylight.controller.clustering.services.CacheExistException;
 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
 import org.opendaylight.controller.clustering.services.IClusterServices;
-import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
-import org.opendaylight.controller.hosttracker.hostAware.IHostFinder;
 import org.opendaylight.controller.hosttracker.IfHostListener;
 import org.opendaylight.controller.hosttracker.IfIptoHost;
 import org.opendaylight.controller.hosttracker.IfNewHostNotify;
+import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
+import org.opendaylight.controller.hosttracker.hostAware.IHostFinder;
 import org.opendaylight.controller.sal.core.ConstructionException;
 import org.opendaylight.controller.sal.core.Edge;
 import org.opendaylight.controller.sal.core.Host;
@@ -433,7 +433,7 @@ public class HostTracker implements IfIptoHost, IfHostListener,
                  */
                 removePendingARPFromList(i);
                 logger.debug("Host Removed from ARPPending List, IP: {}",
-                          networkAddr);
+                        networkAddr);
                 return;
             }
         }
@@ -991,13 +991,14 @@ public class HostTracker implements IfIptoHost, IfHostListener,
                      * there
                      */
                     if (logger.isTraceEnabled()) {
-                      logger.trace(
-                              "ARP Probing ({}) for {}({})",
-                              new Object[] {
-                                      arp_cntdown,
-                                      host.getNetworkAddress().getHostAddress(),
-                                      HexEncode.bytesToHexString(host
-                                              .getDataLayerAddressBytes()) });
+                        logger.trace(
+                                "ARP Probing ({}) for {}({})",
+                                new Object[] {
+                                        arp_cntdown,
+                                        host.getNetworkAddress()
+                                                .getHostAddress(),
+                                        HexEncode.bytesToHexString(host
+                                                .getDataLayerAddressBytes()) });
                     }
                     host.setArpSendCountDown(arp_cntdown);
                     hostFinder.probe(host);
@@ -1260,7 +1261,9 @@ public class HostTracker implements IfIptoHost, IfHostListener,
         for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
             HostNodeConnector host = entry.getValue();
             if (host.getnodeConnector().equals(nodeConnector)) {
-                logger.debug(" NodeConnector: {} is down, remove from Hosts_DB", nodeConnector);
+                logger.debug(
+                        " NodeConnector: {} is down, remove from Hosts_DB",
+                        nodeConnector);
                 removeKnownHost(entry.getKey());
                 notifyHostLearnedOrRemoved(host, false);
             }
index 0af523aaa9b22dbedd7f54d0da0edf26b6e0aecb..06311a5206268ae79fe8ebe32970a395423cf162 100644 (file)
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
  *
@@ -15,8 +14,8 @@ package org.opendaylight.controller.hosttracker.internal;
 
 /**
  * This Class provides methods to discover Host through a blocking call
- * mechanism. Applications can make use of these methods if they don't 
- * find a host in HostTracker's database and want to discover the host  
+ * mechanism. Applications can make use of these methods if they don't
+ * find a host in HostTracker's database and want to discover the host
  * in the same thread without being called by a callback function.
  */
 import java.net.InetAddress;
index 9bd28c8e45315a5c7be43ad08a62909612004291..25de544f52e8d0dd79da9afff83e2eda1e28a145 100644 (file)
@@ -1,4 +1,3 @@
-\r
 /*\r
  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.\r
  *\r
@@ -9,51 +8,48 @@
 \r
 package org.opendaylight.controller.hosttracker.internal;\r
 \r
-\r
 import java.net.InetAddress;\r
 import java.net.UnknownHostException;\r
 import java.util.concurrent.Future;\r
 \r
+import junit.framework.TestCase;\r
+\r
 import org.junit.Assert;\r
 import org.junit.Test;\r
-\r
-import junit.framework.TestCase;\r
 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;\r
 \r
 public class HostTrackerTest extends TestCase {\r
 \r
-       @Test\r
-       public void testHostTrackerCallable() throws UnknownHostException {\r
-               \r
-               HostTracker hostTracker = null;\r
-               hostTracker = new HostTracker();\r
-               Assert.assertFalse(hostTracker== null);\r
-               \r
-               InetAddress hostIP = InetAddress.getByName("192.168.0.8");\r
-               \r
-               HostTrackerCallable htCallable = new HostTrackerCallable (hostTracker, hostIP);\r
-               Assert.assertTrue(htCallable.trackedHost.equals(hostIP));\r
-               Assert.assertTrue(htCallable.hostTracker.equals(hostTracker));\r
-\r
-               long count = htCallable.latch.getCount();\r
-               htCallable.wakeup();\r
-               Assert.assertTrue(htCallable.latch.getCount() == --count );\r
-       }               \r
-               \r
-       \r
-       \r
-       @Test\r
-       public void testHostTracker() throws UnknownHostException {\r
-               HostTracker hostTracker = null;\r
-               hostTracker = new HostTracker();\r
-               Assert.assertFalse(hostTracker== null);\r
-               \r
-               InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8");\r
-               InetAddress hostIP_2 = InetAddress.getByName("192.168.0.18");\r
-               Future<HostNodeConnector> dschost = hostTracker.discoverHost(hostIP_1);\r
-               dschost = hostTracker.discoverHost(hostIP_2);\r
-               hostTracker.nonClusterObjectCreate();\r
-       }\r
-       \r
+    @Test\r
+    public void testHostTrackerCallable() throws UnknownHostException {\r
+\r
+        HostTracker hostTracker = null;\r
+        hostTracker = new HostTracker();\r
+        Assert.assertFalse(hostTracker == null);\r
+\r
+        InetAddress hostIP = InetAddress.getByName("192.168.0.8");\r
+\r
+        HostTrackerCallable htCallable = new HostTrackerCallable(hostTracker,\r
+                hostIP);\r
+        Assert.assertTrue(htCallable.trackedHost.equals(hostIP));\r
+        Assert.assertTrue(htCallable.hostTracker.equals(hostTracker));\r
+\r
+        long count = htCallable.latch.getCount();\r
+        htCallable.wakeup();\r
+        Assert.assertTrue(htCallable.latch.getCount() == --count);\r
+    }\r
+\r
+    @Test\r
+    public void testHostTracker() throws UnknownHostException {\r
+        HostTracker hostTracker = null;\r
+        hostTracker = new HostTracker();\r
+        Assert.assertFalse(hostTracker == null);\r
+\r
+        InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8");\r
+        InetAddress hostIP_2 = InetAddress.getByName("192.168.0.18");\r
+        Future<HostNodeConnector> dschost = hostTracker.discoverHost(hostIP_1);\r
+        dschost = hostTracker.discoverHost(hostIP_2);\r
+        hostTracker.nonClusterObjectCreate();\r
+    }\r
 \r
 }\r
index 1cf320b4df37ad61a7539c4a67643f9dfda2afaa..04219502f6eff56cc6f80d545dc38d5dca1e4d25 100644 (file)
@@ -59,8 +59,7 @@ import org.ops4j.pax.exam.spi.reactors.PerClass;
 \r
 @RunWith(PaxExam.class)\r
 public class HostTrackerIT {\r
-    private Logger log = LoggerFactory\r
-            .getLogger(HostTrackerIT.class);\r
+    private Logger log = LoggerFactory.getLogger(HostTrackerIT.class);\r
     // get the OSGI bundle context\r
     @Inject\r
     private BundleContext bc;\r
diff --git a/opendaylight/hosttracker_new/api/pom.xml b/opendaylight/hosttracker_new/api/pom.xml
new file mode 100644 (file)
index 0000000..6a98c71
--- /dev/null
@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\r
+  <modelVersion>4.0.0</modelVersion>\r
+  <parent>\r
+    <groupId>org.opendaylight.controller</groupId>\r
+    <artifactId>commons.opendaylight</artifactId>\r
+    <version>1.4.0-SNAPSHOT</version>\r
+    <relativePath>../../commons/opendaylight</relativePath>\r
+  </parent>\r
+  <artifactId>hosttracker_new</artifactId>\r
+  <version>0.4.0-SNAPSHOT</version>\r
+  <packaging>bundle</packaging>\r
+\r
+  <build>\r
+    <plugins>\r
+      <plugin>\r
+        <groupId>org.apache.felix</groupId>\r
+        <artifactId>maven-bundle-plugin</artifactId>\r
+        <version>2.3.6</version>\r
+        <extensions>true</extensions>\r
+        <configuration>\r
+          <instructions>\r
+            <Export-Package>\r
+              org.opendaylight.controller.hosttracker,\r
+              org.opendaylight.controller.hosttracker.hostAware\r
+            </Export-Package>\r
+            <Import-Package>\r
+              org.opendaylight.controller.sal.core,\r
+              org.opendaylight.controller.sal.utils,\r
+              org.opendaylight.controller.topologymanager,\r
+              org.opendaylight.controller.sal.packet.address,\r
+              org.opendaylight.controller.switchmanager,\r
+              org.opendaylight.controller.clustering.services,\r
+              javax.xml.bind.annotation,\r
+              javax.xml.bind,\r
+              org.apache.felix.dm,\r
+              org.apache.commons.lang3.builder,\r
+              org.osgi.service.component,\r
+              org.slf4j,\r
+              org.eclipse.osgi.framework.console,\r
+              org.osgi.framework\r
+            </Import-Package>\r
+          </instructions>\r
+          <manifestLocation>${project.basedir}/META-INF</manifestLocation>\r
+        </configuration>\r
+      </plugin>\r
+    </plugins>\r
+  </build>\r
+  <dependencies>\r
+    <dependency>\r
+      <groupId>org.opendaylight.controller</groupId>\r
+      <artifactId>topologymanager</artifactId>\r
+      <version>0.4.0-SNAPSHOT</version>\r
+    </dependency>\r
+    <dependency>\r
+      <groupId>org.opendaylight.controller</groupId>\r
+      <artifactId>switchmanager</artifactId>\r
+      <version>0.4.0-SNAPSHOT</version>\r
+    </dependency>\r
+    <dependency>\r
+      <groupId>org.opendaylight.controller</groupId>\r
+      <artifactId>clustering.services</artifactId>\r
+      <version>0.4.0-SNAPSHOT</version>\r
+    </dependency>\r
+    <dependency>\r
+      <groupId>org.opendaylight.controller</groupId>\r
+      <artifactId>sal</artifactId>\r
+      <version>0.5.0-SNAPSHOT</version>\r
+    </dependency>\r
+  </dependencies>\r
+</project>\r
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/Entity.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/Entity.java
new file mode 100644 (file)
index 0000000..7c98e95
--- /dev/null
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2011,2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker;
+
+import java.util.Date;
+
+import org.opendaylight.controller.sal.core.NodeConnector;
+
+/**
+ * An entity on the network is a visible trace of a device that corresponds to a
+ * packet received from a particular interface on the edge of a network, with a
+ * particular VLAN tag, and a particular MAC address, along with any other
+ * packet characteristics we might want to consider as helpful for
+ * disambiguating devices.
+ *
+ * Entities are the most basic element of devices; devices consist of one or
+ * more entities. Entities are immutable once created, except for the last seen
+ * timestamp.
+ *
+ * @author readams
+ *
+ */
+public class Entity implements Comparable<Entity> {
+    /**
+     * Timeout for computing {@link Entity#activeSince}.
+     *
+     * @see {@link Entity#activeSince}
+     */
+    protected static int ACTIVITY_TIMEOUT = 30000;
+
+    /**
+     * The MAC address associated with this entity
+     */
+    protected long macAddress;
+
+    /**
+     * The IP address associated with this entity, or null if no IP learned from
+     * the network observation associated with this entity
+     */
+    protected Integer ipv4Address;
+
+    /**
+     * The VLAN tag on this entity, or null if untagged
+     */
+    protected Short vlan;
+
+    /**
+     * The attachment point for this entity
+     */
+    NodeConnector port;
+
+    /**
+     * The last time we observed this entity on the network
+     */
+    protected Date lastSeenTimestamp;
+
+    /**
+     * The time between {@link Entity#activeSince} and
+     * {@link Entity#lastSeenTimestamp} is a period of activity for this entity
+     * where it was observed repeatedly. If, when the entity is observed, the is
+     * longer ago than the activity timeout, {@link Entity#lastSeenTimestamp}
+     * and {@link Entity#activeSince} will be set to the current time.
+     */
+    protected Date activeSince;
+
+    private int hashCode = 0;
+
+    // ************
+    // Constructors
+    // ************
+
+    /**
+     * Create a new entity
+     *
+     * @param macAddress
+     * @param vlan
+     * @param ipv4Address
+     * @param switchDPID
+     * @param switchPort
+     * @param lastSeenTimestamp
+     */
+    public Entity(long macAddress, Short vlan, Integer ipv4Address,
+            NodeConnector port, Date lastSeenTimestamp) {
+        this.macAddress = macAddress;
+        this.ipv4Address = ipv4Address;
+        this.vlan = vlan;
+        this.port = port;
+        this.lastSeenTimestamp = lastSeenTimestamp;
+        this.activeSince = lastSeenTimestamp;
+    }
+
+    // ***************
+    // Getters/Setters
+    // ***************
+
+    // @JsonSerialize(using=MACSerializer.class)
+    public long getMacAddress() {
+        return macAddress;
+    }
+
+    // @JsonSerialize(using=IPv4Serializer.class)
+    public Integer getIpv4Address() {
+        return ipv4Address;
+    }
+
+    public Short getVlan() {
+        return vlan;
+    }
+
+    public NodeConnector getPort() {
+        return port;
+    }
+
+    // @JsonIgnore
+    public boolean hasSwitchPort() {
+        return port != null;
+    }
+
+    public Date getLastSeenTimestamp() {
+        return lastSeenTimestamp;
+    }
+
+    /**
+     * Set the last seen timestamp and also update {@link Entity#activeSince} if
+     * appropriate
+     *
+     * @param lastSeenTimestamp
+     *            the new last seen timestamp
+     * @see {@link Entity#activeSince}
+     */
+    public void setLastSeenTimestamp(Date lastSeenTimestamp) {
+        if (activeSince == null
+                || (activeSince.getTime() + ACTIVITY_TIMEOUT) < lastSeenTimestamp
+                        .getTime())
+            this.activeSince = lastSeenTimestamp;
+        this.lastSeenTimestamp = lastSeenTimestamp;
+    }
+
+    public Date getActiveSince() {
+        return activeSince;
+    }
+
+    public void setActiveSince(Date activeSince) {
+        this.activeSince = activeSince;
+    }
+
+    @Override
+    public int hashCode() {
+        if (hashCode != 0)
+            return hashCode;
+        final int prime = 31;
+        hashCode = 1;
+        hashCode = prime * hashCode
+                + ((ipv4Address == null) ? 0 : ipv4Address.hashCode());
+        hashCode = prime * hashCode + (int) (macAddress ^ (macAddress >>> 32));
+        hashCode = prime * hashCode + ((port == null) ? 0 : port.hashCode());
+        hashCode = prime * hashCode + ((vlan == null) ? 0 : vlan.hashCode());
+        return hashCode;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        Entity other = (Entity) obj;
+        if (ipv4Address == null) {
+            if (other.ipv4Address != null)
+                return false;
+        } else if (!ipv4Address.equals(other.ipv4Address))
+            return false;
+        if (macAddress != other.macAddress)
+            return false;
+        if (port == null) {
+            if (other.port != null)
+                return false;
+        } else if (!port.equals(other.port))
+            return false;
+        if (vlan == null) {
+            if (other.vlan != null)
+                return false;
+        } else if (!vlan.equals(other.vlan))
+            return false;
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        return "Entity [macAddress=" + macAddress + ", ipv4Address="
+                + ipv4Address + ", vlan=" + vlan + ", port=" + port + "]";
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @Override
+    public int compareTo(Entity o) {
+        int r;
+        if (port == null)
+            r = o.port == null ? 0 : -1;
+        else if (o.port == null)
+            r = 1;
+        else {
+            // XXX - the node id is only defined as an object rather
+            // than something useful. We're just going to have to
+            // blindly cast to Comparable and hope it works.
+            Comparable switchId = (Comparable) port.getNode().getID();
+            Comparable oswitchId = (Comparable) o.port.getNode().getID();
+            r = switchId.compareTo(oswitchId);
+            if (r != 0)
+                return r;
+
+            Comparable portId = (Comparable) port.getID();
+            Comparable oportId = (Comparable) o.port.getID();
+            r = portId.compareTo(oportId);
+        }
+        return r;
+    }
+
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDevice.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDevice.java
new file mode 100644 (file)
index 0000000..b2ba643
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2011,2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker;
+
+import java.util.Date;
+
+import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
+
+/**
+ * Represents an independent device on the network. A device consists of a set
+ * of entities, and all the information known about a given device comes only
+ * from merging all associated entities for that device.
+ *
+ * @author readams
+ */
+public interface IDevice {
+    /**
+     * Get the primary key for this device.
+     *
+     * @return the primary key
+     */
+    public Long getDeviceKey();
+
+    /**
+     * Get the MAC address of the device as a Long value.
+     *
+     * @return the MAC address for the device
+     */
+    public long getMACAddress();
+
+    /**
+     * Get the MAC address of the device as a String value.
+     *
+     * @return the MAC address for the device
+     */
+    public String getMACAddressString();
+
+    /**
+     * Get all unique VLAN IDs for the device. If the device has untagged
+     * entities, then the value -1 will be returned.
+     *
+     * @return an array containing all unique VLAN IDs for the device.
+     */
+    public Short[] getVlanId();
+
+    /**
+     * Get all unique IPv4 addresses associated with the device.
+     *
+     * @return an array containing the unique IPv4 addresses for the device.
+     */
+    public Integer[] getIPv4Addresses();
+
+    /**
+     * Get all unique attachment points associated with the device. This will
+     * not include any blocked attachment points.
+     *
+     * @return an array containing all unique attachment points for the device
+     */
+    public SwitchPort[] getAttachmentPoints();
+
+    /**
+     * Get all old attachment points associated with the device. this is used in
+     * host movement scenario.
+     *
+     * @return an array containing all unique old attachment points for the
+     *         device
+     */
+    public SwitchPort[] getOldAP();
+
+    /**
+     * Get all unique attachment points associated with the device.
+     *
+     * @param includeError
+     *            whether to include blocked attachment points. Blocked
+     *            attachment points should not be used for forwarding, but could
+     *            be useful to show to a user
+     * @return an array containing all unique attachment points for the device
+     */
+    public SwitchPort[] getAttachmentPoints(boolean includeError);
+
+    /**
+     * Returns all unique VLAN IDs for the device that were observed on the
+     * given switch port
+     *
+     * @param swp
+     *            the switch port to query
+     * @return an array containing the unique VLAN IDs
+     */
+    public Short[] getSwitchPortVlanIds(SwitchPort swp);
+
+    /**
+     * Get the most recent timestamp for this device
+     *
+     * @return the last seen timestamp
+     */
+    public Date getLastSeen();
+
+    /**
+     * Get the entity class for the device.
+     *
+     * @return the entity class
+     * @see IEntityClassifierService
+     */
+    public IEntityClass getEntityClass();
+
+    public HostNodeConnector toHostNodeConnector();
+
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceListener.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceListener.java
new file mode 100644 (file)
index 0000000..5861915
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2011 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker;
+
+import org.opendaylight.controller.sal.utils.IListener;
+
+/**
+ * Implementors of this interface can receive updates from DeviceManager about
+ * the state of devices under its control.
+ *
+ * @author David Erickson (daviderickson@cs.stanford.edu)
+ */
+public interface IDeviceListener extends IListener<String> {
+    /**
+     * Called when a new Device is found
+     *
+     * @param device
+     *            the device that changed
+     */
+    public void deviceAdded(IDevice device);
+
+    /**
+     * Called when a Device is removed, this typically occurs when the port the
+     * Device is attached to goes down, or the switch it is attached to is
+     * removed.
+     *
+     * @param device
+     *            the device that changed
+     */
+    public void deviceRemoved(IDevice device);
+
+    /**
+     * Called when a Device has moved to a new location on the network. Note
+     * that either the switch or the port or both has changed.
+     *
+     * @param device
+     *            the device that changed
+     */
+    public void deviceMoved(IDevice device);
+
+    /**
+     * Called when a network address has been added or remove from a device
+     *
+     * @param device
+     *            the device that changed
+     */
+    public void deviceIPV4AddrChanged(IDevice device);
+
+    /**
+     * Called when a VLAN tag for the device has been added or removed
+     *
+     * @param device
+     *            the device that changed
+     */
+    public void deviceVlanChanged(IDevice device);
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceService.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceService.java
new file mode 100755 (executable)
index 0000000..9199f5a
--- /dev/null
@@ -0,0 +1,241 @@
+/*
+ * Copyright (c) 2011,2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker;
+
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.osgi.service.device.Device;
+
+/**
+ * Device manager allows interacting with devices on the network. Note that
+ * under normal circumstances, {@link Device} objects should be retrieved from
+ * the {@link FloodlightContext} rather than from {@link IDeviceManager}.
+ */
+public interface IDeviceService {
+
+    /**
+     * Fields used in devices for indexes and querying
+     *
+     * @see IDeviceService#addIndex
+     */
+    enum DeviceField {
+        MAC, IPV4, VLAN, SWITCHPORT
+    }
+
+    /**
+     * The source device for the current packet-in, if applicable.
+     */
+    // public static final String CONTEXT_SRC_DEVICE =
+    // "net.floodlightcontroller.devicemanager.srcDevice";
+
+    /**
+     * The destination device for the current packet-in, if applicable.
+     */
+    // public static final String CONTEXT_DST_DEVICE =
+    // / "net.floodlightcontroller.devicemanager.dstDevice";
+
+    /**
+     * The original destination device for the current packet-in
+     */
+    // public static final String CONTEXT_ORIG_DST_DEVICE =
+    // "net.floodlightcontroller.devicemanager.origDstDevice";
+
+    /**
+     * A FloodlightContextStore object that can be used to interact with the
+     * FloodlightContext information created by BVS manager.
+     */
+    // public static final FloodlightContextStore<IDevice> fcStore =
+    // new FloodlightContextStore<IDevice>();
+
+    /**
+     * Get the device with the given device key.
+     *
+     * @param deviceKey
+     *            the key to search for
+     * @return the device associated with the key, or null if no such device
+     * @see IDevice#getDeviceKey()
+     */
+    public IDevice getDevice(Long deviceKey);
+
+    /**
+     * Search for a device exactly matching the provided device fields. This is
+     * the same lookup process that is used for packet_in processing and device
+     * learning. Thus, findDevice() can be used to match flow entries from
+     * switches to devices. Only the key fields as defined by the
+     * {@link IEntityClassifierService} will be important in this search. All
+     * key fields MUST be supplied.
+     *
+     * {@link queryDevices()} might be more appropriate!
+     *
+     * @param macAddress
+     *            The MAC address
+     * @param vlan
+     *            the VLAN. Null means no VLAN and is valid even if VLAN is a
+     *            key field.
+     * @param ipv4Address
+     *            the ipv4 address
+     * @param port
+     *            the node connector
+     * @return an {@link IDevice} or null if no device is found.
+     * @see IDeviceManager#setEntityClassifier(IEntityClassifierService)
+     * @throws IllegalArgumentException
+     *             if not all key fields of the current
+     *             {@link IEntityClassifierService} are specified.
+     */
+    public IDevice findDevice(long macAddress, Short vlan, Integer ipv4Address,
+            NodeConnector port) throws IllegalArgumentException;
+
+    /**
+     * Get a destination device using entity fields that corresponds with the
+     * given source device. The source device is important since there could be
+     * ambiguity in the destination device without the attachment point
+     * information. Search for a device in a given entity class. This is the
+     * same as the lookup process for destination devices.
+     *
+     * Only the key fields as defined by the reference entity class will be
+     * important in this search. All key fields MUST be supplied.
+     *
+     * @param entityClass
+     *            The entity class in which to perform the lookup.
+     * @param macAddress
+     *            The MAC address for the destination
+     * @param vlan
+     *            the VLAN if available
+     * @param ipv4Address
+     *            The IP address if available.
+     * @return an {@link IDevice} or null if no device is found.
+     * @see IDeviceService#findDevice(long, Short, Integer, Long, Integer)
+     * @throws IllegalArgumentException
+     *             if not all key fields of the source's {@link IEntityClass}
+     *             are specified.
+     */
+    public IDevice findClassDevice(IEntityClass entityClass, long macAddress,
+            Short vlan, Integer ipv4Address) throws IllegalArgumentException;
+
+    /**
+     * Get an unmodifiable collection view over all devices currently known.
+     *
+     * @return the collection of all devices
+     */
+    public Collection<? extends IDevice> getAllDevices();
+
+    /**
+     * Create an index over a set of fields. This allows efficient lookup of
+     * devices when querying using the indexed set of specified fields. The
+     * index must be registered before any device learning takes place, or it
+     * may be incomplete. It's OK if this is called multiple times with the same
+     * fields; only one index will be created for each unique set of fields.
+     *
+     * @param perClass
+     *            set to true if the index should be maintained for each entity
+     *            class separately.
+     * @param keyFields
+     *            the set of fields on which to index
+     */
+    public void addIndex(boolean perClass, EnumSet<DeviceField> keyFields);
+
+    /**
+     * Find devices that match the provided query. Any fields that are null will
+     * not be included in the query. If there is an index for the query, then it
+     * will be performed efficiently using the index. Otherwise, there will be a
+     * full scan of the device list.
+     *
+     * @param macAddress
+     *            The MAC address
+     * @param vlan
+     *            the VLAN
+     * @param ipv4Address
+     *            the ipv4 address
+     * @param port
+     *            the switch port
+     * @return an iterator over a set of devices matching the query
+     * @see IDeviceService#queryClassDevices(IEntityClass, Long, Short, Integer,
+     *      Long, Integer)
+     */
+    public Iterator<? extends IDevice> queryDevices(Long macAddress,
+            Short vlan, Integer ipv4Address, NodeConnector port);
+
+    /**
+     * Find devices that match the provided query. Only the index for the
+     * specified class will be searched. Any fields that are null will not be
+     * included in the query. If there is an index for the query, then it will
+     * be performed efficiently using the index. Otherwise, there will be a full
+     * scan of the device list.
+     *
+     * @param entityClass
+     *            The entity class in which to perform the query
+     * @param macAddress
+     *            The MAC address
+     * @param vlan
+     *            the VLAN
+     * @param ipv4Address
+     *            the ipv4 address
+     * @param port
+     *            the switch port
+     * @return an iterator over a set of devices matching the query
+     * @see IDeviceService#queryClassDevices(Long, Short, Integer, Long,
+     *      Integer)
+     */
+    public Iterator<? extends IDevice> queryClassDevices(
+            IEntityClass entityClass, Long macAddress, Short vlan,
+            Integer ipv4Address, NodeConnector port);
+
+    /**
+     * Adds a listener to listen for IDeviceManagerServices notifications
+     *
+     * @param listener
+     *            The listener that wants the notifications
+     * @param type
+     *            The type of the listener
+     */
+    public void addListener(IDeviceListener listener);
+
+    /**
+     * Specify points in the network where attachment points are not to be
+     * learned.
+     *
+     * @param sw
+     * @param port
+     */
+    public void addSuppressAPs(NodeConnector port);
+
+    public void removeSuppressAPs(NodeConnector port);
+
+    public Set<SwitchPort> getSuppressAPs();
+
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClass.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClass.java
new file mode 100644 (file)
index 0000000..7c1c100
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2011,2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker;
+
+import java.util.EnumSet;
+
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+import org.osgi.service.device.Device;
+
+/**
+ * Entities within an entity class are grouped into {@link Device} objects based
+ * on the {@link IEntityClass}, and the key fields specified by the entity
+ * class. A set of entities are considered to be the same device if and only if
+ * they belong to the same entity class and they match on all key fields for
+ * that entity class. A field is effectively wildcarded by not including it in
+ * the list of key fields returned by {@link IEntityClassifierService} and/or
+ * {@link IEntityClass}.
+ *
+ * Note that if you're not using static objects, you'll need to override
+ * {@link Object#equals(Object)} and {@link Object#hashCode()}.
+ *
+ * @author readams
+ *
+ */
+public interface IEntityClass {
+    /**
+     * Return the set of key fields for this entity class. Entities belonging to
+     * this class that differ in fields not included in this collection will be
+     * considered the same device. The key fields for an entity class must not
+     * change unless associated with a flush of that entity class.
+     *
+     * @return a set containing the fields that should not be wildcarded. May be
+     *         null to indicate that all fields are key fields.
+     */
+    EnumSet<DeviceField> getKeyFields();
+
+    /**
+     * Returns a user-friendly, unique name for this EntityClass
+     *
+     * @return the name of the entity class
+     */
+    String getName();
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassListener.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassListener.java
new file mode 100644 (file)
index 0000000..be5f258
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2011 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker;
+
+import java.util.Set;
+
+/**
+ * Implementors of this interface can receive updates from the Entity Classifier
+ * about the changes to entity Classes.
+ *
+ * @author Ananth Suryanarayana (Ananth.Suryanarayana@bigswitch.com)
+ */
+public interface IEntityClassListener {
+
+    /**
+     * Process entity classes change event.
+     *
+     * @param entityClassNames
+     *            Set of entity classes changed
+     */
+    public void entityClassChanged(Set<String> entityClassNames);
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassifierService.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassifierService.java
new file mode 100644 (file)
index 0000000..f6071e1
--- /dev/null
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2011,2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker;
+
+import java.util.Collection;
+import java.util.EnumSet;
+
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+
+/**
+ * A component that wishes to participate in entity classification needs to
+ * implement the IEntityClassifier interface, and register with the Device
+ * Manager as an entity classifier. An entity is classified by the classifier
+ * into an {@link IEntityClass}
+ *
+ * @author readams
+ */
+public interface IEntityClassifierService {
+    /**
+     * Classify the given entity into an IEntityClass. It is important that the
+     * key fields returned by {@link IEntityClassifierService#getKeyFields()} be
+     * sufficient for classifying entities. That is, if two entities are
+     * identical except for a field that is not a key field, they must be
+     * assigned the same class. Furthermore, entity classification must be
+     * transitive: For all entities x, y, z, if x and y belong to a class c, and
+     * y and z belong class c, then x and z must belong to class c.
+     *
+     * @param entity
+     *            the entity to classify
+     * @return the IEntityClass resulting from the classification.
+     * @see IEntityClassifierService#getKeyFields()
+     */
+    IEntityClass classifyEntity(Entity entity);
+
+    /**
+     * Return the most general list of fields that should be used as key fields.
+     * If devices differ in any fields not listed here, they can never be
+     * considered a different device by any {@link IEntityClass} returned by
+     * {@link IEntityClassifierService#classifyEntity}. The key fields for an
+     * entity classifier must not change unless associated with a flush of all
+     * entity state. The list of key fields must be the union of all key fields
+     * that could be returned by {@link IEntityClass#getKeyFields()}.
+     *
+     * @return a set containing the fields that should not be wildcarded. May be
+     *         null to indicate that all fields are key fields.
+     * @see {@link IEntityClass#getKeyFields()}
+     * @see {@link IEntityClassifierService#classifyEntity}
+     */
+    EnumSet<DeviceField> getKeyFields();
+
+    /**
+     * Reclassify the given entity into a class. When reclassifying entities, it
+     * can be helpful to take into account the current classification either as
+     * an optimization or to allow flushing any cached state tied to the key for
+     * that device. The entity will be assigned to a new device with a new
+     * object if the entity class returned is different from the entity class
+     * for curDevice.
+     *
+     * <p>
+     * Note that you must take steps to ensure you always return classes in some
+     * consistent ordering.
+     *
+     * @param curDevice
+     *            the device currently associated with the entity
+     * @param entity
+     *            the entity to reclassify
+     * @return the IEntityClass resulting from the classification
+     */
+    IEntityClass reclassifyEntity(IDevice curDevice, Entity entity);
+
+    /**
+     * Once reclassification is complete for a device, this method will be
+     * called. If any entities within the device changed their classification,
+     * it will split into one or more new devices for each of the entities. If
+     * two devices are merged because of a reclassification, then this will be
+     * called on each of the devices, with the same device in the newDevices
+     * collection.
+     *
+     * @param oldDevice
+     *            the original device object
+     * @param newDevices
+     *            all the new devices derived from the entities of the old
+     *            device. If null, the old device was unchanged.
+     */
+    void deviceUpdate(IDevice oldDevice,
+            Collection<? extends IDevice> newDevices);
+
+    /**
+     * Adds a listener to listen for IEntityClassifierServices notifications
+     *
+     * @param listener
+     *            The listener that wants the notifications
+     */
+    public void addListener(IEntityClassListener listener);
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java
new file mode 100644 (file)
index 0000000..51d68d8
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * 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.hosttracker;
+
+import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
+
+/**
+ * This interface defines the method to notify detected Host on the network. The
+ * information includes Host's IP address, MAC address, switch ID, port, and
+ * VLAN.
+ *
+ */
+
+public interface IfHostListener {
+    /**
+     * Learns new Hosts. Called by ArpHandler and implemented in
+     * HostTracker.java. If a Host is learned for the first time then adds it to
+     * the local database and informs other applications of coming up a new
+     * Host. For the hosts which it has already learned, it refreshes them.
+     *
+     * @param host
+     *            Host info encapsulated in HostNodeConnector class
+     */
+    public void hostListener(HostNodeConnector host);
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java
new file mode 100644 (file)
index 0000000..995ee57
--- /dev/null
@@ -0,0 +1,138 @@
+/*
+ * 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.hosttracker;
+
+import java.net.InetAddress;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Future;
+
+import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.utils.Status;
+
+/**
+ * This interface defines the methods to retrieve information about learned
+ * Hosts. Also provides methods to statically add/remove Hosts from the local
+ * database.
+ *
+ */
+
+public interface IfIptoHost {
+    /**
+     * Applications call this interface methods to determine IP address to MAC
+     * binding and its connectivity to an OpenFlow switch in term of Node, Port,
+     * and VLAN. These bindings are learned dynamically as well as can be added
+     * statically through Northbound APIs. If a binding is unknown, then an ARP
+     * request is initiated immediately to discover the host.
+     *
+     * @param networkAddress
+     *            IP Address of the Host encapsulated in class InetAddress
+     * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+     *         Class that contains the Host info such as its MAC address, Switch
+     *         ID, port, VLAN. If Host is not found, returns NULL
+     */
+    public HostNodeConnector hostFind(InetAddress networkAddress);
+
+    /**
+     * Checks the local Host Database to see if a Host has been learned for a
+     * given IP address.
+     *
+     * @param networkAddress
+     *            IP Address of the Host encapsulated in class InetAddress
+     * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+     *         Class that contains the Host info such as its MAC address, Switch
+     *         ID, port, VLAN. If Host is not found, returns NULL
+     *
+     */
+    public HostNodeConnector hostQuery(InetAddress networkAddress);
+
+    /**
+     * Initiates an immediate discovery of the Host for a given IP address. This
+     * provides for the calling applications to block on the host discovery.
+     *
+     * @param networkAddress
+     *            IP address encapsulated in InetAddress class
+     * @return Future
+     *         {@link org.opendaylight.controller.hosttracker.HostTrackerCallable}
+     */
+    public Future<HostNodeConnector> discoverHost(InetAddress networkAddress);
+
+    /**
+     * Returns the Network Hierarchy for a given Host. This API is typically
+     * used by applications like Hadoop for Rack Awareness functionality.
+     *
+     * @param IP
+     *            address of the Host encapsulated in InetAddress class
+     * @return List of String ArrayList containing the Hierarchies.
+     */
+    public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress);
+
+    /**
+     * Returns all the the Hosts either learned dynamically or added statically
+     * via Northbound APIs.
+     *
+     * @return Set of
+     *         {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+     *         . Class that contains the Host info such as its MAC address,
+     *         Switch ID, port, VLAN.
+     */
+    public Set<HostNodeConnector> getAllHosts();
+
+    /**
+     * Returns all the "Active Hosts" learned "Statically" via Northbound APIs.
+     * These Hosts are categorized as "Active" because the Switch and Port they
+     * are connected to, are in up state.
+     *
+     * @return Set of
+     *         {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+     *         . Class that contains the Host info such as MAC address, Switch
+     *         ID, port, VLAN. If Host is not found, returns NULL
+     */
+    public Set<HostNodeConnector> getActiveStaticHosts();
+
+    /**
+     * Returns all the "Inactive Hosts" learned "Statically" via Northbound
+     * APIs. These Hosts are categorized as "Inactive" because either the Switch
+     * or the Port they are connected to, is in down state.
+     *
+     * @return Set of HostNodeConnector
+     *         {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector}
+     *         . HostNodeConnector is Class that contains the Host info such as
+     *         its MAC address, OpenFlowNode ID, port, VLAN.
+     */
+    public Set<HostNodeConnector> getInactiveStaticHosts();
+
+    /**
+     * Hosts can be learned dynamically or added statically. This method allows
+     * the addition of a Host to the local database statically.
+     *
+     * @param networkAddress
+     *            IP Address of the Host
+     * @param dataLayerAddress
+     *            MAC Address of the Host
+     * @param nc
+     *            NodeConnector to which the host is attached
+     * @param vlan
+     *            VLAN the host belongs to
+     * @return The status object as described in {@code Status} indicating the
+     *         result of this action.
+     */
+    public Status addStaticHost(String networkAddress, String dataLayerAddress,
+            NodeConnector nc, String vlan);
+
+    /**
+     * Allows the deletion of statically learned Host
+     *
+     * @param networkAddress
+     * @return The status object as described in {@code Status} indicating the
+     *         result of this action.
+     */
+    public Status removeStaticHost(String networkAddress);
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java
new file mode 100644 (file)
index 0000000..ef900e4
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * 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.hosttracker;
+
+import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
+
+/**
+ * This Interface defines the methods for client applications of Host Tracker to
+ * get notifications when a new host is learned or existing host is removed from
+ * the network.
+ *
+ */
+public interface IfNewHostNotify {
+    /**
+     * Notifies the HostTracker Clients that a new Host has been learned
+     *
+     * @param host
+     *            Host Info encapsulated in HostNodeConnector class
+     */
+    public void notifyHTClient(HostNodeConnector host);
+
+    /**
+     * Notifies the HostTracker Clients that a Host which was learned in the
+     * past has been removed either due to switch/port down event or due to ARP
+     * Aging
+     *
+     * @param host
+     *            Host Info encapsulated in HostNodeConnector class
+     */
+    public void notifyHTClientHostRemoved(HostNodeConnector host);
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/SwitchPort.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/SwitchPort.java
new file mode 100644 (file)
index 0000000..e60f8b4
--- /dev/null
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker;
+
+import org.opendaylight.controller.sal.core.NodeConnector;
+
+/**
+ * A simple switch DPID/port pair This class is immutable
+ *
+ * @author readams
+ *
+ */
+public class SwitchPort {
+    public enum ErrorStatus {
+        DUPLICATE_DEVICE("duplicate-device");
+
+        private String value;
+
+        ErrorStatus(String v) {
+            value = v;
+        }
+
+        @Override
+        public String toString() {
+            return value;
+        }
+
+        public static ErrorStatus fromString(String str) {
+            for (ErrorStatus m : ErrorStatus.values()) {
+                if (m.value.equals(str)) {
+                    return m;
+                }
+            }
+            return null;
+        }
+    }
+
+    private final NodeConnector port;
+    private final ErrorStatus errorStatus;
+
+    /**
+     * Simple constructor
+     *
+     * @param switchDPID
+     *            the dpid
+     * @param port
+     *            the port
+     * @param errorStatus
+     *            any error status for the switch port
+     */
+    public SwitchPort(NodeConnector port, ErrorStatus errorStatus) {
+        super();
+        this.port = port;
+        this.errorStatus = errorStatus;
+    }
+
+    /**
+     * Simple constructor
+     *
+     * @param switchDPID
+     *            the dpid
+     * @param port
+     *            the port
+     */
+    public SwitchPort(NodeConnector port) {
+        super();
+        this.port = port;
+        this.errorStatus = null;
+    }
+
+    // ***************
+    // Getters/Setters
+    // ***************
+
+    public NodeConnector getPort() {
+        return port;
+    }
+
+    public ErrorStatus getErrorStatus() {
+        return errorStatus;
+    }
+
+    // ******
+    // Object
+    // ******
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result
+                + ((errorStatus == null) ? 0 : errorStatus.hashCode());
+        result = prime * result + ((port == null) ? 0 : port.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        SwitchPort other = (SwitchPort) obj;
+        if (errorStatus != other.errorStatus)
+            return false;
+        if (port == null) {
+            if (other.port != null)
+                return false;
+        } else if (!port.equals(other.port))
+            return false;
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        return "SwitchPort [port=" + port + ", errorStatus=" + errorStatus
+                + "]";
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java
new file mode 100644 (file)
index 0000000..fe396ba
--- /dev/null
@@ -0,0 +1,215 @@
+/*
+ * 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.hosttracker.hostAware;
+
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.util.Arrays;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
+import org.opendaylight.controller.sal.core.ConstructionException;
+import org.opendaylight.controller.sal.core.Host;
+import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.packet.address.EthernetAddress;
+
+@XmlRootElement(name = "host")
+@XmlAccessorType(XmlAccessType.NONE)
+public class HostNodeConnector extends Host {
+    private static final long serialVersionUID = 1L;
+    @XmlElement
+    private NodeConnector nodeConnector;
+    @XmlElement
+    private short vlan;
+    @XmlElement
+    private boolean staticHost;
+    private transient short arpSendCountDown;
+
+    /**
+     * Private constructor used for JAXB mapping
+     */
+    @SuppressWarnings("unused")
+    private HostNodeConnector() {
+    }
+
+    public HostNodeConnector(InetAddress ip) throws ConstructionException {
+        this(ip, null);
+    }
+
+    public HostNodeConnector(InetAddress ip, NodeConnector nc)
+            throws ConstructionException {
+        this(new EthernetAddress(new byte[] { (byte) 0x00, (byte) 0x00,
+                (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }), ip, nc,
+                (short) 0);
+    }
+
+    public HostNodeConnector(byte[] mac, InetAddress ip, NodeConnector nc,
+            short vlan) throws ConstructionException {
+        this(new EthernetAddress(mac.clone()), ip, nc, vlan);
+    }
+
+    public HostNodeConnector(EthernetAddress eaddr, InetAddress naddr,
+            NodeConnector nc, short vlan) throws ConstructionException {
+        super(eaddr, naddr);
+        this.nodeConnector = nc;
+        this.vlan = vlan;
+    }
+
+    /**
+     * @return the NodeConnector
+     */
+    public NodeConnector getnodeConnector() {
+        return this.nodeConnector;
+    }
+
+    /**
+     * @return the Node
+     */
+    public Node getnodeconnectorNode() {
+        return this.nodeConnector.getNode();
+    }
+
+    /**
+     * @return the NodeId
+     */
+    public Long getnodeconnectornodeId() {
+        return (Long) this.nodeConnector.getNode().getID();
+    }
+
+    /**
+     * @return the port
+     */
+    public Short getnodeconnectorportId() {
+        return (Short) this.nodeConnector.getID();
+    }
+
+    /**
+     * @return the DataLayerAddress
+     */
+    public byte[] getDataLayerAddressBytes() {
+        byte[] macaddr = null;
+        if (getDataLayerAddress() instanceof EthernetAddress) {
+            EthernetAddress e = (EthernetAddress) getDataLayerAddress();
+            macaddr = e.getValue();
+        }
+        return macaddr;
+    }
+
+    /**
+     * @return the vlan
+     */
+    public short getVlan() {
+        return this.vlan;
+    }
+
+    public boolean isStaticHost() {
+        return this.staticHost;
+    }
+
+    public HostNodeConnector setStaticHost(boolean statically_learned) {
+        this.staticHost = statically_learned;
+        return this;
+    }
+
+    public HostNodeConnector initArpSendCountDown() {
+        this.arpSendCountDown = 24;
+        return this;
+    }
+
+    public short getArpSendCountDown() {
+        return (this.arpSendCountDown);
+    }
+
+    public HostNodeConnector setArpSendCountDown(short cntdown) {
+        this.arpSendCountDown = cntdown;
+        return this;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = super.hashCode();
+        result = prime * result
+                + ((nodeConnector == null) ? 0 : nodeConnector.hashCode());
+        result = prime * result + (staticHost ? 1231 : 1237);
+        result = prime * result + vlan;
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (!super.equals(obj))
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        HostNodeConnector other = (HostNodeConnector) obj;
+        if (nodeConnector == null) {
+            if (other.nodeConnector != null)
+                return false;
+        } else if (!nodeConnector.equals(other.nodeConnector))
+            return false;
+        if (staticHost != other.staticHost)
+            return false;
+        if (vlan != other.vlan)
+            return false;
+        return true;
+    }
+
+    public boolean equalsByIP(InetAddress networkAddress) {
+        return (this.getNetworkAddress().equals(networkAddress));
+    }
+
+    public boolean isRewriteEnabled() {
+        byte[] emptyArray = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                (byte) 0x00, (byte) 0x00, (byte) 0x00 };
+        byte[] macaddr = null;
+        if (getDataLayerAddress() instanceof EthernetAddress) {
+            EthernetAddress e = (EthernetAddress) getDataLayerAddress();
+            macaddr = e.getValue();
+        }
+        if (macaddr == null)
+            return false;
+        return !Arrays.equals(emptyArray, macaddr);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see java.lang.Object#toString()
+     */
+    @Override
+    public String toString() {
+        return "HostNodeConnector[" + ReflectionToStringBuilder.toString(this)
+                + "]";
+    }
+
+    public boolean isV4Host() {
+        return (getNetworkAddress() instanceof Inet4Address);
+    }
+
+    public boolean isV6Host() {
+        return (getNetworkAddress() instanceof Inet6Address);
+    }
+
+    public String toJson() {
+        return "{\"host\":\"" + super.toString() + "\", " + "\"vlan\":\""
+                + String.valueOf(vlan) + "\",\"NodeConnector\":\""
+                + nodeConnector.toString() + "\"," + "\"static\":\""
+                + String.valueOf(isStaticHost()) + "\"}";
+    }
+
+}
diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java b/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java
new file mode 100644 (file)
index 0000000..abe7518
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * 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.hosttracker.hostAware;
+
+import java.net.InetAddress;
+
+/**
+ * This Interface defines the methods to trigger the discovery of a Host and to
+ * probe if a learned Host is still in the network.
+ *
+ *
+ *
+ */
+public interface IHostFinder {
+    /**
+     * This method initiates the discovery of a host based on its IP address.
+     * This is triggered by query of an application to the HostTracker. The
+     * requested IP address doesn't exist in the local database at this point.
+     *
+     * @param networkAddress
+     *            IP Address encapsulated in InetAddress class
+     *
+     */
+    public void find(InetAddress networkAddress);
+
+    /**
+     * This method is called by HostTracker to see if a learned Host is still in
+     * the network. Used mostly for ARP Aging.
+     *
+     * @param host
+     *            The Host that needs to be probed
+     */
+    public void probe(HostNodeConnector host);
+}
diff --git a/opendaylight/hosttracker_new/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java b/opendaylight/hosttracker_new/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java
new file mode 100644 (file)
index 0000000..0c3ca2f
--- /dev/null
@@ -0,0 +1,100 @@
+/*\r
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.\r
+ *\r
+ * This program and the accompanying materials are made available under the\r
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
+ * and is available at http://www.eclipse.org/legal/epl-v10.html\r
+ */\r
+\r
+package org.opendaylight.controller.hosttracker.hostAware;\r
+\r
+import java.net.InetAddress;\r
+import java.net.UnknownHostException;\r
+\r
+import org.junit.Assert;\r
+import org.junit.Test;\r
+\r
+import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;\r
+import org.opendaylight.controller.sal.core.ConstructionException;\r
+import org.opendaylight.controller.sal.core.Node;\r
+\r
+import junit.framework.TestCase;\r
+\r
+import org.opendaylight.controller.sal.packet.address.EthernetAddress;\r
+\r
+import org.opendaylight.controller.sal.utils.NodeConnectorCreator;\r
+import org.opendaylight.controller.sal.core.NodeConnector;\r
+import org.opendaylight.controller.sal.utils.NodeCreator;\r
+\r
+public class HostNodeConnectorTest extends TestCase {\r
+\r
+    @Test\r
+    public void testHostNodeConnector() throws UnknownHostException {\r
+        HostNodeConnector hostnodeconnector_1, hostnodeconnector_2, hostnodeconnector_3;\r
+        InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8");\r
+        InetAddress hostIP_2 = InetAddress\r
+                .getByName("2001:420:281:1004:e123:e688:d655:a1b0");\r
+        InetAddress hostIP_3 = InetAddress.getByName("192.168.0.28");\r
+        byte[] hostMAC_2 = new byte[] { (byte) 0x11, (byte) 0x22, (byte) 0x33,\r
+                (byte) 0x22, (byte) 0x22, (byte) 0x22 };\r
+        byte[] hostMAC_3 = new byte[] { (byte) 0x11, (byte) 0x22, (byte) 0x33,\r
+                (byte) 0x33, (byte) 0x33, (byte) 0x33 };\r
+\r
+        Node node = NodeCreator.createOFNode(1L);\r
+        NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector(\r
+                (short) 2, node);\r
+        NodeConnector nc2 = NodeConnectorCreator.createOFNodeConnector(\r
+                (short) 1, node);\r
+\r
+        try {\r
+            hostnodeconnector_1 = new HostNodeConnector(hostIP_1);\r
+            Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1));\r
+            Assert.assertTrue(hostnodeconnector_1.isV4Host());\r
+            Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1));\r
+        } catch (ConstructionException e) {\r
+            Assert.assertTrue(false);\r
+        }\r
+\r
+        try {\r
+            hostnodeconnector_2 = new HostNodeConnector(hostMAC_2, hostIP_2,\r
+                    nc1, (short) 2);\r
+            Assert.assertTrue(hostnodeconnector_2.isV6Host());\r
+            Assert.assertTrue(hostnodeconnector_2.getnodeConnector()\r
+                    .equals(nc1));\r
+            Assert.assertTrue(hostnodeconnector_2.getnodeconnectorNode()\r
+                    .equals(node));\r
+            Assert.assertTrue(node.getID().equals(\r
+                    hostnodeconnector_2.getnodeconnectornodeId()));\r
+            Assert.assertTrue(hostnodeconnector_2.getnodeconnectorportId()\r
+                    .equals((short) 2));\r
+        } catch (ConstructionException e) {\r
+            Assert.assertTrue(false);\r
+        }\r
+\r
+        try {\r
+            hostnodeconnector_3 = new HostNodeConnector(new EthernetAddress(\r
+                    hostMAC_3), hostIP_3, nc2, (short) 3);\r
+            byte[] hostMAC_3_rb = hostnodeconnector_3\r
+                    .getDataLayerAddressBytes();\r
+            HostNodeConnector hostnodeconnector_3rb = new HostNodeConnector(\r
+                    new EthernetAddress(hostMAC_3_rb), hostIP_3, nc2, (short) 3);\r
+            Assert.assertTrue(hostnodeconnector_3.equals(hostnodeconnector_3rb));\r
+\r
+            Assert.assertTrue(hostnodeconnector_3.getVlan() == (short) 3);\r
+\r
+            hostnodeconnector_3.setStaticHost(true);\r
+            Assert.assertTrue(hostnodeconnector_3.isStaticHost());\r
+\r
+            Assert.assertTrue(hostnodeconnector_3.isRewriteEnabled());\r
+\r
+            hostnodeconnector_3.initArpSendCountDown().setArpSendCountDown(\r
+                    (short) 10);\r
+            Assert.assertTrue(hostnodeconnector_3.getArpSendCountDown() == (short) 10);\r
+\r
+        } catch (ConstructionException e) {\r
+            Assert.assertTrue(false);\r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/opendaylight/hosttracker_new/implementation/pom.xml b/opendaylight/hosttracker_new/implementation/pom.xml
new file mode 100644 (file)
index 0000000..804f5e3
--- /dev/null
@@ -0,0 +1,125 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+  xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>commons.opendaylight</artifactId>
+    <version>1.4.0-SNAPSHOT</version>
+    <relativePath>../../commons/opendaylight</relativePath>
+  </parent>
+  <artifactId>hosttracker_new.implementation</artifactId>
+  <version>0.4.0-SNAPSHOT</version>
+  <packaging>bundle</packaging>
+
+  <properties>
+    <!-- Sonar properties using jacoco to retrieve integration test results -->
+    <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
+    <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
+    <sonar.jacoco.Reportpath>target/jacoco.exec</sonar.jacoco.Reportpath>
+    <sonar.jacoco.itReportPath>target/jacoco-it.exec</sonar.jacoco.itReportPath>
+    <sonar.language>java</sonar.language>
+  </properties>
+
+  <build>
+    <pluginManagement>
+      <plugins>
+        <plugin>
+          <groupId>org.jacoco</groupId>
+          <artifactId>jacoco-maven-plugin</artifactId>
+          <version>0.5.3.201107060350</version>
+        </plugin>
+      </plugins>
+    </pluginManagement>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.felix</groupId>
+        <artifactId>maven-bundle-plugin</artifactId>
+        <version>2.3.6</version>
+        <extensions>true</extensions>
+        <configuration>
+          <instructions>
+            <Export-Package>
+            </Export-Package>
+            <Import-Package>
+              org.opendaylight.controller.sal.core,
+              org.opendaylight.controller.sal.utils,
+              org.opendaylight.controller.sal.topology,
+              org.opendaylight.controller.sal.packet,
+              org.opendaylight.controller.hosttracker,
+              org.opendaylight.controller.topologymanager,
+              org.opendaylight.controller.sal.packet.address,
+              org.opendaylight.controller.switchmanager,
+              org.opendaylight.controller.clustering.services,
+              org.opendaylight.controller.hosttracker.hostAware,
+              javax.xml.bind.annotation,
+              javax.xml.bind,
+              org.apache.felix.dm,
+              org.apache.commons.lang3.builder,
+              org.osgi.service.component,
+              org.slf4j,
+              org.eclipse.osgi.framework.console,
+              org.osgi.framework
+            </Import-Package>
+            <Bundle-Activator>
+              org.opendaylight.controller.hosttracker.internal.Activator
+            </Bundle-Activator>
+            <Service-Component>
+            </Service-Component>
+          </instructions>
+          <manifestLocation>${project.basedir}/META-INF</manifestLocation>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.jacoco</groupId>
+        <artifactId>jacoco-maven-plugin</artifactId>
+        <configuration>
+          <includes>org.opendaylight.controller.*</includes>
+        </configuration>
+        <executions>
+          <execution>
+            <id>pre-test</id>
+            <goals>
+              <goal>prepare-agent</goal>
+            </goals>
+          </execution>
+          <execution>
+            <id>post-test</id>
+            <phase>test</phase>
+            <goals>
+              <goal>report</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+  <dependencies>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>topologymanager</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>switchmanager</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>clustering.services</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>sal</artifactId>
+      <version>0.5.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>hosttracker_new</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+  </dependencies>
+</project>
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java
new file mode 100644 (file)
index 0000000..2cf1c1d
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * 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.hosttracker.internal;
+
+import java.util.Dictionary;
+import java.util.Hashtable;
+
+import org.apache.felix.dm.Component;
+import org.opendaylight.controller.hosttracker.IDeviceService;
+import org.opendaylight.controller.hosttracker.IfIptoHost;
+import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase;
+import org.opendaylight.controller.sal.packet.IDataPacketService;
+import org.opendaylight.controller.sal.packet.IListenDataPacket;
+import org.opendaylight.controller.switchmanager.ISwitchManager;
+import org.opendaylight.controller.topologymanager.ITopologyManager;
+import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Activator extends ComponentActivatorAbstractBase {
+    protected static final Logger logger = LoggerFactory
+            .getLogger(Activator.class);
+
+    @Override
+    protected void init() {
+
+    }
+
+    @Override
+    protected void destroy() {
+
+    }
+
+    /**
+     * Function that is used to communicate to dependency manager the list of
+     * known implementations for services inside a container
+     *
+     *
+     * @return An array containing all the CLASS objects that will be
+     *         instantiated in order to get an fully working implementation
+     *         Object
+     */
+    @Override
+    public Object[] getImplementations() {
+        Object[] res = { DeviceManagerImpl.class };
+        return res;
+    }
+
+    /**
+     * Function that is called when configuration of the dependencies is
+     * required.
+     *
+     * @param c
+     *            dependency manager Component object, used for configuring the
+     *            dependencies exported and imported
+     * @param imp
+     *            Implementation class that is being configured, needed as long
+     *            as the same routine can configure multiple implementations
+     * @param containerName
+     *            The containerName being configured, this allow also optional
+     *            per-container different behavior if needed, usually should not
+     *            be the case though.
+     */
+    @Override
+    public void configureInstance(Component c, Object imp, String containerName) {
+        if (imp.equals(DeviceManagerImpl.class)) {
+            // export the service
+            // XXX - TODO merge with existing APIs
+            Dictionary<String, String> props = new Hashtable<String, String>();
+            props.put("salListenerName", "devicemanager");
+
+            c.setInterface(
+                    new String[] { IDeviceService.class.getName(),
+                            IfIptoHost.class.getName(),
+                            IListenDataPacket.class.getName(),
+                            ITopologyManagerAware.class.getName() }, props);
+
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(ISwitchManager.class)
+                    .setCallbacks("setSwitchManager", "unsetSwitchManager")
+                    .setRequired(false));
+
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(IDataPacketService.class)
+                    .setCallbacks("setDataPacketService",
+                            "unsetDataPacketService").setRequired(true));
+
+            // c.add(createContainerServiceDependency(containerName).setService(
+            // IClusterContainerServices.class).setCallbacks(
+            // "setClusterContainerService",
+            // "unsetClusterContainerService").setRequired(true));
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(ITopologyManager.class)
+                    .setCallbacks("setTopologyManager", "unsetTopologyManager")
+                    .setRequired(false));
+
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(IDataPacketService.class)
+                    .setCallbacks("setDataPacketService",
+                            "unsetDataPacketService").setRequired(true));
+        }
+    }
+
+    /**
+     * Method which tells how many Global implementations are supported by the
+     * bundle. This way we can tune the number of components created. This
+     * components will be created ONLY at the time of bundle startup and will be
+     * destroyed only at time of bundle destruction, this is the major
+     * difference with the implementation retrieved via getImplementations where
+     * all of them are assumed to be in a container !
+     *
+     *
+     * @return The list of implementations the bundle will support, in Global
+     *         version
+     */
+    @Override
+    protected Object[] getGlobalImplementations() {
+        return null;
+    }
+
+    /**
+     * Configure the dependency for a given instance Global
+     *
+     * @param c
+     *            Component assigned for this instance, this will be what will
+     *            be used for configuration
+     * @param imp
+     *            implementation to be configured
+     * @param containerName
+     *            container on which the configuration happens
+     */
+    @Override
+    protected void configureGlobalInstance(Component c, Object imp) {
+
+    }
+
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/AttachmentPoint.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/AttachmentPoint.java
new file mode 100644 (file)
index 0000000..ba2c64a
--- /dev/null
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2011,2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+/**
+ * @author Srini
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import org.opendaylight.controller.sal.core.NodeConnector;
+
+public class AttachmentPoint {
+    NodeConnector port;
+    long activeSince;
+    long lastSeen;
+
+    // Timeout for moving attachment points from OF/broadcast
+    // domain to another.
+    public static final long INACTIVITY_INTERVAL = 30000; // 30 seconds
+    public static final long EXTERNAL_TO_EXTERNAL_TIMEOUT = 5000; // 5 seconds
+    public static final long OPENFLOW_TO_EXTERNAL_TIMEOUT = 30000; // 30 seconds
+    public static final long CONSISTENT_TIMEOUT = 30000; // 30 seconds
+
+    public AttachmentPoint(NodeConnector port, long activeSince, long lastSeen) {
+        this.port = port;
+        this.activeSince = activeSince;
+        this.lastSeen = lastSeen;
+    }
+
+    public AttachmentPoint(NodeConnector port, long lastSeen) {
+        this.port = port;
+        this.lastSeen = lastSeen;
+        this.activeSince = lastSeen;
+    }
+
+    public AttachmentPoint(AttachmentPoint ap) {
+        this.port = ap.port;
+        this.activeSince = ap.activeSince;
+        this.lastSeen = ap.lastSeen;
+    }
+
+    public NodeConnector getPort() {
+        return port;
+    }
+
+    public void setPort(NodeConnector port) {
+        this.port = port;
+    }
+
+    public long getActiveSince() {
+        return activeSince;
+    }
+
+    public void setActiveSince(long activeSince) {
+        this.activeSince = activeSince;
+    }
+
+    public long getLastSeen() {
+        return lastSeen;
+    }
+
+    public void setLastSeen(long lastSeen) {
+        if (this.lastSeen + INACTIVITY_INTERVAL < lastSeen)
+            this.activeSince = lastSeen;
+        if (this.lastSeen < lastSeen)
+            this.lastSeen = lastSeen;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((port == null) ? 0 : port.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        AttachmentPoint other = (AttachmentPoint) obj;
+        if (port == null) {
+            if (other.port != null)
+                return false;
+        } else if (!port.equals(other.port))
+            return false;
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        return "AttachmentPoint [port=" + port + ", activeSince=" + activeSince
+                + ", lastSeen=" + lastSeen + "]";
+    }
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DefaultEntityClassifier.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DefaultEntityClassifier.java
new file mode 100644 (file)
index 0000000..39c322f
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2011,2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import java.util.Collection;
+import java.util.EnumSet;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDevice;
+import org.opendaylight.controller.hosttracker.IDeviceService;
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+import org.opendaylight.controller.hosttracker.IEntityClass;
+import org.opendaylight.controller.hosttracker.IEntityClassListener;
+import org.opendaylight.controller.hosttracker.IEntityClassifierService;
+
+/**
+ * This is a default entity classifier that simply classifies all entities into
+ * a fixed entity class, with key fields of MAC and VLAN.
+ *
+ * @author readams
+ */
+public class DefaultEntityClassifier implements IEntityClassifierService {
+    /**
+     * A default fixed entity class
+     */
+    protected static class DefaultEntityClass implements IEntityClass {
+        String name;
+
+        public DefaultEntityClass(String name) {
+            this.name = name;
+        }
+
+        @Override
+        public EnumSet<IDeviceService.DeviceField> getKeyFields() {
+            return keyFields;
+        }
+
+        @Override
+        public String getName() {
+            return name;
+        }
+    }
+
+    protected static EnumSet<DeviceField> keyFields;
+    static {
+        keyFields = EnumSet.of(DeviceField.MAC, DeviceField.VLAN);
+    }
+    protected static DefaultEntityClass entityClass = new DefaultEntityClass(
+            "DefaultEntityClass");
+
+    @Override
+    public IEntityClass classifyEntity(Entity entity) {
+        return entityClass;
+    }
+
+    @Override
+    public IEntityClass reclassifyEntity(IDevice curDevice, Entity entity) {
+        return entityClass;
+    }
+
+    @Override
+    public void deviceUpdate(IDevice oldDevice,
+            Collection<? extends IDevice> newDevices) {
+        // no-op
+    }
+
+    @Override
+    public EnumSet<DeviceField> getKeyFields() {
+        return keyFields;
+    }
+
+    @Override
+    public void addListener(IEntityClassListener listener) {
+        // no-op
+
+    }
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Device.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Device.java
new file mode 100755 (executable)
index 0000000..50e77ec
--- /dev/null
@@ -0,0 +1,829 @@
+/*
+ * Copyright (c) 2011,2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeSet;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDevice;
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+import org.opendaylight.controller.hosttracker.IEntityClass;
+import org.opendaylight.controller.hosttracker.SwitchPort;
+import org.opendaylight.controller.hosttracker.SwitchPort.ErrorStatus;
+import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.utils.HexEncode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Concrete implementation of {@link IDevice}
+ *
+ * @author readams
+ */
+public class Device implements IDevice {
+    protected static Logger log = LoggerFactory.getLogger(Device.class);
+    public static final short VLAN_UNTAGGED = (short) 0xffff;
+
+    private final Long deviceKey;
+    protected final DeviceManagerImpl deviceManager;
+
+    protected final Entity[] entities;
+    private final IEntityClass entityClass;
+
+    protected final String macAddressString;
+    // the vlan Ids from the entities of this device
+    protected final Short[] vlanIds;
+    protected volatile String dhcpClientName;
+
+    /**
+     * These are the old attachment points for the device that were valid no
+     * more than INACTIVITY_TIME ago.
+     */
+    protected volatile List<AttachmentPoint> oldAPs;
+    /**
+     * The current attachment points for the device.
+     */
+    protected volatile List<AttachmentPoint> attachmentPoints;
+
+    // ************
+    // Constructors
+    // ************
+
+    /**
+     * Create a device from an entities
+     *
+     * @param deviceManager
+     *            the device manager for this device
+     * @param deviceKey
+     *            the unique identifier for this device object
+     * @param entity
+     *            the initial entity for the device
+     * @param entityClass
+     *            the entity classes associated with the entity
+     */
+    public Device(DeviceManagerImpl deviceManager, Long deviceKey,
+            Entity entity, IEntityClass entityClass) {
+        this.deviceManager = deviceManager;
+        this.deviceKey = deviceKey;
+        this.entities = new Entity[] { entity };
+        this.macAddressString = HexEncode.longToHexString(entity
+                .getMacAddress());
+        this.entityClass = entityClass;
+        Arrays.sort(this.entities);
+
+        this.dhcpClientName = null;
+        this.oldAPs = null;
+        this.attachmentPoints = null;
+
+        if (entity.getPort() != null) {
+            NodeConnector port = entity.getPort();
+
+            if (deviceManager.isValidAttachmentPoint(port)) {
+                AttachmentPoint ap;
+                ap = new AttachmentPoint(port, entity.getLastSeenTimestamp()
+                        .getTime());
+
+                this.attachmentPoints = new ArrayList<AttachmentPoint>();
+                this.attachmentPoints.add(ap);
+            }
+        }
+        vlanIds = computeVlandIds();
+    }
+
+    /**
+     * Create a device from a set of entities
+     *
+     * @param deviceManager
+     *            the device manager for this device
+     * @param deviceKey
+     *            the unique identifier for this device object
+     * @param entities
+     *            the initial entities for the device
+     * @param entityClass
+     *            the entity class associated with the entities
+     */
+    public Device(DeviceManagerImpl deviceManager, Long deviceKey,
+            String dhcpClientName, Collection<AttachmentPoint> oldAPs,
+            Collection<AttachmentPoint> attachmentPoints,
+            Collection<Entity> entities, IEntityClass entityClass) {
+        this.deviceManager = deviceManager;
+        this.deviceKey = deviceKey;
+        this.dhcpClientName = dhcpClientName;
+        this.entities = entities.toArray(new Entity[entities.size()]);
+        this.oldAPs = null;
+        this.attachmentPoints = null;
+        if (oldAPs != null) {
+            this.oldAPs = new ArrayList<AttachmentPoint>(oldAPs);
+        }
+        if (attachmentPoints != null) {
+            this.attachmentPoints = new ArrayList<AttachmentPoint>(
+                    attachmentPoints);
+        }
+        this.macAddressString = HexEncode.longToHexString(this.entities[0]
+                .getMacAddress());
+        this.entityClass = entityClass;
+        Arrays.sort(this.entities);
+        vlanIds = computeVlandIds();
+    }
+
+    /**
+     * Construct a new device consisting of the entities from the old device
+     * plus an additional entity. The caller needs to ensure that the additional
+     * entity is not already present in the array
+     *
+     * @param device
+     *            the old device object
+     * @param newEntity
+     *            the entity to add. newEntity must be have the same entity
+     *            class as device
+     * @param if positive indicates the index in the entities array were the new
+     *        entity should be inserted. If negative we will compute the correct
+     *        insertion point
+     */
+    public Device(Device device, Entity newEntity, int insertionpoint) {
+        this.deviceManager = device.deviceManager;
+        this.deviceKey = device.deviceKey;
+        this.dhcpClientName = device.dhcpClientName;
+
+        this.entities = new Entity[device.entities.length + 1];
+        if (insertionpoint < 0) {
+            insertionpoint = -(Arrays.binarySearch(device.entities, newEntity) + 1);
+        }
+        if (insertionpoint > 0) {
+            // insertion point is not the beginning:
+            // copy up to insertion point
+            System.arraycopy(device.entities, 0, this.entities, 0,
+                    insertionpoint);
+        }
+        if (insertionpoint < device.entities.length) {
+            // insertion point is not the end
+            // copy from insertion point
+            System.arraycopy(device.entities, insertionpoint, this.entities,
+                    insertionpoint + 1, device.entities.length - insertionpoint);
+        }
+        this.entities[insertionpoint] = newEntity;
+        /*
+         * this.entities = Arrays.<Entity>copyOf(device.entities,
+         * device.entities.length + 1); this.entities[this.entities.length - 1]
+         * = newEntity; Arrays.sort(this.entities);
+         */
+        this.oldAPs = null;
+        if (device.oldAPs != null) {
+            this.oldAPs = new ArrayList<AttachmentPoint>(device.oldAPs);
+        }
+        this.attachmentPoints = null;
+        if (device.attachmentPoints != null) {
+            this.attachmentPoints = new ArrayList<AttachmentPoint>(
+                    device.attachmentPoints);
+        }
+
+        this.macAddressString = HexEncode.longToHexString(this.entities[0]
+                .getMacAddress());
+
+        this.entityClass = device.entityClass;
+        vlanIds = computeVlandIds();
+    }
+
+    private Short[] computeVlandIds() {
+        if (entities.length == 1) {
+            if (entities[0].getVlan() != null) {
+                return new Short[] { entities[0].getVlan() };
+            } else {
+                return new Short[] { Short.valueOf((short) -1) };
+            }
+        }
+
+        TreeSet<Short> vals = new TreeSet<Short>();
+        for (Entity e : entities) {
+            if (e.getVlan() == null)
+                vals.add((short) -1);
+            else
+                vals.add(e.getVlan());
+        }
+        return vals.toArray(new Short[vals.size()]);
+    }
+
+    /**
+     * Given a list of attachment points (apList), the procedure would return a
+     * map of attachment points for each L2 domain. L2 domain id is the key.
+     *
+     * @param apList
+     * @return
+     */
+    private Map<Long, AttachmentPoint> getAPMap(List<AttachmentPoint> apList) {
+
+        if (apList == null)
+            return null;
+        // ITopologyService topology = deviceManager.topology;
+
+        // Get the old attachment points and sort them.
+        List<AttachmentPoint> oldAP = new ArrayList<AttachmentPoint>();
+        if (apList != null)
+            oldAP.addAll(apList);
+
+        // Remove invalid attachment points before sorting.
+        List<AttachmentPoint> tempAP = new ArrayList<AttachmentPoint>();
+        for (AttachmentPoint ap : oldAP) {
+            if (deviceManager.isValidAttachmentPoint(ap.getPort())) {
+                tempAP.add(ap);
+            }
+        }
+        oldAP = tempAP;
+
+        Collections.sort(oldAP, deviceManager.apComparator);
+
+        // Map of attachment point by L2 domain Id.
+        Map<Long, AttachmentPoint> apMap = new HashMap<Long, AttachmentPoint>();
+
+        for (int i = 0; i < oldAP.size(); ++i) {
+            AttachmentPoint ap = oldAP.get(i);
+            // if this is not a valid attachment point, continue
+            if (!deviceManager.isValidAttachmentPoint(ap.getPort()))
+                continue;
+
+            // long id = topology.getL2DomainId(ap.getSw());
+            // XXX - Missing functionality
+            long id = 0;
+
+            apMap.put(id, ap);
+        }
+
+        if (apMap.isEmpty())
+            return null;
+        return apMap;
+    }
+
+    /**
+     * Remove all attachment points that are older than INACTIVITY_INTERVAL from
+     * the list.
+     *
+     * @param apList
+     * @return
+     */
+    private boolean removeExpiredAttachmentPoints(List<AttachmentPoint> apList) {
+
+        List<AttachmentPoint> expiredAPs = new ArrayList<AttachmentPoint>();
+
+        if (apList == null)
+            return false;
+
+        for (AttachmentPoint ap : apList) {
+            if (ap.getLastSeen() + AttachmentPoint.INACTIVITY_INTERVAL < System
+                    .currentTimeMillis())
+                expiredAPs.add(ap);
+        }
+        if (expiredAPs.size() > 0) {
+            apList.removeAll(expiredAPs);
+            return true;
+        } else
+            return false;
+    }
+
+    /**
+     * Get a list of duplicate attachment points, given a list of old attachment
+     * points and one attachment point per L2 domain. Given a true attachment
+     * point in the L2 domain, say trueAP, another attachment point in the same
+     * L2 domain, say ap, is duplicate if: 1. ap is inconsistent with trueAP,
+     * and 2. active time of ap is after that of trueAP; and 3. last seen time
+     * of ap is within the last INACTIVITY_INTERVAL
+     *
+     * @param oldAPList
+     * @param apMap
+     * @return
+     */
+    List<AttachmentPoint> getDuplicateAttachmentPoints(
+            List<AttachmentPoint> oldAPList, Map<Long, AttachmentPoint> apMap) {
+        // ITopologyService topology = deviceManager.topology;
+        List<AttachmentPoint> dupAPs = new ArrayList<AttachmentPoint>();
+        long timeThreshold = System.currentTimeMillis()
+                - AttachmentPoint.INACTIVITY_INTERVAL;
+
+        if (oldAPList == null || apMap == null)
+            return dupAPs;
+
+        for (AttachmentPoint ap : oldAPList) {
+            // XXX - Missing functionality
+            // long id = topology.getL2DomainId(ap.getSw());
+            long id = 0;
+            AttachmentPoint trueAP = apMap.get(id);
+
+            if (trueAP == null)
+                continue;
+            // XXX - Missing functionality
+            // boolean c = (topology.isConsistent(trueAP.getSw(),
+            // trueAP.getPort(),
+            // ap.getSw(), ap.getPort()));
+            boolean c = true;
+            boolean active = (ap.getActiveSince() > trueAP.getActiveSince());
+            boolean last = ap.getLastSeen() > timeThreshold;
+            if (!c && active && last) {
+                dupAPs.add(ap);
+            }
+        }
+
+        return dupAPs;
+    }
+
+    /**
+     * Update the known attachment points. This method is called whenever
+     * topology changes. The method returns true if there's any change to the
+     * list of attachment points -- which indicates a possible device move.
+     *
+     * @return
+     */
+    protected boolean updateAttachmentPoint() {
+        boolean moved = false;
+        this.oldAPs = attachmentPoints;
+        if (attachmentPoints == null || attachmentPoints.isEmpty())
+            return false;
+
+        List<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
+        if (attachmentPoints != null)
+            apList.addAll(attachmentPoints);
+        Map<Long, AttachmentPoint> newMap = getAPMap(apList);
+        if (newMap == null || newMap.size() != apList.size()) {
+            moved = true;
+        }
+
+        // Prepare the new attachment point list.
+        if (moved) {
+            log.info("updateAttachmentPoint: ap {}  newmap {} ",
+                    attachmentPoints, newMap);
+            List<AttachmentPoint> newAPList = new ArrayList<AttachmentPoint>();
+            if (newMap != null)
+                newAPList.addAll(newMap.values());
+            this.attachmentPoints = newAPList;
+        }
+
+        // Set the oldAPs to null.
+        return moved;
+    }
+
+    /**
+     * Update the list of attachment points given that a new packet-in was seen
+     * from (sw, port) at time (lastSeen). The return value is true if there was
+     * any change to the list of attachment points for the device -- which
+     * indicates a device move.
+     *
+     * @param sw
+     * @param port
+     * @param lastSeen
+     * @return
+     */
+    protected boolean updateAttachmentPoint(NodeConnector port, long lastSeen) {
+        // ITopologyService topology = deviceManager.topology;
+        List<AttachmentPoint> oldAPList;
+        List<AttachmentPoint> apList;
+        boolean oldAPFlag = false;
+
+        if (!deviceManager.isValidAttachmentPoint(port))
+            return false;
+        AttachmentPoint newAP = new AttachmentPoint(port, lastSeen);
+        // Copy the oldAP and ap list.
+        apList = new ArrayList<AttachmentPoint>();
+        if (attachmentPoints != null)
+            apList.addAll(attachmentPoints);
+        oldAPList = new ArrayList<AttachmentPoint>();
+        if (oldAPs != null)
+            oldAPList.addAll(oldAPs);
+
+        // if the sw, port is in old AP, remove it from there
+        // and update the lastSeen in that object.
+        if (oldAPList.contains(newAP)) {
+            int index = oldAPList.indexOf(newAP);
+            newAP = oldAPList.remove(index);
+            newAP.setLastSeen(lastSeen);
+            this.oldAPs = oldAPList;
+            oldAPFlag = true;
+        }
+
+        // newAP now contains the new attachment point.
+
+        // Get the APMap is null or empty.
+        Map<Long, AttachmentPoint> apMap = getAPMap(apList);
+        if (apMap == null || apMap.isEmpty()) {
+            apList.add(newAP);
+            attachmentPoints = apList;
+            // there are no old attachment points - since the device exists,
+            // this
+            // may be because the host really moved (so the old AP port went
+            // down);
+            // or it may be because the switch restarted (so old APs were
+            // nullified).
+            // For now we will treat both cases as host moved.
+            return true;
+        }
+
+        // XXX - Missing functionality
+        // long id = topology.getL2DomainId(sw);
+        long id = 0;
+        AttachmentPoint oldAP = apMap.get(id);
+
+        if (oldAP == null) // No attachment on this L2 domain.
+        {
+            apList = new ArrayList<AttachmentPoint>();
+            apList.addAll(apMap.values());
+            apList.add(newAP);
+            this.attachmentPoints = apList;
+            return true; // new AP found on an L2 island.
+        }
+
+        // There is already a known attachment point on the same L2 island.
+        // we need to compare oldAP and newAP.
+        if (oldAP.equals(newAP)) {
+            // nothing to do here. just the last seen has to be changed.
+            if (newAP.lastSeen > oldAP.lastSeen) {
+                oldAP.setLastSeen(newAP.lastSeen);
+            }
+            this.attachmentPoints = new ArrayList<AttachmentPoint>(
+                    apMap.values());
+            return false; // nothing to do here.
+        }
+
+        int x = deviceManager.apComparator.compare(oldAP, newAP);
+        if (x < 0) {
+            // newAP replaces oldAP.
+            apMap.put(id, newAP);
+            this.attachmentPoints = new ArrayList<AttachmentPoint>(
+                    apMap.values());
+
+            oldAPList = new ArrayList<AttachmentPoint>();
+            if (oldAPs != null)
+                oldAPList.addAll(oldAPs);
+            oldAPList.add(oldAP);
+            this.oldAPs = oldAPList;
+            // XXX - Missing functionality
+            // if (!topology.isInSameBroadcastDomain(oldAP.getSw(),
+            // oldAP.getPort(),
+            // newAP.getSw(), newAP.getPort()))
+            // return true; // attachment point changed.
+            return true;
+        } else if (oldAPFlag) {
+            // retain oldAP as is. Put the newAP in oldAPs for flagging
+            // possible duplicates.
+            oldAPList = new ArrayList<AttachmentPoint>();
+            if (oldAPs != null)
+                oldAPList.addAll(oldAPs);
+            // Add to oldAPList only if it was picked up from the oldAPList
+            oldAPList.add(newAP);
+            this.oldAPs = oldAPList;
+            // XXX - Missing functionality
+            // if (!topology.isInSameBroadcastDomain(oldAP.getSw(),
+            // oldAP.getPort(),
+            // newAP.getSw(), newAP.getPort()))
+            // return true; // attachment point changed.
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Delete (sw,port) from the list of list of attachment points and oldAPs.
+     *
+     * @param sw
+     * @param port
+     * @return
+     */
+    public boolean deleteAttachmentPoint(NodeConnector port) {
+        AttachmentPoint ap = new AttachmentPoint(port, 0);
+
+        if (this.oldAPs != null) {
+            ArrayList<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
+            apList.addAll(this.oldAPs);
+            int index = apList.indexOf(ap);
+            if (index > 0) {
+                apList.remove(index);
+                this.oldAPs = apList;
+            }
+        }
+
+        if (this.attachmentPoints != null) {
+            ArrayList<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
+            apList.addAll(this.attachmentPoints);
+            int index = apList.indexOf(ap);
+            if (index > 0) {
+                apList.remove(index);
+                this.attachmentPoints = apList;
+                return true;
+            }
+        }
+        return false;
+    }
+
+    // *******
+    // IDevice
+    // *******
+
+    @Override
+    public SwitchPort[] getOldAP() {
+        List<SwitchPort> sp = new ArrayList<SwitchPort>();
+        SwitchPort[] returnSwitchPorts = new SwitchPort[] {};
+        if (oldAPs == null)
+            return returnSwitchPorts;
+        if (oldAPs.isEmpty())
+            return returnSwitchPorts;
+
+        // copy ap list.
+        List<AttachmentPoint> oldAPList;
+        oldAPList = new ArrayList<AttachmentPoint>();
+
+        if (oldAPs != null)
+            oldAPList.addAll(oldAPs);
+        removeExpiredAttachmentPoints(oldAPList);
+
+        if (oldAPList != null) {
+            for (AttachmentPoint ap : oldAPList) {
+                SwitchPort swport = new SwitchPort(ap.getPort());
+                sp.add(swport);
+            }
+        }
+        return sp.toArray(new SwitchPort[sp.size()]);
+    }
+
+    @Override
+    public SwitchPort[] getAttachmentPoints() {
+        return getAttachmentPoints(false);
+    }
+
+    @Override
+    public SwitchPort[] getAttachmentPoints(boolean includeError) {
+        List<SwitchPort> sp = new ArrayList<SwitchPort>();
+        SwitchPort[] returnSwitchPorts = new SwitchPort[] {};
+        if (attachmentPoints == null)
+            return returnSwitchPorts;
+        if (attachmentPoints.isEmpty())
+            return returnSwitchPorts;
+
+        // copy ap list.
+        List<AttachmentPoint> apList = attachmentPoints;
+
+        if (apList != null) {
+            for (AttachmentPoint ap : apList) {
+                SwitchPort swport = new SwitchPort(ap.getPort());
+                sp.add(swport);
+            }
+        }
+
+        if (!includeError)
+            return sp.toArray(new SwitchPort[sp.size()]);
+
+        List<AttachmentPoint> oldAPList;
+        oldAPList = new ArrayList<AttachmentPoint>();
+
+        if (oldAPs != null)
+            oldAPList.addAll(oldAPs);
+
+        if (removeExpiredAttachmentPoints(oldAPList))
+            this.oldAPs = oldAPList;
+
+        List<AttachmentPoint> dupList;
+        // get AP map.
+        Map<Long, AttachmentPoint> apMap = getAPMap(apList);
+        dupList = this.getDuplicateAttachmentPoints(oldAPList, apMap);
+        if (dupList != null) {
+            for (AttachmentPoint ap : dupList) {
+                SwitchPort swport = new SwitchPort(ap.getPort(),
+                        ErrorStatus.DUPLICATE_DEVICE);
+                sp.add(swport);
+            }
+        }
+        return sp.toArray(new SwitchPort[sp.size()]);
+    }
+
+    @Override
+    public Long getDeviceKey() {
+        return deviceKey;
+    }
+
+    @Override
+    public long getMACAddress() {
+        // we assume only one MAC per device for now.
+        return entities[0].getMacAddress();
+    }
+
+    @Override
+    public String getMACAddressString() {
+        return macAddressString;
+    }
+
+    @Override
+    public Short[] getVlanId() {
+        return Arrays.copyOf(vlanIds, vlanIds.length);
+    }
+
+    static final EnumSet<DeviceField> ipv4Fields = EnumSet.of(DeviceField.IPV4);
+
+    @Override
+    public Integer[] getIPv4Addresses() {
+        // XXX - TODO we can cache this result. Let's find out if this
+        // is really a performance bottleneck first though.
+
+        TreeSet<Integer> vals = new TreeSet<Integer>();
+        for (Entity e : entities) {
+            if (e.getIpv4Address() == null)
+                continue;
+
+            // We have an IP address only if among the devices within the class
+            // we have the most recent entity with that IP.
+            boolean validIP = true;
+            Iterator<Device> devices = deviceManager.queryClassByEntity(
+                    entityClass, ipv4Fields, e);
+            while (devices.hasNext()) {
+                Device d = devices.next();
+                if (deviceKey.equals(d.getDeviceKey()))
+                    continue;
+                for (Entity se : d.entities) {
+                    if (se.getIpv4Address() != null
+                            && se.getIpv4Address().equals(e.getIpv4Address())
+                            && se.getLastSeenTimestamp() != null
+                            && 0 < se.getLastSeenTimestamp().compareTo(
+                                    e.getLastSeenTimestamp())) {
+                        validIP = false;
+                        break;
+                    }
+                }
+                if (!validIP)
+                    break;
+            }
+
+            if (validIP)
+                vals.add(e.getIpv4Address());
+        }
+
+        return vals.toArray(new Integer[vals.size()]);
+    }
+
+    @Override
+    public Short[] getSwitchPortVlanIds(SwitchPort swp) {
+        TreeSet<Short> vals = new TreeSet<Short>();
+        for (Entity e : entities) {
+            if (e.getPort().equals(swp.getPort())) {
+                if (e.getVlan() == null)
+                    vals.add(VLAN_UNTAGGED);
+                else
+                    vals.add(e.getVlan());
+            }
+        }
+        return vals.toArray(new Short[vals.size()]);
+    }
+
+    @Override
+    public Date getLastSeen() {
+        Date d = null;
+        for (int i = 0; i < entities.length; i++) {
+            if (d == null
+                    || entities[i].getLastSeenTimestamp().compareTo(d) > 0)
+                d = entities[i].getLastSeenTimestamp();
+        }
+        return d;
+    }
+
+    // ***************
+    // Getters/Setters
+    // ***************
+
+    @Override
+    public IEntityClass getEntityClass() {
+        return entityClass;
+    }
+
+    public Entity[] getEntities() {
+        return entities;
+    }
+
+    public String getDHCPClientName() {
+        return dhcpClientName;
+    }
+
+    // ***************
+    // Utility Methods
+    // ***************
+
+    /**
+     * Check whether the device contains the specified entity
+     *
+     * @param entity
+     *            the entity to search for
+     * @return the index of the entity, or <0 if not found
+     */
+    protected int entityIndex(Entity entity) {
+        return Arrays.binarySearch(entities, entity);
+    }
+
+    // ******
+    // Object
+    // ******
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + Arrays.hashCode(entities);
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        Device other = (Device) obj;
+        if (!deviceKey.equals(other.deviceKey))
+            return false;
+        if (!Arrays.equals(entities, other.entities))
+            return false;
+        return true;
+    }
+
+    public HostNodeConnector toHostNodeConnector() {
+        Integer[] ipv4s = this.getIPv4Addresses();
+        try {
+            InetAddress ip = InetAddress.getByName(ipv4s[ipv4s.length - 1]
+                    .toString());
+            byte[] macAddr = macLongToByte(this.getMACAddress());
+            HostNodeConnector nc = new HostNodeConnector(macAddr, ip, null,
+                    (short) 0);
+            return nc;
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    private byte[] macLongToByte(long mac) {
+        byte[] macAddr = new byte[6];
+        for (int i = 0; i < 6; i++) {
+            macAddr[5 - i] = (byte) (mac >> (8 * i));
+        }
+        return macAddr;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("Device [deviceKey=");
+        builder.append(deviceKey);
+        builder.append(", entityClass=");
+        builder.append(entityClass.getName());
+        builder.append(", MAC=");
+        builder.append(macAddressString);
+        builder.append(", IPs=[");
+        boolean isFirst = true;
+        for (Integer ip : getIPv4Addresses()) {
+            if (!isFirst)
+                builder.append(", ");
+            isFirst = false;
+            // builder.append(IPv4.fromIPv4Address(ip));
+            builder.append(ip);
+        }
+        builder.append("], APs=");
+        builder.append(Arrays.toString(getAttachmentPoints(true)));
+        builder.append("]");
+        return builder.toString();
+    }
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndex.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndex.java
new file mode 100644 (file)
index 0000000..5f06806
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.Iterator;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+
+/**
+ * An index that maps key fields of an entity to device keys
+ */
+public abstract class DeviceIndex {
+    /**
+     * The key fields for this index
+     */
+    protected EnumSet<DeviceField> keyFields;
+
+    /**
+     * Construct a new device index using the provided key fields
+     *
+     * @param keyFields
+     *            the key fields to use
+     */
+    public DeviceIndex(EnumSet<DeviceField> keyFields) {
+        super();
+        this.keyFields = keyFields;
+    }
+
+    /**
+     * Find all device keys in the index that match the given entity on all the
+     * key fields for this index
+     *
+     * @param e
+     *            the entity to search for
+     * @return an iterator over device keys
+     */
+    public abstract Iterator<Long> queryByEntity(Entity entity);
+
+    /**
+     * Get all device keys in the index. If certain devices exist multiple
+     * times, then these devices may be returned multiple times
+     *
+     * @return an iterator over device keys
+     */
+    public abstract Iterator<Long> getAll();
+
+    /**
+     * Attempt to update an index with the entities in the provided
+     * {@link Device}. If the update fails because of a concurrent update, will
+     * return false.
+     *
+     * @param device
+     *            the device to update
+     * @param deviceKey
+     *            the device key for the device
+     * @return true if the update succeeded, false otherwise.
+     */
+    public abstract boolean updateIndex(Device device, Long deviceKey);
+
+    /**
+     * Add a mapping from the given entity to the given device key. This update
+     * will not fail because of a concurrent update
+     *
+     * @param device
+     *            the device to update
+     * @param deviceKey
+     *            the device key for the device
+     */
+    public abstract void updateIndex(Entity entity, Long deviceKey);
+
+    /**
+     * Remove the entry for the given entity
+     *
+     * @param entity
+     *            the entity to remove
+     */
+    public abstract void removeEntity(Entity entity);
+
+    /**
+     * Remove the given device key from the index for the given entity
+     *
+     * @param entity
+     *            the entity to search for
+     * @param deviceKey
+     *            the key to remove
+     */
+    public abstract void removeEntity(Entity entity, Long deviceKey);
+
+    /**
+     * Remove the give device from the index only if this the collection of
+     * others does not contain an entity that is identical on all the key fields
+     * for this index.
+     *
+     * @param entity
+     *            the entity to search for
+     * @param deviceKey
+     *            the key to remove
+     * @param others
+     *            the others against which to check
+     */
+    public void removeEntityIfNeeded(Entity entity, Long deviceKey,
+            Collection<Entity> others) {
+        IndexedEntity ie = new IndexedEntity(keyFields, entity);
+        for (Entity o : others) {
+            IndexedEntity oio = new IndexedEntity(keyFields, o);
+            if (oio.equals(ie))
+                return;
+        }
+
+        Iterator<Long> keyiter = this.queryByEntity(entity);
+        while (keyiter.hasNext()) {
+            Long key = keyiter.next();
+            if (key.equals(deviceKey)) {
+                removeEntity(entity, deviceKey);
+                break;
+            }
+        }
+    }
+
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndexInterator.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndexInterator.java
new file mode 100644 (file)
index 0000000..469bd61
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import java.util.Iterator;
+
+/**
+ * An iterator for handling device index queries
+ */
+public class DeviceIndexInterator implements Iterator<Device> {
+    private DeviceManagerImpl deviceManager;
+    private Iterator<Long> subIterator;
+
+    /**
+     * Construct a new device index iterator referring to a device manager
+     * instance and an iterator over device keys
+     *
+     * @param deviceManager
+     *            the device manager
+     * @param subIterator
+     *            an iterator over device keys
+     */
+    public DeviceIndexInterator(DeviceManagerImpl deviceManager,
+            Iterator<Long> subIterator) {
+        super();
+        this.deviceManager = deviceManager;
+        this.subIterator = subIterator;
+    }
+
+    @Override
+    public boolean hasNext() {
+        return subIterator.hasNext();
+    }
+
+    @Override
+    public Device next() {
+        Long next = subIterator.next();
+        return deviceManager.deviceMap.get(next);
+    }
+
+    @Override
+    public void remove() {
+        subIterator.remove();
+    }
+
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIterator.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIterator.java
new file mode 100644 (file)
index 0000000..68f175c
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import java.util.Arrays;
+import java.util.Iterator;
+
+import org.opendaylight.controller.hosttracker.IEntityClass;
+import org.opendaylight.controller.hosttracker.SwitchPort;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.utils.FilterIterator;
+
+/**
+ * An iterator for handling device queries
+ */
+public class DeviceIterator extends FilterIterator<Device> {
+    private IEntityClass[] entityClasses;
+
+    private Long macAddress;
+    private Short vlan;
+    private Integer ipv4Address;
+    private NodeConnector port;
+
+    /**
+     * Construct a new device iterator over the key fields
+     *
+     * @param subIterator
+     *            an iterator over the full data structure to scan
+     * @param entityClasses
+     *            the entity classes to search for
+     * @param macAddress
+     *            The MAC address
+     * @param vlan
+     *            the VLAN
+     * @param ipv4Address
+     *            the ipv4 address
+     * @param switchDPID
+     *            the switch DPID
+     * @param switchPort
+     *            the switch port
+     */
+    public DeviceIterator(Iterator<Device> subIterator,
+            IEntityClass[] entityClasses, Long macAddress, Short vlan,
+            Integer ipv4Address, NodeConnector port) {
+        super(subIterator);
+        this.entityClasses = entityClasses;
+        this.subIterator = subIterator;
+        this.macAddress = macAddress;
+        this.vlan = vlan;
+        this.ipv4Address = ipv4Address;
+        this.port = port;
+    }
+
+    @Override
+    protected boolean matches(Device value) {
+        boolean match;
+        if (entityClasses != null) {
+            IEntityClass clazz = value.getEntityClass();
+            if (clazz == null)
+                return false;
+
+            match = false;
+            for (IEntityClass entityClass : entityClasses) {
+                if (clazz.equals(entityClass)) {
+                    match = true;
+                    break;
+                }
+            }
+            if (!match)
+                return false;
+        }
+        if (macAddress != null) {
+            if (macAddress.longValue() != value.getMACAddress())
+                return false;
+        }
+        if (vlan != null) {
+            Short[] vlans = value.getVlanId();
+            if (Arrays.binarySearch(vlans, vlan) < 0)
+                return false;
+        }
+        if (ipv4Address != null) {
+            Integer[] ipv4Addresses = value.getIPv4Addresses();
+            if (Arrays.binarySearch(ipv4Addresses, ipv4Address) < 0)
+                return false;
+        }
+        if (port != null) {
+            SwitchPort[] sps = value.getAttachmentPoints();
+            if (sps == null)
+                return false;
+
+            match = false;
+            for (SwitchPort sp : sps) {
+                if (sp.getPort().equals(sp.getPort())) {
+                    match = true;
+                    break;
+                }
+            }
+            if (!match)
+                return false;
+        }
+        return true;
+    }
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImpl.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImpl.java
new file mode 100755 (executable)
index 0000000..bda1372
--- /dev/null
@@ -0,0 +1,2371 @@
+/*
+ * Copyright (c) 2011,2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import static org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl.DeviceUpdate.Change.ADD;
+import static org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl.DeviceUpdate.Change.CHANGE;
+import static org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl.DeviceUpdate.Change.DELETE;
+
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDevice;
+import org.opendaylight.controller.hosttracker.IDeviceListener;
+import org.opendaylight.controller.hosttracker.IDeviceService;
+import org.opendaylight.controller.hosttracker.IEntityClass;
+import org.opendaylight.controller.hosttracker.IEntityClassListener;
+import org.opendaylight.controller.hosttracker.IEntityClassifierService;
+import org.opendaylight.controller.hosttracker.IfIptoHost;
+import org.opendaylight.controller.hosttracker.SwitchPort;
+import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
+import org.opendaylight.controller.sal.core.Edge;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
+import org.opendaylight.controller.sal.packet.ARP;
+import org.opendaylight.controller.sal.packet.Ethernet;
+import org.opendaylight.controller.sal.packet.IDataPacketService;
+import org.opendaylight.controller.sal.packet.IListenDataPacket;
+import org.opendaylight.controller.sal.packet.Packet;
+import org.opendaylight.controller.sal.packet.PacketResult;
+import org.opendaylight.controller.sal.packet.RawPacket;
+import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
+import org.opendaylight.controller.sal.utils.ListenerDispatcher;
+import org.opendaylight.controller.sal.utils.MultiIterator;
+import org.opendaylight.controller.sal.utils.SingletonTask;
+import org.opendaylight.controller.sal.utils.Status;
+import org.opendaylight.controller.switchmanager.ISwitchManager;
+import org.opendaylight.controller.topologymanager.ITopologyManager;
+import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * DeviceManager creates Devices based upon MAC addresses seen in the network.
+ * It tracks any network addresses mapped to the Device, and its location within
+ * the network.
+ *
+ * @author readams
+ */
+public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
+        IListenDataPacket, ITopologyManagerAware, IfIptoHost {
+    protected static Logger logger = LoggerFactory
+            .getLogger(DeviceManagerImpl.class);
+
+    public static final String MODULE_NAME = "devicemanager";
+
+    // protected ITopologyService topology;
+    // protected IStorageSourceService storageSource;
+    // protected IRestApiService restApi;
+    // protected IThreadPoolService threadPool;
+    // protected IFlowReconcileService flowReconcileMgr;
+    // protected IFlowReconcileEngineService flowReconcileEngine;
+    // protected IDebugCounterService debugCounters;
+    // private ISyncService syncService;
+    // private IStoreClient<String,DeviceSyncRepresentation> storeClient;
+    // private DeviceSyncManager deviceSyncManager;
+
+    private ITopologyManager topology;
+    private ISwitchManager switchManager = null;
+    private IDataPacketService dataPacketService = null;
+
+    public static final String CNT_INCOMING = MODULE_NAME + "-incoming";
+    public static final String CNT_RECONCILE_REQUEST = MODULE_NAME
+            + "-reconcileRequest";
+    public static final String CNT_RECONCILE_NO_SOURCE = MODULE_NAME
+            + "-reconcileNoSourceDevice";
+    public static final String CNT_RECONCILE_NO_DEST = MODULE_NAME
+            + "-reconcileNoDestDevice";
+    public static final String CNT_BROADCAST_SOURCE = MODULE_NAME
+            + "-broadcastSource";
+    public static final String CNT_NO_SOURCE = MODULE_NAME + "-noSourceDevice";
+    public static final String CNT_NO_DEST = MODULE_NAME + "-noDestDevice";
+    public static final String CNT_DHCP_CLIENT_NAME_SNOOPED = MODULE_NAME
+            + "-dhcpClientNameSnooped";
+    public static final String CNT_DEVICE_ON_INTERAL_PORT_NOT_LEARNED = MODULE_NAME
+            + "-deviceOnInternalPortNotLearned";
+    public static final String CNT_PACKET_NOT_ALLOWED = MODULE_NAME
+            + "-packetNotAllowed";
+    public static final String CNT_NEW_DEVICE = MODULE_NAME + "-newDevice";
+    public static final String CNT_PACKET_ON_INTERNAL_PORT_FOR_KNOWN_DEVICE = MODULE_NAME
+            + "-packetOnInternalPortForKnownDevice";
+    public static final String CNT_NEW_ENTITY = MODULE_NAME + "-newEntity";
+    public static final String CNT_DEVICE_CHANGED = MODULE_NAME
+            + "-deviceChanged";
+    public static final String CNT_DEVICE_MOVED = MODULE_NAME + "-deviceMoved";
+    public static final String CNT_CLEANUP_ENTITIES_RUNS = MODULE_NAME
+            + "-cleanupEntitiesRuns";
+    public static final String CNT_ENTITY_REMOVED_TIMEOUT = MODULE_NAME
+            + "-entityRemovedTimeout";
+    public static final String CNT_DEVICE_DELETED = MODULE_NAME
+            + "-deviceDeleted";
+    public static final String CNT_DEVICE_RECLASSIFY_DELETE = MODULE_NAME
+            + "-deviceReclassifyDelete";
+    public static final String CNT_DEVICE_STORED = MODULE_NAME
+            + "-deviceStored";
+    public static final String CNT_DEVICE_STORE_THROTTLED = MODULE_NAME
+            + "-deviceStoreThrottled";
+    public static final String CNT_DEVICE_REMOVED_FROM_STORE = MODULE_NAME
+            + "-deviceRemovedFromStore";
+    public static final String CNT_SYNC_EXCEPTION = MODULE_NAME
+            + "-syncException";
+    public static final String CNT_DEVICES_FROM_STORE = MODULE_NAME
+            + "-devicesFromStore";
+    public static final String CNT_CONSOLIDATE_STORE_RUNS = MODULE_NAME
+            + "-consolidateStoreRuns";
+    public static final String CNT_CONSOLIDATE_STORE_DEVICES_REMOVED = MODULE_NAME
+            + "-consolidateStoreDevicesRemoved";
+
+    static final String DEVICE_SYNC_STORE_NAME = DeviceManagerImpl.class
+            .getCanonicalName() + ".stateStore";
+
+    /**
+     * Time interval between writes of entries for the same device to the sync
+     * store.
+     */
+    // static final int DEFAULT_SYNC_STORE_WRITE_INTERVAL_MS =
+    // 5*60*1000; // 5 min
+    // private int syncStoreWriteIntervalMs =
+    // DEFAULT_SYNC_STORE_WRITE_INTERVAL_MS;
+
+    /**
+     * Time after SLAVE->MASTER until we run the consolidate store code.
+     */
+    // static final int DEFAULT_INITIAL_SYNC_STORE_CONSOLIDATE_MS =
+    // 15*1000; // 15 sec
+    // private int initialSyncStoreConsolidateMs =
+    // DEFAULT_INITIAL_SYNC_STORE_CONSOLIDATE_MS;
+
+    /**
+     * Time interval between consolidate store runs.
+     */
+    // static final int DEFAULT_SYNC_STORE_CONSOLIDATE_INTERVAL_MS =
+    // 75*60*1000; // 75 min
+    // private final int syncStoreConsolidateIntervalMs =
+    // DEFAULT_SYNC_STORE_CONSOLIDATE_INTERVAL_MS;
+
+    /**
+     * Time in milliseconds before entities will expire
+     */
+    protected static final int ENTITY_TIMEOUT = 60 * 60 * 1000;
+
+    /**
+     * Time in seconds between cleaning up old entities/devices
+     */
+    protected static final int ENTITY_CLEANUP_INTERVAL = 60 * 60;
+
+    /**
+     * This is the master device map that maps device IDs to {@link Device}
+     * objects.
+     */
+    protected ConcurrentHashMap<Long, Device> deviceMap;
+
+    /**
+     * Counter used to generate device keys
+     */
+    protected long deviceKeyCounter = 0;
+
+    /**
+     * Lock for incrementing the device key counter
+     */
+    protected Object deviceKeyLock = new Object();
+
+    /**
+     * This is the primary entity index that contains all entities
+     */
+    protected DeviceUniqueIndex primaryIndex;
+
+    /**
+     * This stores secondary indices over the fields in the devices
+     */
+    protected Map<EnumSet<DeviceField>, DeviceIndex> secondaryIndexMap;
+
+    /**
+     * This map contains state for each of the {@ref IEntityClass} that exist
+     */
+    protected ConcurrentHashMap<String, ClassState> classStateMap;
+
+    /**
+     * This is the list of indices we want on a per-class basis
+     */
+    protected Set<EnumSet<DeviceField>> perClassIndices;
+
+    /**
+     * The entity classifier currently in use
+     */
+    protected IEntityClassifierService entityClassifier;
+
+    /**
+     * Used to cache state about specific entity classes
+     */
+    protected class ClassState {
+
+        /**
+         * The class index
+         */
+        protected DeviceUniqueIndex classIndex;
+
+        /**
+         * This stores secondary indices over the fields in the device for the
+         * class
+         */
+        protected Map<EnumSet<DeviceField>, DeviceIndex> secondaryIndexMap;
+
+        /**
+         * Allocate a new {@link ClassState} object for the class
+         *
+         * @param clazz
+         *            the class to use for the state
+         */
+        public ClassState(IEntityClass clazz) {
+            EnumSet<DeviceField> keyFields = clazz.getKeyFields();
+            EnumSet<DeviceField> primaryKeyFields = entityClassifier
+                    .getKeyFields();
+            boolean keyFieldsMatchPrimary = primaryKeyFields.equals(keyFields);
+
+            if (!keyFieldsMatchPrimary)
+                classIndex = new DeviceUniqueIndex(keyFields);
+
+            secondaryIndexMap = new HashMap<EnumSet<DeviceField>, DeviceIndex>();
+            for (EnumSet<DeviceField> fields : perClassIndices) {
+                secondaryIndexMap.put(fields, new DeviceMultiIndex(fields));
+            }
+        }
+    }
+
+    /**
+     * Device manager event listeners reclassifyDeviceListeners are notified
+     * first before reconcileDeviceListeners. This is to make sure devices are
+     * correctly reclassified before reconciliation.
+     */
+    protected ListenerDispatcher<String, IDeviceListener> deviceListeners;
+
+    /**
+     * A device update event to be dispatched
+     */
+    protected static class DeviceUpdate {
+        public enum Change {
+            ADD, DELETE, CHANGE;
+        }
+
+        /**
+         * The affected device
+         */
+        protected Device device;
+
+        /**
+         * The change that was made
+         */
+        protected Change change;
+
+        /**
+         * If not added, then this is the list of fields changed
+         */
+        protected EnumSet<DeviceField> fieldsChanged;
+
+        public DeviceUpdate(Device device, Change change,
+                EnumSet<DeviceField> fieldsChanged) {
+            super();
+            this.device = device;
+            this.change = change;
+            this.fieldsChanged = fieldsChanged;
+        }
+
+        @Override
+        public String toString() {
+            String devIdStr = device.getEntityClass().getName() + "::"
+                    + device.getMACAddressString();
+            return "DeviceUpdate [device=" + devIdStr + ", change=" + change
+                    + ", fieldsChanged=" + fieldsChanged + "]";
+        }
+
+    }
+
+    /**
+     * AttachmentPointComparator
+     *
+     * Compares two attachment points and returns the latest one. It is assumed
+     * that the two attachment points are in the same L2 domain.
+     *
+     * @author srini
+     */
+    protected class AttachmentPointComparator implements
+            Comparator<AttachmentPoint> {
+        public AttachmentPointComparator() {
+            super();
+        }
+
+        @Override
+        public int compare(AttachmentPoint oldAP, AttachmentPoint newAP) {
+            // First compare based on L2 domain ID;
+
+            // XXX - missing functionality -- need topology
+            // long oldDomain = topology.getL2DomainId(oldSw);
+            // boolean oldBD = topology.isBroadcastDomainPort(oldSw, oldPort);
+            long oldDomain = 0;
+            boolean oldBD = false;
+
+            // XXX - missing functionality -- need topology
+            // long newDomain = topology.getL2DomainId(newSw);
+            // boolean newBD = topology.isBroadcastDomainPort(newSw, newPort);
+            long newDomain = 0;
+            boolean newBD = false;
+
+            if (oldDomain < newDomain)
+                return -1;
+            else if (oldDomain > newDomain)
+                return 1;
+
+            // Give preference to OFPP_LOCAL always
+            if (!oldAP.getPort().getType().equals(NodeConnectorIDType.SWSTACK)
+                    && newAP.getPort().getType()
+                            .equals(NodeConnectorIDType.SWSTACK)) {
+                return -1;
+            } else if (oldAP.getPort().getType()
+                    .equals(NodeConnectorIDType.SWSTACK)
+                    && !newAP.getPort().getType()
+                            .equals(NodeConnectorIDType.SWSTACK)) {
+                return 1;
+            }
+
+            // We expect that the last seen of the new AP is higher than
+            // old AP, if it is not, just reverse and send the negative
+            // of the result.
+            if (oldAP.getActiveSince() > newAP.getActiveSince())
+                return -compare(newAP, oldAP);
+
+            long activeOffset = 0;
+            // XXX - missing functionality -- need topology
+            // if (!topology.isConsistent(oldSw, oldPort, newSw, newPort)) {
+            if (!newBD && oldBD) {
+                return -1;
+            }
+            if (newBD && oldBD) {
+                activeOffset = AttachmentPoint.EXTERNAL_TO_EXTERNAL_TIMEOUT;
+            } else if (newBD && !oldBD) {
+                activeOffset = AttachmentPoint.OPENFLOW_TO_EXTERNAL_TIMEOUT;
+            }
+
+            // } else {
+            // // The attachment point is consistent.
+            // activeOffset = AttachmentPoint.CONSISTENT_TIMEOUT;
+            // }
+
+            if ((newAP.getActiveSince() > oldAP.getLastSeen() + activeOffset)
+                    || (newAP.getLastSeen() > oldAP.getLastSeen()
+                            + AttachmentPoint.INACTIVITY_INTERVAL)) {
+                return -1;
+            }
+            return 1;
+        }
+    }
+
+    /**
+     * Comparator for sorting by cluster ID
+     */
+    public AttachmentPointComparator apComparator;
+
+    /**
+     * Switch ports where attachment points shouldn't be learned
+     */
+    private Set<SwitchPort> suppressAPs;
+
+    /**
+     * Periodic task to clean up expired entities
+     */
+    public SingletonTask entityCleanupTask;
+
+    // ********************
+    // Dependency injection
+    // ********************
+
+    void setDataPacketService(IDataPacketService s) {
+        this.dataPacketService = s;
+    }
+
+    void unsetDataPacketService(IDataPacketService s) {
+        if (this.dataPacketService == s) {
+            this.dataPacketService = null;
+        }
+    }
+
+    public void setTopologyManager(ITopologyManager s) {
+        this.topology = s;
+    }
+
+    public void unsetTopologyManager(ITopologyManager s) {
+        if (this.topology == s) {
+            logger.debug("Topology Manager Service removed!");
+            this.topology = null;
+        }
+    }
+
+    private volatile boolean stopped = true;
+    private ScheduledExecutorService ses;
+
+    public void stop() {
+        stopped = true;
+        if (ses != null)
+            ses.shutdownNow();
+    }
+
+    public void start() {
+        this.perClassIndices = new HashSet<EnumSet<DeviceField>>();
+
+        // XXX - TODO need to make it possible to register a non-default
+        // classifier
+        entityClassifier = new DefaultEntityClassifier();
+        this.deviceListeners = new ListenerDispatcher<String, IDeviceListener>();
+        this.suppressAPs = Collections
+                .newSetFromMap(new ConcurrentHashMap<SwitchPort, Boolean>());
+        primaryIndex = new DeviceUniqueIndex(entityClassifier.getKeyFields());
+        secondaryIndexMap = new HashMap<EnumSet<DeviceField>, DeviceIndex>();
+
+        deviceMap = new ConcurrentHashMap<Long, Device>();
+        classStateMap = new ConcurrentHashMap<String, ClassState>();
+        apComparator = new AttachmentPointComparator();
+
+        addIndex(true, EnumSet.of(DeviceField.IPV4));
+
+        // floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
+        // floodlightProvider.addHAListener(this.haListenerDelegate);
+        // if (topology != null)
+        // topology.addListener(this);
+        // flowReconcileMgr.addFlowReconcileListener(this);
+        // entityClassifier.addListener(this);
+
+        stopped = false;
+        // XXX - Should use a common threadpool but this doesn't currently exist
+        ses = Executors.newScheduledThreadPool(1);
+        Runnable ecr = new Runnable() {
+            @Override
+            public void run() {
+                cleanupEntities();
+                if (!stopped)
+                    entityCleanupTask.reschedule(ENTITY_CLEANUP_INTERVAL,
+                            TimeUnit.SECONDS);
+            }
+        };
+        entityCleanupTask = new SingletonTask(ses, ecr);
+        entityCleanupTask.reschedule(ENTITY_CLEANUP_INTERVAL, TimeUnit.SECONDS);
+
+        /*
+         * XXX Missing functionality if (restApi != null) {
+         * restApi.addRestletRoutable(new DeviceRoutable()); } else {
+         * logger.debug("Could not instantiate REST API"); }
+         */
+
+        registerDeviceManagerDebugCounters();
+
+        /*
+         * XXX Missing functionality try {
+         * this.syncService.registerStore(DEVICE_SYNC_STORE_NAME, Scope.LOCAL);
+         * this.storeClient = this.syncService
+         * .getStoreClient(DEVICE_SYNC_STORE_NAME, String.class,
+         * DeviceSyncRepresentation.class); } catch (SyncException e) { throw
+         * new FloodlightModuleException("Error while setting up sync service",
+         * e); }
+         *
+         * Runnable consolidateStoreRunner = new Runnable() {
+         *
+         * @Override public void run() { deviceSyncManager.consolidateStore();
+         * storeConsolidateTask.reschedule(syncStoreConsolidateIntervalMs,
+         * TimeUnit.MILLISECONDS); debugCounters.flushCounters(); } };
+         * storeConsolidateTask = new SingletonTask(ses,
+         * consolidateStoreRunner); if (isMaster)
+         * storeConsolidateTask.reschedule(syncStoreConsolidateIntervalMs,
+         * TimeUnit.MILLISECONDS);
+         */
+    }
+
+    /**
+     * Periodic task to consolidate entries in the store. I.e., delete entries
+     * in the store that are not known to DeviceManager
+     */
+    // XXX - Missing functionality
+    // private SingletonTask storeConsolidateTask;
+
+    // *********************
+    // IDeviceManagerService
+    // *********************
+
+    void setSwitchManager(ISwitchManager s) {
+        logger.debug("SwitchManager set");
+        this.switchManager = s;
+    }
+
+    void unsetSwitchManager(ISwitchManager s) {
+        if (this.switchManager == s) {
+            logger.debug("SwitchManager removed!");
+            this.switchManager = null;
+        }
+    }
+
+    @Override
+    public IDevice getDevice(Long deviceKey) {
+        return deviceMap.get(deviceKey);
+    }
+
+    @Override
+    public IDevice findDevice(long macAddress, Short vlan, Integer ipv4Address,
+            NodeConnector port) throws IllegalArgumentException {
+        if (vlan != null && vlan.shortValue() <= 0)
+            vlan = null;
+        if (ipv4Address != null && ipv4Address == 0)
+            ipv4Address = null;
+        Entity e = new Entity(macAddress, vlan, ipv4Address, port, null);
+        if (!allKeyFieldsPresent(e, entityClassifier.getKeyFields())) {
+            throw new IllegalArgumentException("Not all key fields specified."
+                    + " Required fields: " + entityClassifier.getKeyFields());
+        }
+        return findDeviceByEntity(e);
+    }
+
+    @Override
+    public IDevice findClassDevice(IEntityClass entityClass, long macAddress,
+            Short vlan, Integer ipv4Address) throws IllegalArgumentException {
+        if (vlan != null && vlan.shortValue() <= 0)
+            vlan = null;
+        if (ipv4Address != null && ipv4Address == 0)
+            ipv4Address = null;
+        Entity e = new Entity(macAddress, vlan, ipv4Address, null, null);
+        if (entityClass == null
+                || !allKeyFieldsPresent(e, entityClass.getKeyFields())) {
+            throw new IllegalArgumentException("Not all key fields and/or "
+                    + " no source device specified. Required fields: "
+                    + entityClassifier.getKeyFields());
+        }
+        return findDestByEntity(entityClass, e);
+    }
+
+    @Override
+    public Collection<? extends IDevice> getAllDevices() {
+        return Collections.unmodifiableCollection(deviceMap.values());
+    }
+
+    @Override
+    public void addIndex(boolean perClass, EnumSet<DeviceField> keyFields) {
+        if (perClass) {
+            perClassIndices.add(keyFields);
+        } else {
+            secondaryIndexMap.put(keyFields, new DeviceMultiIndex(keyFields));
+        }
+    }
+
+    @Override
+    public Iterator<? extends IDevice> queryDevices(Long macAddress,
+            Short vlan, Integer ipv4Address, NodeConnector port) {
+        DeviceIndex index = null;
+        if (secondaryIndexMap.size() > 0) {
+            EnumSet<DeviceField> keys = getEntityKeys(macAddress, vlan,
+                    ipv4Address, port);
+            index = secondaryIndexMap.get(keys);
+        }
+
+        Iterator<Device> deviceIterator = null;
+        if (index == null) {
+            // Do a full table scan
+            deviceIterator = deviceMap.values().iterator();
+        } else {
+            // index lookup
+            Entity entity = new Entity((macAddress == null ? 0 : macAddress),
+                    vlan, ipv4Address, port, null);
+            deviceIterator = new DeviceIndexInterator(this,
+                    index.queryByEntity(entity));
+        }
+
+        DeviceIterator di = new DeviceIterator(deviceIterator, null,
+                macAddress, vlan, ipv4Address, port);
+        return di;
+    }
+
+    @Override
+    public Iterator<? extends IDevice> queryClassDevices(
+            IEntityClass entityClass, Long macAddress, Short vlan,
+            Integer ipv4Address, NodeConnector port) {
+        ArrayList<Iterator<Device>> iterators = new ArrayList<Iterator<Device>>();
+        ClassState classState = getClassState(entityClass);
+
+        DeviceIndex index = null;
+        if (classState.secondaryIndexMap.size() > 0) {
+            EnumSet<DeviceField> keys = getEntityKeys(macAddress, vlan,
+                    ipv4Address, port);
+            index = classState.secondaryIndexMap.get(keys);
+        }
+
+        Iterator<Device> iter;
+        if (index == null) {
+            index = classState.classIndex;
+            if (index == null) {
+                // scan all devices
+                return new DeviceIterator(deviceMap.values().iterator(),
+                        new IEntityClass[] { entityClass }, macAddress, vlan,
+                        ipv4Address, port);
+            } else {
+                // scan the entire class
+                iter = new DeviceIndexInterator(this, index.getAll());
+            }
+        } else {
+            // index lookup
+            Entity entity = new Entity((macAddress == null ? 0 : macAddress),
+                    vlan, ipv4Address, port, null);
+            iter = new DeviceIndexInterator(this, index.queryByEntity(entity));
+        }
+        iterators.add(iter);
+
+        return new MultiIterator<Device>(iterators.iterator());
+    }
+
+    protected Iterator<Device> getDeviceIteratorForQuery(Long macAddress,
+            Short vlan, Integer ipv4Address, NodeConnector port) {
+        DeviceIndex index = null;
+        if (secondaryIndexMap.size() > 0) {
+            EnumSet<DeviceField> keys = getEntityKeys(macAddress, vlan,
+                    ipv4Address, port);
+            index = secondaryIndexMap.get(keys);
+        }
+
+        Iterator<Device> deviceIterator = null;
+        if (index == null) {
+            // Do a full table scan
+            deviceIterator = deviceMap.values().iterator();
+        } else {
+            // index lookup
+            Entity entity = new Entity((macAddress == null ? 0 : macAddress),
+                    vlan, ipv4Address, port, null);
+            deviceIterator = new DeviceIndexInterator(this,
+                    index.queryByEntity(entity));
+        }
+
+        DeviceIterator di = new DeviceIterator(deviceIterator, null,
+                macAddress, vlan, ipv4Address, port);
+        return di;
+    }
+
+    @Override
+    public void addListener(IDeviceListener listener) {
+        deviceListeners.addListener("device", listener);
+        logListeners();
+    }
+
+    @Override
+    public void addSuppressAPs(NodeConnector port) {
+        suppressAPs.add(new SwitchPort(port));
+    }
+
+    @Override
+    public void removeSuppressAPs(NodeConnector port) {
+        suppressAPs.remove(new SwitchPort(port));
+    }
+
+    @Override
+    public Set<SwitchPort> getSuppressAPs() {
+        return Collections.unmodifiableSet(suppressAPs);
+    }
+
+    private void logListeners() {
+        List<IDeviceListener> listeners = deviceListeners.getOrderedListeners();
+        if (listeners != null) {
+            StringBuffer sb = new StringBuffer();
+            sb.append("DeviceListeners: ");
+            for (IDeviceListener l : listeners) {
+                sb.append(l.getName());
+                sb.append(",");
+            }
+            logger.debug(sb.toString());
+        }
+    }
+
+    // ***************
+    // IFlowReconcileListener
+    // ***************
+    /*
+     * XXX - Missing functionality
+     *
+     * @Override public Command reconcileFlows(ArrayList<OFMatchReconcile>
+     * ofmRcList) { ListIterator<OFMatchReconcile> iter =
+     * ofmRcList.listIterator(); while (iter.hasNext()) { OFMatchReconcile ofm =
+     * iter.next();
+     *
+     * // Remove the STOPPed flow. if (Command.STOP == reconcileFlow(ofm)) {
+     * iter.remove(); } }
+     *
+     * if (ofmRcList.size() > 0) { return Command.CONTINUE; } else { return
+     * Command.STOP; } }
+     *
+     * protected Command reconcileFlow(OFMatchReconcile ofm) {
+     * debugCounters.updateCounter(CNT_RECONCILE_REQUEST); // Extract source
+     * entity information Entity srcEntity =
+     * getEntityFromFlowMod(ofm.ofmWithSwDpid, true); if (srcEntity == null) {
+     * debugCounters.updateCounter(CNT_RECONCILE_NO_SOURCE); return
+     * Command.STOP; }
+     *
+     * // Find the device by source entity Device srcDevice =
+     * findDeviceByEntity(srcEntity); if (srcDevice == null) {
+     * debugCounters.updateCounter(CNT_RECONCILE_NO_SOURCE); return
+     * Command.STOP; } // Store the source device in the context
+     * fcStore.put(ofm.cntx, CONTEXT_SRC_DEVICE, srcDevice);
+     *
+     * // Find the device matching the destination from the entity // classes of
+     * the source. Entity dstEntity = getEntityFromFlowMod(ofm.ofmWithSwDpid,
+     * false); Device dstDevice = null; if (dstEntity != null) { dstDevice =
+     * findDestByEntity(srcDevice.getEntityClass(), dstEntity); if (dstDevice !=
+     * null) fcStore.put(ofm.cntx, CONTEXT_DST_DEVICE, dstDevice); else
+     * debugCounters.updateCounter(CNT_RECONCILE_NO_DEST); } else {
+     * debugCounters.updateCounter(CNT_RECONCILE_NO_DEST); } if
+     * (logger.isTraceEnabled()) {
+     * logger.trace("Reconciling flow: match={}, srcEntity={}, srcDev={}, " +
+     * "dstEntity={}, dstDev={}", new Object[] {ofm.ofmWithSwDpid.getOfMatch(),
+     * srcEntity, srcDevice, dstEntity, dstDevice } ); } return
+     * Command.CONTINUE; }
+     */
+
+    // *****************
+    // IListenDataPacket
+    // *****************
+
+    @Override
+    public PacketResult receiveDataPacket(RawPacket inPkt) {
+        // XXX - Can this really pass in null? Why would you ever want that?
+        if (inPkt == null) {
+            return PacketResult.IGNORED;
+        }
+        try {
+            throw new Exception("Sample");
+        } catch (Exception e) {
+            logger.error("Sample stack trace", e);
+        }
+
+        Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt);
+        Ethernet eth;
+        if (formattedPak instanceof Ethernet) {
+            eth = (Ethernet) formattedPak;
+        } else {
+            return PacketResult.IGNORED;
+        }
+
+        // Extract source entity information
+        NodeConnector inPort = inPkt.getIncomingNodeConnector();
+        Entity srcEntity = getSourceEntityFromPacket(eth, inPort);
+        if (srcEntity == null) {
+            // debugCounters.updateCounter(CNT_BROADCAST_SOURCE);
+            return PacketResult.CONSUME;
+        }
+
+        // Learn from ARP packet for special VRRP settings.
+        // In VRRP settings, the source MAC address and sender MAC
+        // addresses can be different. In such cases, we need to learn
+        // the IP to MAC mapping of the VRRP IP address. The source
+        // entity will not have that information. Hence, a separate call
+        // to learn devices in such cases.
+        learnDeviceFromArpResponseData(eth, inPort);
+
+        // Learn/lookup device information
+        Device srcDevice = learnDeviceByEntity(srcEntity);
+        if (srcDevice == null) {
+            // debugCounters.updateCounter(CNT_NO_SOURCE);
+            return PacketResult.CONSUME;
+        }
+        logger.trace("Saw packet from device {}", srcDevice);
+
+        // // Store the source device in the context
+        // fcStore.put(cntx, CONTEXT_SRC_DEVICE, srcDevice);
+        //
+        // // Find the device matching the destination from the entity
+        // // classes of the source.
+        // Entity dstEntity = getDestEntityFromPacket(eth);
+        // Device dstDevice = null;
+        // if (dstEntity != null) {
+        // dstDevice =
+        // findDestByEntity(srcDevice.getEntityClass(), dstEntity);
+        // if (dstDevice != null)
+        // fcStore.put(cntx, CONTEXT_DST_DEVICE, dstDevice);
+        // //else
+        // //debugCounters.updateCounter(CNT_NO_DEST);
+        // } else {
+        // //debugCounters.updateCounter(CNT_NO_DEST);
+        // }
+        //
+        // if (logger.isTraceEnabled()) {
+        // logger.trace("Received PI: {} on switch {}, port {} *** eth={}" +
+        // " *** srcDev={} *** dstDev={} *** ",
+        // new Object[] { pi, sw.getStringId(), pi.getInPort(), eth,
+        // srcDevice, dstDevice });
+        // }
+        //
+        // snoopDHCPClientName(eth, srcDevice);
+
+        return PacketResult.KEEP_PROCESSING;
+    }
+
+    // ****************
+    // Internal methods
+    // ****************
+
+    /**
+     * Snoop and record client-provided host name from DHCP requests
+     *
+     * @param eth
+     * @param srcDevice
+     */
+    // private void snoopDHCPClientName(Ethernet eth, Device srcDevice) {
+    // if (! (eth.getPayload() instanceof IPv4) )
+    // return;
+    // IPv4 ipv4 = (IPv4) eth.getPayload();
+    // if (! (ipv4.getPayload() instanceof UDP) )
+    // return;
+    // UDP udp = (UDP) ipv4.getPayload();
+    // if (!(udp.getPayload() instanceof DHCP))
+    // return;
+    // DHCP dhcp = (DHCP) udp.getPayload();
+    // byte opcode = dhcp.getOpCode();
+    // if (opcode == DHCP.OPCODE_REQUEST) {
+    // DHCPOption dhcpOption = dhcp.getOption(
+    // DHCPOptionCode.OptionCode_Hostname);
+    // if (dhcpOption != null) {
+    // debugCounters.updateCounter(CNT_DHCP_CLIENT_NAME_SNOOPED);
+    // srcDevice.dhcpClientName = new String(dhcpOption.getData());
+    // }
+    // }
+    // }
+
+    /**
+     * Check whether the given attachment point is valid given the current
+     * topology
+     *
+     * @param switchDPID
+     *            the DPID
+     * @param switchPort
+     *            the port
+     * @return true if it's a valid attachment point
+     */
+    public boolean isValidAttachmentPoint(NodeConnector port) {
+        // XXX - missing functionality -- need topology module
+        // if (topology.isAttachmentPointPort(port) == false)
+        // return false;
+        if (topology.isInternal(port))
+            return false;
+        if (!switchManager.isNodeConnectorEnabled(port))
+            return false;
+        if (suppressAPs.contains(new SwitchPort(port)))
+            return false;
+
+        return true;
+    }
+
+    /**
+     * Get sender IP address from packet if the packet is either an ARP packet.
+     *
+     * @param eth
+     * @param dlAddr
+     * @return
+     */
+    private int getSrcNwAddr(Ethernet eth, long dlAddr) {
+        if (eth.getPayload() instanceof ARP) {
+            ARP arp = (ARP) eth.getPayload();
+            if ((arp.getProtocolType() == ARP.PROTO_TYPE_IP)
+                    && (toLong(arp.getSenderHardwareAddress()) == dlAddr)) {
+                return toIPv4Address(arp.getSenderProtocolAddress());
+            }
+        }
+        return 0;
+    }
+
+    /**
+     * Parse an entity from an {@link Ethernet} packet.
+     *
+     * @param eth
+     *            the packet to parse
+     * @param sw
+     *            the switch on which the packet arrived
+     * @param pi
+     *            the original packetin
+     * @return the entity from the packet
+     */
+    protected Entity getSourceEntityFromPacket(Ethernet eth, NodeConnector port) {
+        byte[] dlAddrArr = eth.getSourceMACAddress();
+        long dlAddr = toLong(dlAddrArr);
+
+        // Ignore broadcast/multicast source
+        if ((dlAddrArr[0] & 0x1) != 0)
+            return null;
+
+        // XXX missing functionality
+        // short vlan = 0;
+        int nwSrc = getSrcNwAddr(eth, dlAddr);
+        return new Entity(dlAddr, null, ((nwSrc != 0) ? nwSrc : null), port,
+                new Date());
+    }
+
+    /**
+     * Learn device from ARP data in scenarios where the Ethernet source MAC is
+     * different from the sender hardware address in ARP data.
+     */
+    protected void learnDeviceFromArpResponseData(Ethernet eth,
+            NodeConnector port) {
+
+        if (!(eth.getPayload() instanceof ARP))
+            return;
+        ARP arp = (ARP) eth.getPayload();
+
+        byte[] dlAddrArr = eth.getSourceMACAddress();
+        long dlAddr = toLong(dlAddrArr);
+
+        byte[] senderHardwareAddr = arp.getSenderHardwareAddress();
+        long senderAddr = toLong(senderHardwareAddr);
+
+        if (dlAddr == senderAddr)
+            return;
+
+        // Ignore broadcast/multicast source
+        if ((senderHardwareAddr[0] & 0x1) != 0)
+            return;
+
+        // short vlan = eth.getVlanID();
+        int nwSrc = toIPv4Address(arp.getSenderProtocolAddress());
+
+        Entity e = new Entity(senderAddr, null, ((nwSrc != 0) ? nwSrc : null),
+                port, new Date());
+
+        learnDeviceByEntity(e);
+    }
+
+    /**
+     * Get a (partial) entity for the destination from the packet.
+     *
+     * @param eth
+     * @return
+     */
+    // protected Entity getDestEntityFromPacket(Ethernet eth) {
+    // byte[] dlAddrArr = eth.getDestinationMACAddress();
+    // long dlAddr = Ethernet.toLong(dlAddrArr);
+    // short vlan = eth.getVlanID();
+    // int nwDst = 0;
+    //
+    // // Ignore broadcast/multicast destination
+    // if ((dlAddrArr[0] & 0x1) != 0)
+    // return null;
+    //
+    // if (eth.getPayload() instanceof IPv4) {
+    // IPv4 ipv4 = (IPv4) eth.getPayload();
+    // nwDst = ipv4.getDestinationAddress();
+    // }
+    //
+    // return new Entity(dlAddr,
+    // ((vlan >= 0) ? vlan : null),
+    // ((nwDst != 0) ? nwDst : null),
+    // null,
+    // null,
+    // null);
+    // }
+
+    /**
+     * Parse an entity from an OFMatchWithSwDpid.
+     *
+     * @param ofmWithSwDpid
+     * @return the entity from the packet
+     */
+    // private Entity getEntityFromFlowMod(OFMatchWithSwDpid ofmWithSwDpid,
+    // boolean isSource) {
+    // byte[] dlAddrArr = ofmWithSwDpid.getOfMatch().getDataLayerSource();
+    // int nwSrc = ofmWithSwDpid.getOfMatch().getNetworkSource();
+    // if (!isSource) {
+    // dlAddrArr = ofmWithSwDpid.getOfMatch().getDataLayerDestination();
+    // nwSrc = ofmWithSwDpid.getOfMatch().getNetworkDestination();
+    // }
+    //
+    // long dlAddr = Ethernet.toLong(dlAddrArr);
+    //
+    // // Ignore broadcast/multicast source
+    // if ((dlAddrArr[0] & 0x1) != 0)
+    // return null;
+    //
+    // Long swDpid = null;
+    // Short inPort = null;
+    //
+    // if (isSource) {
+    // swDpid = ofmWithSwDpid.getSwitchDataPathId();
+    // inPort = ofmWithSwDpid.getOfMatch().getInputPort();
+    // }
+    //
+    // /**for the new flow cache design, the flow mods retrived are not always
+    // from the source, learn AP should be disabled --meiyang*/
+    // boolean learnap = false;
+    // /**
+    // * if (swDpid == null ||
+    // inPort == null ||
+    // !isValidAttachmentPoint(swDpid, inPort)) {
+    // // If this is an internal port or we otherwise don't want
+    // // to learn on these ports. In the future, we should
+    // // handle this case by labeling flows with something that
+    // // will give us the entity class. For now, we'll do our
+    // // best assuming attachment point information isn't used
+    // // as a key field.
+    // learnap = false;
+    // }
+    // */
+    //
+    // short vlan = ofmWithSwDpid.getOfMatch().getDataLayerVirtualLan();
+    // return new Entity(dlAddr,
+    // ((vlan >= 0) ? vlan : null),
+    // ((nwSrc != 0) ? nwSrc : null),
+    // (learnap ? swDpid : null),
+    // (learnap ? (int)inPort : null),
+    // new Date());
+    // }
+
+    /**
+     * Look up a {@link Device} based on the provided {@link Entity}. We first
+     * check the primary index. If we do not find an entry there we classify the
+     * device into its IEntityClass and query the classIndex. This implies that
+     * all key field of the current IEntityClassifier must be present in the
+     * entity for the lookup to succeed!
+     *
+     * @param entity
+     *            the entity to search for
+     * @return The {@link Device} object if found
+     */
+    protected Device findDeviceByEntity(Entity entity) {
+        // Look up the fully-qualified entity to see if it already
+        // exists in the primary entity index.
+        Long deviceKey = primaryIndex.findByEntity(entity);
+        IEntityClass entityClass = null;
+
+        if (deviceKey == null) {
+            // If the entity does not exist in the primary entity index,
+            // use the entity classifier for find the classes for the
+            // entity. Look up the entity in the returned class'
+            // class entity index.
+            entityClass = entityClassifier.classifyEntity(entity);
+            if (entityClass == null) {
+                return null;
+            }
+            ClassState classState = getClassState(entityClass);
+
+            if (classState.classIndex != null) {
+                deviceKey = classState.classIndex.findByEntity(entity);
+            }
+        }
+        if (deviceKey == null)
+            return null;
+        return deviceMap.get(deviceKey);
+    }
+
+    /**
+     * Get a destination device using entity fields that corresponds with the
+     * given source device. The source device is important since there could be
+     * ambiguity in the destination device without the attachment point
+     * information.
+     *
+     * @param reference
+     *            the source device's entity class. The returned destination
+     *            will be in the same entity class as the source.
+     * @param dstEntity
+     *            the entity to look up
+     * @return an {@link Device} or null if no device is found.
+     */
+    protected Device findDestByEntity(IEntityClass reference, Entity dstEntity) {
+
+        // Look up the fully-qualified entity to see if it
+        // exists in the primary entity index
+        Long deviceKey = primaryIndex.findByEntity(dstEntity);
+
+        if (deviceKey == null) {
+            // This could happen because:
+            // 1) no destination known, or a broadcast destination
+            // 2) if we have attachment point key fields since
+            // attachment point information isn't available for
+            // destination devices.
+            // For the second case, we'll need to match up the
+            // destination device with the class of the source
+            // device.
+            ClassState classState = getClassState(reference);
+            if (classState.classIndex == null) {
+                return null;
+            }
+            deviceKey = classState.classIndex.findByEntity(dstEntity);
+        }
+        if (deviceKey == null)
+            return null;
+        return deviceMap.get(deviceKey);
+    }
+
+    /**
+     * Look up a {@link Device} within a particular entity class based on the
+     * provided {@link Entity}.
+     *
+     * @param clazz
+     *            the entity class to search for the entity
+     * @param entity
+     *            the entity to search for
+     * @return The {@link Device} object if found private Device
+     *         findDeviceInClassByEntity(IEntityClass clazz, Entity entity) { //
+     *         XXX - TODO throw new UnsupportedOperationException(); }
+     */
+
+    /**
+     * Look up a {@link Device} based on the provided {@link Entity}. Also
+     * learns based on the new entity, and will update existing devices as
+     * required.
+     *
+     * @param entity
+     *            the {@link Entity}
+     * @return The {@link Device} object if found
+     */
+    protected Device learnDeviceByEntity(Entity entity) {
+        logger.info("Primary index {}", primaryIndex);
+        ArrayList<Long> deleteQueue = null;
+        LinkedList<DeviceUpdate> deviceUpdates = null;
+        Device device = null;
+
+        // we may need to restart the learning process if we detect
+        // concurrent modification. Note that we ensure that at least
+        // one thread should always succeed so we don't get into infinite
+        // starvation loops
+        while (true) {
+            deviceUpdates = null;
+
+            // Look up the fully-qualified entity to see if it already
+            // exists in the primary entity index.
+            Long deviceKey = primaryIndex.findByEntity(entity);
+            IEntityClass entityClass = null;
+
+            if (deviceKey == null) {
+                // If the entity does not exist in the primary entity index,
+                // use the entity classifier for find the classes for the
+                // entity. Look up the entity in the returned class'
+                // class entity index.
+                entityClass = entityClassifier.classifyEntity(entity);
+                if (entityClass == null) {
+                    // could not classify entity. No device
+                    device = null;
+                    break;
+                }
+                ClassState classState = getClassState(entityClass);
+
+                if (classState.classIndex != null) {
+                    deviceKey = classState.classIndex.findByEntity(entity);
+                }
+            }
+            if (deviceKey != null) {
+                // If the primary or secondary index contains the entity
+                // use resulting device key to look up the device in the
+                // device map, and use the referenced Device below.
+                device = deviceMap.get(deviceKey);
+                if (device == null) {
+                    // This can happen due to concurrent modification
+                    if (logger.isDebugEnabled()) {
+                        logger.debug("No device for deviceKey {} while "
+                                + "while processing entity {}", deviceKey,
+                                entity);
+                    }
+                    // if so, then try again till we don't even get the device
+                    // key
+                    // and so we recreate the device
+                    continue;
+                }
+            } else {
+                // If the secondary index does not contain the entity,
+                // create a new Device object containing the entity, and
+                // generate a new device ID if the the entity is on an
+                // attachment point port. Otherwise ignore.
+                if (entity.hasSwitchPort()
+                        && !isValidAttachmentPoint(entity.getPort())) {
+                    // debugCounters.updateCounter(CNT_DEVICE_ON_INTERAL_PORT_NOT_LEARNED);
+                    if (logger.isDebugEnabled()) {
+                        logger.debug("Not learning new device on internal"
+                                + " link: {}", entity);
+                    }
+                    device = null;
+                    break;
+                }
+                // Before we create the new device also check if
+                // the entity is allowed (e.g., for spoofing protection)
+                if (!isEntityAllowed(entity, entityClass)) {
+                    // debugCounters.updateCounter(CNT_PACKET_NOT_ALLOWED);
+                    if (logger.isDebugEnabled()) {
+                        logger.debug("PacketIn is not allowed {} {}",
+                                entityClass.getName(), entity);
+                    }
+                    device = null;
+                    break;
+                }
+                synchronized (deviceKeyLock) {
+                    deviceKey = Long.valueOf(deviceKeyCounter++);
+                }
+                device = allocateDevice(deviceKey, entity, entityClass);
+
+                // Add the new device to the primary map with a simple put
+                deviceMap.put(deviceKey, device);
+
+                // update indices
+                if (!updateIndices(device, deviceKey)) {
+                    if (deleteQueue == null)
+                        deleteQueue = new ArrayList<Long>();
+                    deleteQueue.add(deviceKey);
+                    continue;
+                }
+
+                updateSecondaryIndices(entity, entityClass, deviceKey);
+
+                // We need to count and log here. If we log earlier we could
+                // hit a concurrent modification and restart the dev creation
+                // and potentially count the device twice.
+                // debugCounters.updateCounter(CNT_NEW_DEVICE);
+                if (logger.isDebugEnabled()) {
+                    logger.debug(
+                            "New device created: {} deviceKey={}, entity={}",
+                            new Object[] { device, deviceKey, entity });
+                }
+                // generate new device update
+                deviceUpdates = updateUpdates(deviceUpdates, new DeviceUpdate(
+                        device, ADD, null));
+
+                break;
+            }
+            // if it gets here, we have a pre-existing Device for this Entity
+            if (!isEntityAllowed(entity, device.getEntityClass())) {
+                // debugCounters.updateCounter(CNT_PACKET_NOT_ALLOWED);
+                if (logger.isDebugEnabled()) {
+                    logger.info("PacketIn is not allowed {} {}", device
+                            .getEntityClass().getName(), entity);
+                }
+                return null;
+            }
+            // If this is not an attachment point port we don't learn the new
+            // entity
+            // and don't update indexes. But we do allow the device to continue
+            // up
+            // the chain.
+            if (entity.hasSwitchPort()
+                    && !isValidAttachmentPoint(entity.getPort())) {
+                // debugCounters.updateCounter(CNT_PACKET_ON_INTERNAL_PORT_FOR_KNOWN_DEVICE);
+                break;
+            }
+            int entityindex = -1;
+            if ((entityindex = device.entityIndex(entity)) >= 0) {
+                // Entity already exists
+                // update timestamp on the found entity
+                Date lastSeen = entity.getLastSeenTimestamp();
+                if (lastSeen == null) {
+                    lastSeen = new Date();
+                    entity.setLastSeenTimestamp(lastSeen);
+                }
+                device.entities[entityindex].setLastSeenTimestamp(lastSeen);
+                // we break the loop after checking for changes to the AP
+            } else {
+                // New entity for this device
+                // compute the insertion point for the entity.
+                // see Arrays.binarySearch()
+                entityindex = -(entityindex + 1);
+                Device newDevice = allocateDevice(device, entity, entityindex);
+
+                // generate updates
+                EnumSet<DeviceField> changedFields = findChangedFields(device,
+                        entity);
+
+                // update the device map with a replace call
+                boolean res = deviceMap.replace(deviceKey, device, newDevice);
+                // If replace returns false, restart the process from the
+                // beginning (this implies another thread concurrently
+                // modified this Device).
+                if (!res)
+                    continue;
+
+                device = newDevice;
+                // update indices
+                if (!updateIndices(device, deviceKey)) {
+                    continue;
+                }
+                updateSecondaryIndices(entity, device.getEntityClass(),
+                        deviceKey);
+
+                // We need to count here after all the possible "continue"
+                // statements in this branch
+                // debugCounters.updateCounter(CNT_NEW_ENTITY);
+                if (changedFields.size() > 0) {
+                    // debugCounters.updateCounter(CNT_DEVICE_CHANGED);
+                    deviceUpdates = updateUpdates(deviceUpdates,
+                            new DeviceUpdate(newDevice, CHANGE, changedFields));
+                }
+                // we break the loop after checking for changed AP
+            }
+            // Update attachment point (will only be hit if the device
+            // already existed and no concurrent modification)
+            if (entity.hasSwitchPort()) {
+                boolean moved = device.updateAttachmentPoint(entity.getPort(),
+                        entity.getLastSeenTimestamp().getTime());
+                // TODO: use update mechanism instead of sending the
+                // notification directly
+                if (moved) {
+                    // we count device moved events in
+                    // sendDeviceMovedNotification()
+                    sendDeviceMovedNotification(device);
+                    if (logger.isTraceEnabled()) {
+                        logger.trace("Device moved: attachment points {},"
+                                + "entities {}", device.attachmentPoints,
+                                device.entities);
+                    }
+                } else {
+                    if (logger.isTraceEnabled()) {
+                        logger.trace("Device attachment point updated: "
+                                + "attachment points {}," + "entities {}",
+                                device.attachmentPoints, device.entities);
+                    }
+                }
+            }
+            break;
+        }
+
+        if (deleteQueue != null) {
+            for (Long l : deleteQueue) {
+                Device dev = deviceMap.get(l);
+                this.deleteDevice(dev);
+            }
+        }
+
+        processUpdates(deviceUpdates);
+        // deviceSyncManager.storeDeviceThrottled(device);
+
+        return device;
+    }
+
+    protected boolean isEntityAllowed(Entity entity, IEntityClass entityClass) {
+        return true;
+    }
+
+    protected EnumSet<DeviceField> findChangedFields(Device device,
+            Entity newEntity) {
+        EnumSet<DeviceField> changedFields = EnumSet.of(DeviceField.IPV4,
+                DeviceField.VLAN, DeviceField.SWITCHPORT);
+
+        if (newEntity.getIpv4Address() == null)
+            changedFields.remove(DeviceField.IPV4);
+        if (newEntity.getVlan() == null)
+            changedFields.remove(DeviceField.VLAN);
+        if (newEntity.getPort() == null)
+            changedFields.remove(DeviceField.SWITCHPORT);
+
+        if (changedFields.size() == 0)
+            return changedFields;
+
+        for (Entity entity : device.getEntities()) {
+            if (newEntity.getIpv4Address() == null
+                    || (entity.getIpv4Address() != null && entity
+                            .getIpv4Address()
+                            .equals(newEntity.getIpv4Address())))
+                changedFields.remove(DeviceField.IPV4);
+            if (newEntity.getVlan() == null
+                    || (entity.getVlan() != null && entity.getVlan().equals(
+                            newEntity.getVlan())))
+                changedFields.remove(DeviceField.VLAN);
+            if (newEntity.getPort() == null
+                    || (entity.getPort() != null && entity.getPort().equals(
+                            newEntity.getPort())))
+                changedFields.remove(DeviceField.SWITCHPORT);
+        }
+
+        return changedFields;
+    }
+
+    /**
+     * Send update notifications to listeners
+     *
+     * @param updates
+     *            the updates to process.
+     */
+    protected void processUpdates(Queue<DeviceUpdate> updates) {
+        if (updates == null)
+            return;
+        DeviceUpdate update = null;
+        while (null != (update = updates.poll())) {
+            if (logger.isTraceEnabled()) {
+                logger.trace("Dispatching device update: {}", update);
+            }
+            // if (update.change == DeviceUpdate.Change.DELETE)
+            // deviceSyncManager.removeDevice(update.device);
+            // else
+            // deviceSyncManager.storeDevice(update.device);
+            List<IDeviceListener> listeners = deviceListeners
+                    .getOrderedListeners();
+            notifyListeners(listeners, update);
+        }
+    }
+
+    protected void notifyListeners(List<IDeviceListener> listeners,
+            DeviceUpdate update) {
+        if (listeners == null) {
+            return;
+        }
+        for (IDeviceListener listener : listeners) {
+            switch (update.change) {
+            case ADD:
+                listener.deviceAdded(update.device);
+                break;
+            case DELETE:
+                listener.deviceRemoved(update.device);
+                break;
+            case CHANGE:
+                for (DeviceField field : update.fieldsChanged) {
+                    switch (field) {
+                    case IPV4:
+                        listener.deviceIPV4AddrChanged(update.device);
+                        break;
+                    case SWITCHPORT:
+                        // listener.deviceMoved(update.device);
+                        break;
+                    case VLAN:
+                        listener.deviceVlanChanged(update.device);
+                        break;
+                    default:
+                        logger.debug("Unknown device field changed {}",
+                                update.fieldsChanged.toString());
+                        break;
+                    }
+                }
+                break;
+            }
+        }
+    }
+
+    /**
+     * Check if the entity e has all the keyFields set. Returns false if not
+     *
+     * @param e
+     *            entity to check
+     * @param keyFields
+     *            the key fields to check e against
+     * @return
+     */
+    protected boolean allKeyFieldsPresent(Entity e,
+            EnumSet<DeviceField> keyFields) {
+        for (DeviceField f : keyFields) {
+            switch (f) {
+            case MAC:
+                // MAC address is always present
+                break;
+            case IPV4:
+                if (e.getIpv4Address() == null)
+                    return false;
+                break;
+            case SWITCHPORT:
+                if (e.getPort() == null)
+                    return false;
+                break;
+            case VLAN:
+                // FIXME: vlan==null is ambiguous: it can mean: not present
+                // or untagged
+                // if (e.vlan == null) return false;
+                break;
+            default:
+                // we should never get here. unless somebody extended
+                // DeviceFields
+                throw new IllegalStateException();
+            }
+        }
+        return true;
+    }
+
+    private LinkedList<DeviceUpdate> updateUpdates(
+            LinkedList<DeviceUpdate> list, DeviceUpdate update) {
+        if (update == null)
+            return list;
+        if (list == null)
+            list = new LinkedList<DeviceUpdate>();
+        list.add(update);
+
+        return list;
+    }
+
+    /**
+     * Get the secondary index for a class. Will return null if the secondary
+     * index was created concurrently in another thread.
+     *
+     * @param clazz
+     *            the class for the index
+     * @return
+     */
+    private ClassState getClassState(IEntityClass clazz) {
+        ClassState classState = classStateMap.get(clazz.getName());
+        if (classState != null)
+            return classState;
+
+        classState = new ClassState(clazz);
+        ClassState r = classStateMap.putIfAbsent(clazz.getName(), classState);
+        if (r != null) {
+            // concurrent add
+            return r;
+        }
+        return classState;
+    }
+
+    /**
+     * Update both the primary and class indices for the provided device. If the
+     * update fails because of an concurrent update, will return false.
+     *
+     * @param device
+     *            the device to update
+     * @param deviceKey
+     *            the device key for the device
+     * @return true if the update succeeded, false otherwise.
+     */
+    private boolean updateIndices(Device device, Long deviceKey) {
+        if (!primaryIndex.updateIndex(device, deviceKey)) {
+            return false;
+        }
+        IEntityClass entityClass = device.getEntityClass();
+        ClassState classState = getClassState(entityClass);
+
+        if (classState.classIndex != null) {
+            if (!classState.classIndex.updateIndex(device, deviceKey))
+                return false;
+        }
+        return true;
+    }
+
+    /**
+     * Update the secondary indices for the given entity and associated entity
+     * classes
+     *
+     * @param entity
+     *            the entity to update
+     * @param entityClass
+     *            the entity class for the entity
+     * @param deviceKey
+     *            the device key to set up
+     */
+    private void updateSecondaryIndices(Entity entity,
+            IEntityClass entityClass, Long deviceKey) {
+        for (DeviceIndex index : secondaryIndexMap.values()) {
+            index.updateIndex(entity, deviceKey);
+        }
+        ClassState state = getClassState(entityClass);
+        for (DeviceIndex index : state.secondaryIndexMap.values()) {
+            index.updateIndex(entity, deviceKey);
+        }
+    }
+
+    /**
+     * Clean up expired entities/devices
+     */
+    protected void cleanupEntities() {
+        // debugCounters.updateCounter(CNT_CLEANUP_ENTITIES_RUNS);
+
+        Calendar c = Calendar.getInstance();
+        c.add(Calendar.MILLISECOND, -ENTITY_TIMEOUT);
+        Date cutoff = c.getTime();
+
+        ArrayList<Entity> toRemove = new ArrayList<Entity>();
+        ArrayList<Entity> toKeep = new ArrayList<Entity>();
+
+        Iterator<Device> diter = deviceMap.values().iterator();
+        LinkedList<DeviceUpdate> deviceUpdates = new LinkedList<DeviceUpdate>();
+
+        while (diter.hasNext()) {
+            Device d = diter.next();
+
+            while (true) {
+                deviceUpdates.clear();
+                toRemove.clear();
+                toKeep.clear();
+                for (Entity e : d.getEntities()) {
+                    if (e.getLastSeenTimestamp() != null
+                            && 0 > e.getLastSeenTimestamp().compareTo(cutoff)) {
+                        // individual entity needs to be removed
+                        toRemove.add(e);
+                    } else {
+                        toKeep.add(e);
+                    }
+                }
+                if (toRemove.size() == 0) {
+                    break;
+                }
+
+                // debugCounters.updateCounter(CNT_ENTITY_REMOVED_TIMEOUT);
+                for (Entity e : toRemove) {
+                    removeEntity(e, d.getEntityClass(), d.getDeviceKey(),
+                            toKeep);
+                }
+
+                if (toKeep.size() > 0) {
+                    Device newDevice = allocateDevice(d.getDeviceKey(),
+                            d.getDHCPClientName(), d.oldAPs,
+                            d.attachmentPoints, toKeep, d.getEntityClass());
+
+                    EnumSet<DeviceField> changedFields = EnumSet
+                            .noneOf(DeviceField.class);
+                    for (Entity e : toRemove) {
+                        changedFields.addAll(findChangedFields(newDevice, e));
+                    }
+                    DeviceUpdate update = null;
+                    if (changedFields.size() > 0) {
+                        update = new DeviceUpdate(d, CHANGE, changedFields);
+                    }
+
+                    if (!deviceMap.replace(newDevice.getDeviceKey(), d,
+                            newDevice)) {
+                        // concurrent modification; try again
+                        // need to use device that is the map now for the next
+                        // iteration
+                        d = deviceMap.get(d.getDeviceKey());
+                        if (null != d)
+                            continue;
+                    }
+                    if (update != null) {
+                        // need to count after all possibly continue stmts in
+                        // this branch
+                        // debugCounters.updateCounter(CNT_DEVICE_CHANGED);
+                        deviceUpdates.add(update);
+                    }
+                } else {
+                    DeviceUpdate update = new DeviceUpdate(d, DELETE, null);
+                    if (!deviceMap.remove(d.getDeviceKey(), d)) {
+                        // concurrent modification; try again
+                        // need to use device that is the map now for the next
+                        // iteration
+                        d = deviceMap.get(d.getDeviceKey());
+                        if (null != d)
+                            continue;
+                        // debugCounters.updateCounter(CNT_DEVICE_DELETED);
+                    }
+                    deviceUpdates.add(update);
+                }
+                processUpdates(deviceUpdates);
+                break;
+            }
+        }
+    }
+
+    protected void removeEntity(Entity removed, IEntityClass entityClass,
+            Long deviceKey, Collection<Entity> others) {
+        // Don't count in this method. This method CAN BE called to clean-up
+        // after concurrent device adds/updates and thus counting here
+        // is misleading
+        for (DeviceIndex index : secondaryIndexMap.values()) {
+            index.removeEntityIfNeeded(removed, deviceKey, others);
+        }
+        ClassState classState = getClassState(entityClass);
+        for (DeviceIndex index : classState.secondaryIndexMap.values()) {
+            index.removeEntityIfNeeded(removed, deviceKey, others);
+        }
+
+        primaryIndex.removeEntityIfNeeded(removed, deviceKey, others);
+
+        if (classState.classIndex != null) {
+            classState.classIndex.removeEntityIfNeeded(removed, deviceKey,
+                    others);
+        }
+    }
+
+    /**
+     * method to delete a given device, remove all entities first and then
+     * finally delete the device itself.
+     *
+     * @param device
+     */
+    protected void deleteDevice(Device device) {
+        // Don't count in this method. This method CAN BE called to clean-up
+        // after concurrent device adds/updates and thus counting here
+        // is misleading
+        ArrayList<Entity> emptyToKeep = new ArrayList<Entity>();
+        for (Entity entity : device.getEntities()) {
+            this.removeEntity(entity, device.getEntityClass(),
+                    device.getDeviceKey(), emptyToKeep);
+        }
+        if (!deviceMap.remove(device.getDeviceKey(), device)) {
+            if (logger.isDebugEnabled())
+                logger.debug("device map does not have this device -"
+                        + device.toString());
+        }
+    }
+
+    private EnumSet<DeviceField> getEntityKeys(Long macAddress, Short vlan,
+            Integer ipv4Address, NodeConnector port) {
+        // FIXME: vlan==null is a valid search. Need to handle this
+        // case correctly. Note that the code will still work correctly.
+        // But we might do a full device search instead of using an index.
+        EnumSet<DeviceField> keys = EnumSet.noneOf(DeviceField.class);
+        if (macAddress != null)
+            keys.add(DeviceField.MAC);
+        if (vlan != null)
+            keys.add(DeviceField.VLAN);
+        if (ipv4Address != null)
+            keys.add(DeviceField.IPV4);
+        if (port != null)
+            keys.add(DeviceField.SWITCHPORT);
+        return keys;
+    }
+
+    protected Iterator<Device> queryClassByEntity(IEntityClass clazz,
+            EnumSet<DeviceField> keyFields, Entity entity) {
+        ClassState classState = getClassState(clazz);
+        DeviceIndex index = classState.secondaryIndexMap.get(keyFields);
+        if (index == null)
+            return Collections.<Device> emptySet().iterator();
+        return new DeviceIndexInterator(this, index.queryByEntity(entity));
+    }
+
+    protected Device allocateDevice(Long deviceKey, Entity entity,
+            IEntityClass entityClass) {
+        return new Device(this, deviceKey, entity, entityClass);
+    }
+
+    // TODO: FIX THIS.
+    protected Device allocateDevice(Long deviceKey, String dhcpClientName,
+            List<AttachmentPoint> aps, List<AttachmentPoint> trueAPs,
+            Collection<Entity> entities, IEntityClass entityClass) {
+        return new Device(this, deviceKey, dhcpClientName, aps, trueAPs,
+                entities, entityClass);
+    }
+
+    protected Device allocateDevice(Device device, Entity entity,
+            int insertionpoint) {
+        return new Device(device, entity, insertionpoint);
+    }
+
+    // not used
+    protected Device allocateDevice(Device device, Set<Entity> entities) {
+        List<AttachmentPoint> newPossibleAPs = new ArrayList<AttachmentPoint>();
+        List<AttachmentPoint> newAPs = new ArrayList<AttachmentPoint>();
+        for (Entity entity : entities) {
+            if (entity.getPort() != null) {
+                AttachmentPoint aP = new AttachmentPoint(entity.getPort(), 0);
+                newPossibleAPs.add(aP);
+            }
+        }
+        if (device.attachmentPoints != null) {
+            for (AttachmentPoint oldAP : device.attachmentPoints) {
+                if (newPossibleAPs.contains(oldAP)) {
+                    newAPs.add(oldAP);
+                }
+            }
+        }
+        if (newAPs.isEmpty())
+            newAPs = null;
+        Device d = new Device(this, device.getDeviceKey(),
+                device.getDHCPClientName(), newAPs, null, entities,
+                device.getEntityClass());
+        d.updateAttachmentPoint();
+        return d;
+    }
+
+    // *********************
+    // ITopologyManagerAware
+    // *********************
+
+    @Override
+    public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
+        Iterator<Device> diter = deviceMap.values().iterator();
+
+        while (diter.hasNext()) {
+            Device d = diter.next();
+            if (d.updateAttachmentPoint()) {
+                if (logger.isDebugEnabled()) {
+                    logger.debug("Attachment point changed for device: {}", d);
+                }
+                sendDeviceMovedNotification(d);
+            }
+        }
+    }
+
+    @Override
+    public void edgeOverUtilized(Edge edge) {
+        // nothing to do
+    }
+
+    @Override
+    public void edgeUtilBackToNormal(Edge edge) {
+        // nothing to do
+    }
+
+    // *********************
+    // IEntityClassListener
+    // *********************
+
+    @Override
+    public void entityClassChanged(Set<String> entityClassNames) {
+        /*
+         * iterate through the devices, reclassify the devices that belong to
+         * these entity class names
+         */
+        Iterator<Device> diter = deviceMap.values().iterator();
+        while (diter.hasNext()) {
+            Device d = diter.next();
+            if (d.getEntityClass() == null
+                    || entityClassNames.contains(d.getEntityClass().getName()))
+                reclassifyDevice(d);
+        }
+    }
+
+    // *************
+    // Local methods
+    // *************
+    /**
+     * Send update notifications to listeners
+     *
+     * @param updates
+     *            the updates to process.
+     */
+    protected void sendDeviceMovedNotification(Device d) {
+        // debugCounters.updateCounter(CNT_DEVICE_MOVED);
+        // deviceSyncManager.storeDevice(d);
+        List<IDeviceListener> listeners = deviceListeners.getOrderedListeners();
+        if (listeners != null) {
+            for (IDeviceListener listener : listeners) {
+                listener.deviceMoved(d);
+            }
+        }
+    }
+
+    /**
+     * this method will reclassify and reconcile a device - possibilities are -
+     * create new device(s), remove entities from this device. If the device
+     * entity class did not change then it returns false else true.
+     *
+     * @param device
+     */
+    protected boolean reclassifyDevice(Device device) {
+        // first classify all entities of this device
+        if (device == null) {
+            logger.debug("In reclassify for null device");
+            return false;
+        }
+        boolean needToReclassify = false;
+        for (Entity entity : device.entities) {
+            IEntityClass entityClass = this.entityClassifier
+                    .classifyEntity(entity);
+            if (entityClass == null || device.getEntityClass() == null) {
+                needToReclassify = true;
+                break;
+            }
+            if (!entityClass.getName()
+                    .equals(device.getEntityClass().getName())) {
+                needToReclassify = true;
+                break;
+            }
+        }
+        if (needToReclassify == false) {
+            return false;
+        }
+
+        // debugCounters.updateCounter(CNT_DEVICE_RECLASSIFY_DELETE);
+        LinkedList<DeviceUpdate> deviceUpdates = new LinkedList<DeviceUpdate>();
+        // delete this device and then re-learn all the entities
+        this.deleteDevice(device);
+        deviceUpdates.add(new DeviceUpdate(device, DeviceUpdate.Change.DELETE,
+                null));
+        if (!deviceUpdates.isEmpty())
+            processUpdates(deviceUpdates);
+        for (Entity entity : device.entities) {
+            this.learnDeviceByEntity(entity);
+        }
+        return true;
+    }
+
+    /**
+     * For testing: sets the interval between writes of the same device to the
+     * device store.
+     *
+     * @param intervalMs
+     */
+    // void setSyncStoreWriteInterval(int intervalMs) {
+    // this.syncStoreWriteIntervalMs = intervalMs;
+    // }
+
+    /**
+     * For testing: sets the time between transition to MASTER and consolidate
+     * store
+     *
+     * @param intervalMs
+     */
+    // void setInitialSyncStoreConsolidateMs(int intervalMs) {
+    // this.initialSyncStoreConsolidateMs = intervalMs;
+    // }
+
+    private long toLong(byte[] address) {
+        long mac = 0;
+        for (int i = 0; i < 6; i++) {
+            long t = (address[i] & 0xffL) << ((5 - i) * 8);
+            mac |= t;
+        }
+        return mac;
+    }
+
+    /**
+     * Accepts an IPv4 address in a byte array and returns the corresponding
+     * 32-bit integer value.
+     *
+     * @param ipAddress
+     * @return
+     */
+    private static int toIPv4Address(byte[] ipAddress) {
+        int ip = 0;
+        for (int i = 0; i < 4; i++) {
+            int t = (ipAddress[i] & 0xff) << ((3 - i) * 8);
+            ip |= t;
+        }
+        return ip;
+    }
+
+    private void registerDeviceManagerDebugCounters() {
+        /*
+         * XXX Missing functionality if (debugCounters == null) {
+         * logger.error("Debug Counter Service not found."); debugCounters = new
+         * NullDebugCounter(); return; }
+         * debugCounters.registerCounter(CNT_INCOMING,
+         * "All incoming packets seen by this module",
+         * CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_RECONCILE_REQUEST,
+         * "Number of flows that have been received for reconciliation by " +
+         * "this module", CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_RECONCILE_NO_SOURCE,
+         * "Number of flow reconcile events that failed because no source " +
+         * "device could be identified", CounterType.WARN); // is this really a
+         * warning debugCounters.registerCounter(CNT_RECONCILE_NO_DEST,
+         * "Number of flow reconcile events that failed because no " +
+         * "destination device could be identified", CounterType.WARN); // is
+         * this really a warning
+         * debugCounters.registerCounter(CNT_BROADCAST_SOURCE,
+         * "Number of packetIns that were discarded because the source " +
+         * "MAC was broadcast or multicast", CounterType.WARN);
+         * debugCounters.registerCounter(CNT_NO_SOURCE,
+         * "Number of packetIns that were discarded because the " +
+         * "could not identify a source device. This can happen if a " +
+         * "packet is not allowed, appears on an illegal port, does not " +
+         * "have a valid address space, etc.", CounterType.WARN);
+         * debugCounters.registerCounter(CNT_NO_DEST,
+         * "Number of packetIns that did not have an associated " +
+         * "destination device. E.g., because the destination MAC is " +
+         * "broadcast/multicast or is not yet known to the controller.",
+         * CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_DHCP_CLIENT_NAME_SNOOPED,
+         * "Number of times a DHCP client name was snooped from a " +
+         * "packetIn.", CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_DEVICE_ON_INTERAL_PORT_NOT_LEARNED,
+         * "Number of times packetIn was received on an internal port and" +
+         * "no source device is known for the source MAC. The packetIn is " +
+         * "discarded.", CounterType.WARN);
+         * debugCounters.registerCounter(CNT_PACKET_NOT_ALLOWED,
+         * "Number of times a packetIn was not allowed due to spoofing " +
+         * "protection configuration.", CounterType.WARN); // is this really a
+         * warning? debugCounters.registerCounter(CNT_NEW_DEVICE,
+         * "Number of times a new device was learned",
+         * CounterType.ALWAYS_COUNT); debugCounters.registerCounter(
+         * CNT_PACKET_ON_INTERNAL_PORT_FOR_KNOWN_DEVICE,
+         * "Number of times a packetIn was received on an internal port " +
+         * "for a known device.", CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_NEW_ENTITY,
+         * "Number of times a new entity was learned for an existing device",
+         * CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_DEVICE_CHANGED,
+         * "Number of times device properties have changed",
+         * CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_DEVICE_MOVED,
+         * "Number of times devices have moved", CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_CLEANUP_ENTITIES_RUNS,
+         * "Number of times the entity cleanup task has been run",
+         * CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_ENTITY_REMOVED_TIMEOUT,
+         * "Number of times entities have been removed due to timeout " +
+         * "(entity has been inactive for " + ENTITY_TIMEOUT/1000 + "s)",
+         * CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_DEVICE_DELETED,
+         * "Number of devices that have been removed due to inactivity",
+         * CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_DEVICE_RECLASSIFY_DELETE,
+         * "Number of devices that required reclassification and have been " +
+         * "temporarily delete for reclassification", CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_DEVICE_STORED,
+         * "Number of device entries written or updated to the sync store",
+         * CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_DEVICE_STORE_THROTTLED,
+         * "Number of times a device update to the sync store was " +
+         * "requested but not performed because the same device entities " +
+         * "have recently been updated already", CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_DEVICE_REMOVED_FROM_STORE,
+         * "Number of devices that were removed from the sync store " +
+         * "because the local controller removed the device due to " +
+         * "inactivity", CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_SYNC_EXCEPTION,
+         * "Number of times an operation on the sync store resulted in " +
+         * "sync exception", CounterType.WARN); // it this an error?
+         * debugCounters.registerCounter(CNT_DEVICES_FROM_STORE,
+         * "Number of devices that were read from the sync store after " +
+         * "the local controller transitioned from SLAVE to MASTER",
+         * CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_CONSOLIDATE_STORE_RUNS,
+         * "Number of times the task to consolidate entries in the " +
+         * "store witch live known devices has been run",
+         * CounterType.ALWAYS_COUNT);
+         * debugCounters.registerCounter(CNT_CONSOLIDATE_STORE_DEVICES_REMOVED,
+         * "Number of times a device has been removed from the sync " +
+         * "store because no corresponding live device is known. " +
+         * "This indicates a remote controller still writing device " +
+         * "entries despite the local controller being MASTER or an " +
+         * "incosistent store update from the local controller.",
+         * CounterType.WARN);
+         * debugCounters.registerCounter(CNT_TRANSITION_TO_MASTER,
+         * "Number of times this controller has transitioned from SLAVE " +
+         * "to MASTER role. Will be 0 or 1.", CounterType.ALWAYS_COUNT);
+         */
+    }
+
+    @Override
+    public HostNodeConnector hostFind(InetAddress networkAddress) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public HostNodeConnector hostQuery(InetAddress networkAddress) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Future<HostNodeConnector> discoverHost(InetAddress networkAddress) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Set<HostNodeConnector> getAllHosts() {
+        Collection<Device> devices = Collections
+                .unmodifiableCollection(deviceMap.values());
+        Iterator<Device> i = devices.iterator();
+        Set<HostNodeConnector> nc = new HashSet<HostNodeConnector>();
+        while (i.hasNext()) {
+            Device device = i.next();
+            nc.add(device.toHostNodeConnector());
+        }
+        return nc;
+    }
+
+    @Override
+    public Set<HostNodeConnector> getActiveStaticHosts() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Set<HostNodeConnector> getInactiveStaticHosts() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Status addStaticHost(String networkAddress, String dataLayerAddress,
+            NodeConnector nc, String vlan) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Status removeStaticHost(String networkAddress) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    /**
+     * For testing: consolidate the store NOW
+     */
+    // void scheduleConsolidateStoreNow() {
+    // this.storeConsolidateTask.reschedule(0, TimeUnit.MILLISECONDS);
+    // }
+
+    // private class DeviceSyncManager {
+    // // maps (opaque) deviceKey to the time in System.nanoTime() when we
+    // // last wrote the device to the sync store
+    // private ConcurrentMap<Long, Long> lastWriteTimes =
+    // new ConcurrentHashMap<Long, Long>();
+    //
+    // /**
+    // * Write the given device to storage if we are MASTER.
+    // * Use this method if the device has significantly changed (e.g.,
+    // * new AP, new IP, entities removed).
+    // * @param d the device to store
+    // */
+    // public void storeDevice(Device d) {
+    // if (!isMaster)
+    // return;
+    // if (d == null)
+    // return;
+    // long now = System.nanoTime();
+    // writeUpdatedDeviceToStorage(d);
+    // lastWriteTimes.put(d.getDeviceKey(), now);
+    // }
+    //
+    // /**
+    // * Write the given device to storage if we are MASTER and if the
+    // * last write for the device was more than this.syncStoreIntervalNs
+    // * time ago.
+    // * Use this method to updated last active times in the store.
+    // * @param d the device to store
+    // */
+    // public void storeDeviceThrottled(Device d) {
+    // long intervalNs = syncStoreWriteIntervalMs*1000L*1000L;
+    // if (!isMaster)
+    // return;
+    // if (d == null)
+    // return;
+    // long now = System.nanoTime();
+    // Long last = lastWriteTimes.get(d.getDeviceKey());
+    // if (last == null ||
+    // now - last > intervalNs) {
+    // writeUpdatedDeviceToStorage(d);
+    // lastWriteTimes.put(d.getDeviceKey(), now);
+    // } else {
+    // debugCounters.updateCounter(CNT_DEVICE_STORE_THROTTLED);
+    // }
+    // }
+    //
+    // /**
+    // * Remove the given device from the store. If only some entities have
+    // * been removed the updated device should be written using
+    // * {@link #storeDevice(Device)}
+    // * @param d
+    // */
+    // public void removeDevice(Device d) {
+    // if (!isMaster)
+    // return;
+    // // FIXME: could we have a problem with concurrent put to the
+    // // hashMap? I.e., we write a stale entry to the map after the
+    // // delete and now are left with an entry we'll never clean up
+    // lastWriteTimes.remove(d.getDeviceKey());
+    // try {
+    // // TODO: should probably do versioned delete. OTOH, even
+    // // if we accidentally delete, we'll write it again after
+    // // the next entity ....
+    // debugCounters.updateCounter(CNT_DEVICE_REMOVED_FROM_STORE);
+    // storeClient.delete(DeviceSyncRepresentation.computeKey(d));
+    // } catch(ObsoleteVersionException e) {
+    // // FIXME
+    // } catch (SyncException e) {
+    // debugCounters.updateCounter(CNT_SYNC_EXCEPTION);
+    // logger.error("Could not remove device " + d + " from store", e);
+    // }
+    // }
+    //
+    // /**
+    // * Remove the given Versioned device from the store. If the device
+    // * was locally modified ignore the delete request.
+    // * @param syncedDeviceKey
+    // */
+    // private void removeDevice(Versioned<DeviceSyncRepresentation> dev) {
+    // try {
+    // debugCounters.updateCounter(CNT_DEVICE_REMOVED_FROM_STORE);
+    // storeClient.delete(dev.getValue().getKey(),
+    // dev.getVersion());
+    // } catch(ObsoleteVersionException e) {
+    // // Key was locally modified by another thread.
+    // // Do not delete and ignore.
+    // } catch(SyncException e) {
+    // debugCounters.updateCounter(CNT_SYNC_EXCEPTION);
+    // logger.error("Failed to remove device entry for " +
+    // dev.toString() + " from store.", e);
+    // }
+    // }
+    //
+    // /**
+    // * Synchronously transition from SLAVE to MASTER. By iterating through
+    // * the store and learning all devices from the store
+    // */
+    // private void goToMaster() {
+    // if (logger.isDebugEnabled()) {
+    // logger.debug("Transitioning to MASTER role");
+    // }
+    // debugCounters.updateCounter(CNT_TRANSITION_TO_MASTER);
+    // IClosableIterator<Map.Entry<String,Versioned<DeviceSyncRepresentation>>>
+    // iter = null;
+    // try {
+    // iter = storeClient.entries();
+    // } catch (SyncException e) {
+    // debugCounters.updateCounter(CNT_SYNC_EXCEPTION);
+    // logger.error("Failed to read devices from sync store", e);
+    // return;
+    // }
+    // try {
+    // while(iter.hasNext()) {
+    // Versioned<DeviceSyncRepresentation> versionedDevice =
+    // iter.next().getValue();
+    // DeviceSyncRepresentation storedDevice =
+    // versionedDevice.getValue();
+    // if (storedDevice == null)
+    // continue;
+    // debugCounters.updateCounter(CNT_DEVICES_FROM_STORE);
+    // for(SyncEntity se: storedDevice.getEntities()) {
+    // learnDeviceByEntity(se.asEntity());
+    // }
+    // }
+    // } finally {
+    // if (iter != null)
+    // iter.close();
+    // }
+    // storeConsolidateTask.reschedule(initialSyncStoreConsolidateMs,
+    // TimeUnit.MILLISECONDS);
+    // }
+    //
+    // /**
+    // * Actually perform the write of the device to the store
+    // * FIXME: concurrent modification behavior
+    // * @param device The device to write
+    // */
+    // private void writeUpdatedDeviceToStorage(Device device) {
+    // try {
+    // debugCounters.updateCounter(CNT_DEVICE_STORED);
+    // // FIXME: use a versioned put
+    // DeviceSyncRepresentation storeDevice =
+    // new DeviceSyncRepresentation(device);
+    // storeClient.put(storeDevice.getKey(), storeDevice);
+    // } catch (ObsoleteVersionException e) {
+    // // FIXME: what's the right behavior here. Can the store client
+    // // even throw this error?
+    // } catch (SyncException e) {
+    // debugCounters.updateCounter(CNT_SYNC_EXCEPTION);
+    // logger.error("Could not write device " + device +
+    // " to sync store:", e);
+    // }
+    // }
+    //
+    // /**
+    // * Iterate through all entries in the sync store. For each device
+    // * in the store check if any stored entity matches a live device. If
+    // * no entities match a live device we remove the entry from the store.
+    // *
+    // * Note: we do not check if all devices known to device manager are
+    // * in the store. We rely on regular packetIns for that.
+    // * Note: it's possible that multiple entries in the store map to the
+    // * same device. We don't check or handle this case.
+    // *
+    // * We need to perform this check after a SLAVE->MASTER transition to
+    // * get rid of all entries the old master might have written to the
+    // * store after we took over. We also run it regularly in MASTER
+    // * state to ensure we don't have stale entries in the store
+    // */
+    // private void consolidateStore() {
+    // if (!isMaster)
+    // return;
+    // debugCounters.updateCounter(CNT_CONSOLIDATE_STORE_RUNS);
+    // if (logger.isDebugEnabled()) {
+    // logger.debug("Running consolidateStore.");
+    // }
+    // IClosableIterator<Map.Entry<String,Versioned<DeviceSyncRepresentation>>>
+    // iter = null;
+    // try {
+    // iter = storeClient.entries();
+    // } catch (SyncException e) {
+    // debugCounters.updateCounter(CNT_SYNC_EXCEPTION);
+    // logger.error("Failed to read devices from sync store", e);
+    // return;
+    // }
+    // try {
+    // while(iter.hasNext()) {
+    // boolean found = false;
+    // Versioned<DeviceSyncRepresentation> versionedDevice =
+    // iter.next().getValue();
+    // DeviceSyncRepresentation storedDevice =
+    // versionedDevice.getValue();
+    // if (storedDevice == null)
+    // continue;
+    // for(SyncEntity se: storedDevice.getEntities()) {
+    // try {
+    // // Do we have a device for this entity??
+    // IDevice d = findDevice(se.macAddress, se.vlan,
+    // se.ipv4Address,
+    // se.switchDPID,
+    // se.switchPort);
+    // if (d != null) {
+    // found = true;
+    // break;
+    // }
+    // } catch (IllegalArgumentException e) {
+    // // not all key fields provided. Skip entity
+    // }
+    // }
+    // if (!found) {
+    // // We currently DO NOT have a live device that
+    // // matches the current device from the store.
+    // // Delete device from store.
+    // if (logger.isDebugEnabled()) {
+    // logger.debug("Removing device {} from store. No "
+    // + "corresponding live device",
+    // storedDevice.getKey());
+    // }
+    // debugCounters.updateCounter(CNT_CONSOLIDATE_STORE_DEVICES_REMOVED);
+    // removeDevice(versionedDevice);
+    // }
+    // }
+    // } finally {
+    // if (iter != null)
+    // iter.close();
+    // }
+    // }
+    // }
+    //
+    //
+    // /**
+    // * For testing. Sets the syncService. Only call after init but before
+    // * startUp. Used by MockDeviceManager
+    // * @param syncService
+    // */
+    // protected void setSyncServiceIfNotSet(ISyncService syncService) {
+    // if (this.syncService == null)
+    // this.syncService = syncService;
+    // }
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceMultiIndex.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceMultiIndex.java
new file mode 100644 (file)
index 0000000..85cb094
--- /dev/null
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+import org.opendaylight.controller.sal.utils.IterableIterator;
+
+/**
+ * An index that maps key fields of an entity to device keys, with multiple
+ * device keys allowed per entity
+ */
+public class DeviceMultiIndex extends DeviceIndex {
+    /**
+     * The index
+     */
+    private ConcurrentHashMap<IndexedEntity, Collection<Long>> index;
+
+    /**
+     * @param keyFields
+     */
+    public DeviceMultiIndex(EnumSet<DeviceField> keyFields) {
+        super(keyFields);
+        index = new ConcurrentHashMap<IndexedEntity, Collection<Long>>();
+    }
+
+    // ***********
+    // DeviceIndex
+    // ***********
+
+    @Override
+    public Iterator<Long> queryByEntity(Entity entity) {
+        IndexedEntity ie = new IndexedEntity(keyFields, entity);
+        Collection<Long> devices = index.get(ie);
+        if (devices != null)
+            return devices.iterator();
+
+        return Collections.<Long> emptySet().iterator();
+    }
+
+    @Override
+    public Iterator<Long> getAll() {
+        Iterator<Collection<Long>> iter = index.values().iterator();
+        return new IterableIterator<Long>(iter);
+    }
+
+    @Override
+    public boolean updateIndex(Device device, Long deviceKey) {
+        for (Entity e : device.entities) {
+            updateIndex(e, deviceKey);
+        }
+        return true;
+    }
+
+    @Override
+    public void updateIndex(Entity entity, Long deviceKey) {
+        Collection<Long> devices = null;
+
+        IndexedEntity ie = new IndexedEntity(keyFields, entity);
+        if (!ie.hasNonNullKeys())
+            return;
+
+        devices = index.get(ie);
+        if (devices == null) {
+            Map<Long, Boolean> chm = new ConcurrentHashMap<Long, Boolean>();
+            devices = Collections.newSetFromMap(chm);
+            Collection<Long> r = index.putIfAbsent(ie, devices);
+            if (r != null)
+                devices = r;
+        }
+
+        devices.add(deviceKey);
+    }
+
+    @Override
+    public void removeEntity(Entity entity) {
+        IndexedEntity ie = new IndexedEntity(keyFields, entity);
+        index.remove(ie);
+    }
+
+    @Override
+    public void removeEntity(Entity entity, Long deviceKey) {
+        IndexedEntity ie = new IndexedEntity(keyFields, entity);
+        Collection<Long> devices = index.get(ie);
+        if (devices != null)
+            devices.remove(deviceKey);
+    }
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndex.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndex.java
new file mode 100644 (file)
index 0000000..6ca0556
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.Iterator;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDeviceService;
+
+/**
+ * An index that maps key fields of an entity uniquely to a device key
+ */
+public class DeviceUniqueIndex extends DeviceIndex {
+    /**
+     * The index
+     */
+    private final ConcurrentHashMap<IndexedEntity, Long> index;
+
+    /**
+     * Construct a new device index using the provided key fields
+     *
+     * @param keyFields
+     *            the key fields to use
+     */
+    public DeviceUniqueIndex(EnumSet<IDeviceService.DeviceField> keyFields) {
+        super(keyFields);
+        index = new ConcurrentHashMap<IndexedEntity, Long>();
+    }
+
+    // ***********
+    // DeviceIndex
+    // ***********
+
+    @Override
+    public Iterator<Long> queryByEntity(Entity entity) {
+        final Long deviceKey = findByEntity(entity);
+        if (deviceKey != null)
+            return Collections.<Long> singleton(deviceKey).iterator();
+
+        return Collections.<Long> emptySet().iterator();
+    }
+
+    @Override
+    public Iterator<Long> getAll() {
+        return index.values().iterator();
+    }
+
+    @Override
+    public boolean updateIndex(Device device, Long deviceKey) {
+        for (Entity e : device.entities) {
+            IndexedEntity ie = new IndexedEntity(keyFields, e);
+            if (!ie.hasNonNullKeys())
+                continue;
+
+            Long ret = index.putIfAbsent(ie, deviceKey);
+            if (ret != null && !ret.equals(deviceKey)) {
+                // If the return value is non-null, then fail the insert
+                // (this implies that a device using this entity has
+                // already been created in another thread).
+                return false;
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public void updateIndex(Entity entity, Long deviceKey) {
+        IndexedEntity ie = new IndexedEntity(keyFields, entity);
+        if (!ie.hasNonNullKeys())
+            return;
+        index.put(ie, deviceKey);
+    }
+
+    @Override
+    public void removeEntity(Entity entity) {
+        IndexedEntity ie = new IndexedEntity(keyFields, entity);
+        index.remove(ie);
+    }
+
+    @Override
+    public void removeEntity(Entity entity, Long deviceKey) {
+        IndexedEntity ie = new IndexedEntity(keyFields, entity);
+        index.remove(ie, deviceKey);
+    }
+
+    // **************
+    // Public Methods
+    // **************
+
+    /**
+     * Look up a {@link Device} based on the provided {@link Entity}.
+     *
+     * @param entity
+     *            the entity to search for
+     * @return The key for the {@link Device} object if found
+     */
+    public Long findByEntity(Entity entity) {
+        IndexedEntity ie = new IndexedEntity(keyFields, entity);
+        Long deviceKey = index.get(ie);
+        if (deviceKey == null)
+            return null;
+        return deviceKey;
+    }
+
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/IndexedEntity.java b/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/IndexedEntity.java
new file mode 100644 (file)
index 0000000..fa9fad8
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) 2013 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import java.util.EnumSet;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDeviceService;
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This is a thin wrapper around {@link Entity} that allows overriding the
+ * behavior of {@link Object#hashCode()} and {@link Object#equals(Object)} so
+ * that the keying behavior in a hash map can be changed dynamically
+ *
+ * @author readams
+ */
+public class IndexedEntity {
+    protected EnumSet<DeviceField> keyFields;
+    protected Entity entity;
+    private int hashCode = 0;
+    protected static Logger logger = LoggerFactory
+            .getLogger(IndexedEntity.class);
+
+    /**
+     * Create a new {@link IndexedEntity} for the given {@link Entity} using the
+     * provided key fields.
+     *
+     * @param keyFields
+     *            The key fields that will be used for computing
+     *            {@link IndexedEntity#hashCode()} and
+     *            {@link IndexedEntity#equals(Object)}
+     * @param entity
+     *            the entity to wrap
+     */
+    public IndexedEntity(EnumSet<DeviceField> keyFields, Entity entity) {
+        super();
+        this.keyFields = keyFields;
+        this.entity = entity;
+    }
+
+    /**
+     * Check whether this entity has non-null values in any of its key fields
+     *
+     * @return true if any key fields have a non-null value
+     */
+    public boolean hasNonNullKeys() {
+        for (DeviceField f : keyFields) {
+            switch (f) {
+            case MAC:
+                return true;
+            case IPV4:
+                if (entity.getIpv4Address() != null)
+                    return true;
+                break;
+            case SWITCHPORT:
+                if (entity.getPort() != null)
+                    return true;
+                break;
+            case VLAN:
+                if (entity.getVlan() != null)
+                    return true;
+                break;
+            }
+        }
+        return false;
+    }
+
+    @Override
+    public int hashCode() {
+
+        if (hashCode != 0) {
+            return hashCode;
+        }
+
+        final int prime = 31;
+        hashCode = 1;
+        for (DeviceField f : keyFields) {
+            switch (f) {
+            case MAC:
+                hashCode = prime
+                        * hashCode
+                        + (int) (entity.getMacAddress() ^ (entity
+                                .getMacAddress() >>> 32));
+                break;
+            case IPV4:
+                hashCode = prime
+                        * hashCode
+                        + ((entity.getIpv4Address() == null) ? 0 : entity
+                                .getIpv4Address().hashCode());
+                break;
+            case SWITCHPORT:
+                hashCode = prime
+                        * hashCode
+                        + ((entity.getPort() == null) ? 0 : entity.getPort()
+                                .hashCode());
+                break;
+            case VLAN:
+                hashCode = prime
+                        * hashCode
+                        + ((entity.getVlan() == null) ? 0 : entity.getVlan()
+                                .hashCode());
+                break;
+            }
+        }
+        return hashCode;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        IndexedEntity other = (IndexedEntity) obj;
+
+        if (!keyFields.equals(other.keyFields))
+            return false;
+
+        for (IDeviceService.DeviceField f : keyFields) {
+            switch (f) {
+            case MAC:
+                if (entity.getMacAddress() != other.entity.getMacAddress())
+                    return false;
+                break;
+            case IPV4:
+                if (entity.getIpv4Address() == null) {
+                    if (other.entity.getIpv4Address() != null)
+                        return false;
+                } else if (!entity.getIpv4Address().equals(
+                        other.entity.getIpv4Address()))
+                    return false;
+                break;
+            case SWITCHPORT:
+                if (entity.getPort() == null) {
+                    if (other.entity.getPort() != null)
+                        return false;
+                } else if (!entity.getPort().equals(other.entity.getPort()))
+                    return false;
+                break;
+            case VLAN:
+                if (entity.getVlan() == null) {
+                    if (other.entity.getVlan() != null)
+                        return false;
+                } else if (!entity.getVlan().equals(other.entity.getVlan()))
+                    return false;
+                break;
+            }
+        }
+
+        return true;
+    }
+
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImplTest.java b/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImplTest.java
new file mode 100644 (file)
index 0000000..3bed3a5
--- /dev/null
@@ -0,0 +1,2644 @@
+package org.opendaylight.controller.hosttracker.internal;
+
+///*
+// * Copyright (c) 2011,2013 Big Switch Networks, Inc.
+// *
+// * Licensed under the Eclipse Public License, Version 1.0 (the
+// * "License"); you may not use this file except in compliance with the
+// * License. You may obtain a copy of the License at
+// *
+// *      http://www.eclipse.org/legal/epl-v10.html
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+// * implied. See the License for the specific language governing
+// * permissions and limitations under the License.
+// *
+// * This file incorporates work covered by the following copyright and
+// * permission notice:
+// *
+// *    Originally created by David Erickson, Stanford University
+// *
+// *    Licensed under the Apache License, Version 2.0 (the "License");
+// *    you may not use this file except in compliance with the
+// *    License. You may obtain a copy of the License at
+// *
+// *         http://www.apache.org/licenses/LICENSE-2.0
+// *
+// *    Unless required by applicable law or agreed to in writing,
+// *    software distributed under the License is distributed on an "AS
+// *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+// *    express or implied. See the License for the specific language
+// *    governing permissions and limitations under the License.
+// */
+//
+//package org.opendaylight.controller.hosttracker.internal;
+//
+//import static org.easymock.EasyMock.anyLong;
+//import static org.easymock.EasyMock.anyObject;
+//import static org.easymock.EasyMock.anyShort;
+//import static org.easymock.EasyMock.createMock;
+//import static org.easymock.EasyMock.createNiceMock;
+//import static org.easymock.EasyMock.eq;
+//import static org.easymock.EasyMock.expect;
+//import static org.easymock.EasyMock.expectLastCall;
+//import static org.easymock.EasyMock.isA;
+//import static org.easymock.EasyMock.or;
+//import static org.easymock.EasyMock.replay;
+//import static org.easymock.EasyMock.reset;
+//import static org.easymock.EasyMock.verify;
+//import static org.junit.Assert.*;
+//
+//import java.util.ArrayList;
+//import java.util.Arrays;
+//import java.util.Calendar;
+//import java.util.Collection;
+//import java.util.Collections;
+//import java.util.Date;
+//import java.util.EnumSet;
+//import java.util.HashMap;
+//import java.util.HashSet;
+//import java.util.Iterator;
+//import java.util.List;
+//import java.util.Map;
+//import java.util.Map.Entry;
+//import java.util.Set;
+//import java.util.concurrent.ConcurrentHashMap;
+//
+//import org.junit.Before;
+//import org.junit.Test;
+//
+//import org.slf4j.Logger;
+//import org.slf4j.LoggerFactory;
+//
+//public class DeviceManagerImplTest {
+//
+//    protected static Logger logger =
+//            LoggerFactory.getLogger(DeviceManagerImplTest.class);
+//
+//    protected OFPacketIn packetIn_1, packetIn_2, packetIn_3;
+//    protected IPacket testARPReplyPacket_1, testARPReplyPacket_2,
+//    testARPReplyPacket_3;
+//    protected IPacket testARPReqPacket_1, testARPReqPacket_2;
+//    protected byte[] testARPReplyPacket_1_Srld, testARPReplyPacket_2_Srld;
+//    private MockSyncService syncService;
+//    private IStoreClient<String, DeviceSyncRepresentation> storeClient;
+//
+//    DeviceManagerImpl deviceManager;
+//    MemoryStorageSource storageSource;
+//    FlowReconcileManager flowReconcileMgr;
+//
+//    private IOFSwitch makeSwitchMock(long id) {
+//        IOFSwitch mockSwitch = createMock(IOFSwitch.class);
+//        ImmutablePort port = ImmutablePort.create("p1", (short)1);
+//        expect(mockSwitch.getId()).andReturn(id).anyTimes();
+//        expect(mockSwitch.getStringId())
+//                .andReturn(HexString.toHexString(id, 6)).anyTimes();
+//        expect(mockSwitch.getPort(anyShort()))
+//                .andReturn(port).anyTimes();
+//        return mockSwitch;
+//    }
+//
+//    /*
+//     * return an EasyMock ITopologyService that's setup so that it will
+//     * answer all questions a device or device manager will ask
+//     * (isAttachmentPointPort, etc.) in a way so that every port is a
+//     * non-BD, attachment point port.
+//     * The returned mock is still in record mode
+//     */
+//    private ITopologyService makeMockTopologyAllPortsAp() {
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        mockTopology.isAttachmentPointPort(anyLong(), anyShort());
+//        expectLastCall().andReturn(true).anyTimes();
+//        mockTopology.getL2DomainId(anyLong());
+//        expectLastCall().andReturn(1L).anyTimes();
+//        mockTopology.isBroadcastDomainPort(anyLong(), anyShort());
+//        expectLastCall().andReturn(false).anyTimes();
+//        mockTopology.isConsistent(anyLong(), anyShort(), anyLong(), anyShort());
+//        expectLastCall().andReturn(false).anyTimes();
+//        mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(),
+//                                             anyLong(), anyShort());
+//        expectLastCall().andReturn(false).anyTimes();
+//        return mockTopology;
+//    }
+//
+//    @Override
+//    @Before
+//    public void setUp() throws Exception {
+//        doSetUp(Role.MASTER);
+//    }
+//
+//    public void doSetUp(Role initialRole) throws Exception {
+//        super.setUp();
+//
+//        this.syncService = new MockSyncService();
+//
+//        FloodlightModuleContext fmc = new FloodlightModuleContext();
+//        RestApiServer restApi = new RestApiServer();
+//        MockThreadPoolService tp = new MockThreadPoolService();
+//        ITopologyService topology = createMock(ITopologyService.class);
+//        fmc.addService(IThreadPoolService.class, tp);
+//        mockFloodlightProvider = getMockFloodlightProvider();
+//        mockFloodlightProvider.setRole(initialRole, "");
+//
+//        deviceManager = new DeviceManagerImpl();
+//        flowReconcileMgr = new FlowReconcileManager();
+//        DefaultEntityClassifier entityClassifier = new DefaultEntityClassifier();
+//        fmc.addService(IDeviceService.class, deviceManager);
+//        storageSource = new MemoryStorageSource();
+//        fmc.addService(IStorageSourceService.class, storageSource);
+//        fmc.addService(IFloodlightProviderService.class, mockFloodlightProvider);
+//        fmc.addService(IRestApiService.class, restApi);
+//        fmc.addService(IFlowReconcileService.class, flowReconcileMgr);
+//        fmc.addService(IEntityClassifierService.class, entityClassifier);
+//        fmc.addService(ITopologyService.class, topology);
+//        fmc.addService(ISyncService.class, syncService);
+//        tp.init(fmc);
+//        restApi.init(fmc);
+//        storageSource.init(fmc);
+//        deviceManager.init(fmc);
+//        flowReconcileMgr.init(fmc);
+//        entityClassifier.init(fmc);
+//        syncService.init(fmc);
+//        storageSource.startUp(fmc);
+//        deviceManager.startUp(fmc);
+//        flowReconcileMgr.startUp(fmc);
+//        tp.startUp(fmc);
+//        entityClassifier.startUp(fmc);
+//        syncService.startUp(fmc);
+//
+//        this.storeClient =
+//                this.syncService.getStoreClient(DeviceManagerImpl.DEVICE_SYNC_STORE_NAME,
+//                            String.class, DeviceSyncRepresentation.class);
+//
+//        reset(topology);
+//        topology.addListener(deviceManager);
+//        expectLastCall().anyTimes();
+//        replay(topology);
+//
+//        IOFSwitch mockSwitch1 = makeSwitchMock(1L);
+//        IOFSwitch mockSwitch10 = makeSwitchMock(10L);
+//        IOFSwitch mockSwitch5 = makeSwitchMock(5L);
+//        IOFSwitch mockSwitch50 = makeSwitchMock(50L);
+//        Map<Long, IOFSwitch> switches = new HashMap<Long,IOFSwitch>();
+//        switches.put(1L, mockSwitch1);
+//        switches.put(10L, mockSwitch10);
+//        switches.put(5L, mockSwitch5);
+//        switches.put(50L, mockSwitch50);
+//        mockFloodlightProvider.setSwitches(switches);
+//
+//        replay(mockSwitch1, mockSwitch5, mockSwitch10, mockSwitch50);
+//
+//        // Build our test packet
+//        this.testARPReplyPacket_1 = new Ethernet()
+//        .setSourceMACAddress("00:44:33:22:11:01")
+//        .setDestinationMACAddress("00:11:22:33:44:55")
+//        .setEtherType(Ethernet.TYPE_ARP)
+//        .setVlanID((short)5)
+//        .setPayload(
+//                    new ARP()
+//                    .setHardwareType(ARP.HW_TYPE_ETHERNET)
+//                    .setProtocolType(ARP.PROTO_TYPE_IP)
+//                    .setHardwareAddressLength((byte) 6)
+//                    .setProtocolAddressLength((byte) 4)
+//                    .setOpCode(ARP.OP_REPLY)
+//                    .setSenderHardwareAddress(Ethernet.toMACAddress("00:44:33:22:11:01"))
+//                    .setSenderProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.1"))
+//                    .setTargetHardwareAddress(Ethernet.toMACAddress("00:11:22:33:44:55"))
+//                    .setTargetProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.2")));
+//        this.testARPReplyPacket_1_Srld = testARPReplyPacket_1.serialize();
+//
+//        // Another test packet with a different source IP
+//        this.testARPReplyPacket_2 = new Ethernet()
+//        .setSourceMACAddress("00:99:88:77:66:55")
+//        .setDestinationMACAddress("00:11:22:33:44:55")
+//        .setEtherType(Ethernet.TYPE_ARP)
+//        .setVlanID((short)5)
+//        .setPayload(
+//                    new ARP()
+//                    .setHardwareType(ARP.HW_TYPE_ETHERNET)
+//                    .setProtocolType(ARP.PROTO_TYPE_IP)
+//                    .setHardwareAddressLength((byte) 6)
+//                    .setProtocolAddressLength((byte) 4)
+//                    .setOpCode(ARP.OP_REPLY)
+//                    .setSenderHardwareAddress(Ethernet.toMACAddress("00:44:33:22:11:01"))
+//                    .setSenderProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.1"))
+//                    .setTargetHardwareAddress(Ethernet.toMACAddress("00:11:22:33:44:55"))
+//                    .setTargetProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.2")));
+//        this.testARPReplyPacket_2_Srld = testARPReplyPacket_2.serialize();
+//
+//        // Build the PacketIn
+//        this.packetIn_1 = ((OFPacketIn) mockFloodlightProvider.
+//                getOFMessageFactory().getMessage(OFType.PACKET_IN))
+//                .setBufferId(-1)
+//                .setInPort((short) 1)
+//                .setPacketData(this.testARPReplyPacket_1_Srld)
+//                .setReason(OFPacketInReason.NO_MATCH)
+//                .setTotalLength((short) this.testARPReplyPacket_1_Srld.length);
+//
+//        // Build the PacketIn
+//        this.packetIn_2 = ((OFPacketIn) mockFloodlightProvider.
+//                getOFMessageFactory().getMessage(OFType.PACKET_IN))
+//                .setBufferId(-1)
+//                .setInPort((short) 1)
+//                .setPacketData(this.testARPReplyPacket_2_Srld)
+//                .setReason(OFPacketInReason.NO_MATCH)
+//                .setTotalLength((short) this.testARPReplyPacket_2_Srld.length);
+//    }
+//
+//
+//
+//
+//
+//    @Test
+//    public void testLastSeen() throws Exception {
+//        Calendar c = Calendar.getInstance();
+//        Date d1 = c.getTime();
+//        Entity entity1 = new Entity(1L, null, null, null, null, d1);
+//        c.add(Calendar.SECOND, 1);
+//        Entity entity2 = new Entity(1L, null, 1, null, null, c.getTime());
+//
+//        IDevice d = deviceManager.learnDeviceByEntity(entity2);
+//        assertEquals(c.getTime(), d.getLastSeen());
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//        assertEquals(c.getTime(), d.getLastSeen());
+//
+//        deviceManager.startUp(null);
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//        assertEquals(d1, d.getLastSeen());
+//        d = deviceManager.learnDeviceByEntity(entity2);
+//        assertEquals(c.getTime(), d.getLastSeen());
+//    }
+//
+//    @Test
+//    public void testEntityLearning() throws Exception {
+//        IDeviceListener mockListener =
+//                createMock(IDeviceListener.class);
+//        expect(mockListener.getName()).andReturn("mockListener").atLeastOnce();
+//        expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//        expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//
+//        replay(mockListener);
+//        deviceManager.addListener(mockListener);
+//        verify(mockListener);
+//        reset(mockListener);
+//        deviceManager.entityClassifier= new MockEntityClassifier();
+//        deviceManager.startUp(null);
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        expect(mockTopology.getL2DomainId(anyLong())).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(anyLong(), anyShort())).
+//        andReturn(false).anyTimes();
+//
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).andReturn(true).anyTimes();
+//        expect(mockTopology.isConsistent(10L, (short)1, 10L, (short)1)).
+//        andReturn(true).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)1, 1L, (short)1)).
+//        andReturn(true).anyTimes();
+//        expect(mockTopology.isConsistent(50L, (short)3, 50L, (short)3)).
+//        andReturn(true).anyTimes();
+//
+//        Date topologyUpdateTime = new Date();
+//        expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime).
+//        anyTimes();
+//
+//        deviceManager.topology = mockTopology;
+//
+//        Entity entity1 = new Entity(1L, null, null, 1L, 1, new Date());
+//        Entity entity2 = new Entity(1L, null, null, 10L, 1, new Date());
+//        Entity entity3 = new Entity(1L, null, 1, 10L, 1, new Date());
+//        Entity entity4 = new Entity(1L, null, 1, 1L, 1, new Date());
+//        Entity entity5 = new Entity(2L, (short)4, 1, 5L, 2, new Date());
+//        Entity entity6 = new Entity(2L, (short)4, 1, 50L, 3, new Date());
+//        Entity entity7 = new Entity(2L, (short)4, 2, 50L, 3, new Date());
+//
+//        mockListener.deviceAdded(isA(IDevice.class));
+//        replay(mockListener, mockTopology);
+//
+//        Device d1 = deviceManager.learnDeviceByEntity(entity1);
+//        assertSame(d1, deviceManager.learnDeviceByEntity(entity1));
+//        assertSame(d1, deviceManager.findDeviceByEntity(entity1));
+//        assertEquals(DefaultEntityClassifier.entityClass ,
+//                          d1.getEntityClass());
+//        assertArrayEquals(new Short[] { -1 }, d1.getVlanId());
+//        assertArrayEquals(new Integer[] { }, d1.getIPv4Addresses());
+//
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceAdded(isA(IDevice.class));
+//        replay(mockListener);
+//
+//        Device d2 = deviceManager.learnDeviceByEntity(entity2);
+//        assertFalse(d1.equals(d2));
+//        assertNotSame(d1, d2);
+//        assertNotSame(d1.getDeviceKey(), d2.getDeviceKey());
+//        assertEquals(MockEntityClassifier.testEC, d2.getEntityClass());
+//        assertArrayEquals(new Short[] { -1 }, d2.getVlanId());
+//        assertArrayEquals(new Integer[] { }, d2.getIPv4Addresses());
+//
+//        assertEquals(2, deviceManager.getAllDevices().size());
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceIPV4AddrChanged(isA(IDevice.class));
+//        replay(mockListener);
+//
+//        Device d3 = deviceManager.learnDeviceByEntity(entity3);
+//        assertNotSame(d2, d3);
+//        assertEquals(d2.getDeviceKey(), d3.getDeviceKey());
+//        assertEquals(MockEntityClassifier.testEC, d3.getEntityClass());
+//        assertArrayEquals(new Integer[] { 1 },
+//                          d3.getIPv4Addresses());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(10L, 1) },
+//                          d3.getAttachmentPoints());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(10L, 1) },
+//                          d3.getAttachmentPoints(true));
+//        assertArrayEquals(new Short[] { -1 },
+//                          d3.getVlanId());
+//
+//        assertEquals(2, deviceManager.getAllDevices().size());
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceIPV4AddrChanged(isA(IDevice.class));
+//        replay(mockListener);
+//
+//        Device d4 = deviceManager.learnDeviceByEntity(entity4);
+//        assertNotSame(d1, d4);
+//        assertEquals(d1.getDeviceKey(), d4.getDeviceKey());
+//        assertEquals(DefaultEntityClassifier.entityClass, d4.getEntityClass());
+//        assertArrayEquals(new Integer[] { 1 },
+//                          d4.getIPv4Addresses());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) },
+//                          d4.getAttachmentPoints());
+//        assertArrayEquals(new Short[] { -1 },
+//                          d4.getVlanId());
+//
+//        assertEquals(2, deviceManager.getAllDevices().size());
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceAdded((isA(IDevice.class)));
+//        replay(mockListener);
+//
+//        Device d5 = deviceManager.learnDeviceByEntity(entity5);
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 2) },
+//                          d5.getAttachmentPoints());
+//        assertArrayEquals(new Short[] { (short) 4 },
+//                          d5.getVlanId());
+//        assertEquals(2L, d5.getMACAddress());
+//        assertEquals("00:00:00:00:00:02", d5.getMACAddressString());
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceAdded(isA(IDevice.class));
+//        replay(mockListener);
+//
+//        Device d6 = deviceManager.learnDeviceByEntity(entity6);
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(50L, 3) },
+//                          d6.getAttachmentPoints());
+//        assertArrayEquals(new Short[] { (short) 4 },
+//                          d6.getVlanId());
+//
+//        assertEquals(4, deviceManager.getAllDevices().size());
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceIPV4AddrChanged(isA(IDevice.class));
+//        replay(mockListener);
+//
+//        Device d7 = deviceManager.learnDeviceByEntity(entity7);
+//        assertNotSame(d6, d7);
+//        assertEquals(d6.getDeviceKey(), d7.getDeviceKey());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(50L, 3) },
+//                          d7.getAttachmentPoints());
+//        assertArrayEquals(new Short[] { (short) 4 },
+//                          d7.getVlanId());
+//
+//        assertEquals(4, deviceManager.getAllDevices().size());
+//        verify(mockListener);
+//
+//
+//        reset(mockListener);
+//        replay(mockListener);
+//
+//        reset(deviceManager.topology);
+//        deviceManager.topology.addListener(deviceManager);
+//        expectLastCall().times(1);
+//        replay(deviceManager.topology);
+//
+//        deviceManager.entityClassifier = new MockEntityClassifierMac();
+//        deviceManager.startUp(null);
+//        Entity entityNoClass = new Entity(5L, (short)1, 5, -1L, 1, new Date());
+//        assertEquals(null, deviceManager.learnDeviceByEntity(entityNoClass));
+//
+//        verify(mockListener);
+//    }
+//
+//
+//    private void doTestEntityOrdering(boolean computeInsertionPoint) throws Exception {
+//        Entity e = new Entity(10L, null, null, null, null, null);
+//        IEntityClass ec = createNiceMock(IEntityClass.class);
+//        Device d = new Device(deviceManager, 1L, e, ec);
+//
+//        int expectedLength = 1;
+//        Long[] macs = new Long[] {  5L,  // new first element
+//                                   15L,  // new last element
+//                                    7L,  // insert in middle
+//                                   12L,  // insert in middle
+//                                    6L,  // insert at idx 1
+//                                   14L,  // insert at idx length-2
+//                                    1L,
+//                                   20L
+//                                  };
+//
+//        for (Long mac: macs) {
+//            e = new Entity(mac, null, null, null, null, null);
+//            int insertionPoint;
+//            if (computeInsertionPoint) {
+//                insertionPoint = -(Arrays.binarySearch(d.entities, e)+1);
+//            } else {
+//                insertionPoint = -1;
+//            }
+//            d = deviceManager.allocateDevice(d, e, insertionPoint);
+//            expectedLength++;
+//            assertEquals(expectedLength, d.entities.length);
+//            for (int i = 0; i < d.entities.length-1; i++)
+//                assertEquals(-1, d.entities[i].compareTo(d.entities[i+1]));
+//        }
+//    }
+//
+//    @Test
+//    public void testEntityOrderingExternal() throws Exception {
+//        doTestEntityOrdering(true);
+//    }
+//
+//    @Test
+//    public void testEntityOrderingInternal() throws Exception {
+//        doTestEntityOrdering(false);
+//    }
+//
+//    @Test
+//    public void testAttachmentPointLearning() throws Exception {
+//        IDeviceListener mockListener =
+//                createMock(IDeviceListener.class);
+//        expect(mockListener.getName()).andReturn("mockListener").atLeastOnce();
+//        expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//        expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//
+//        replay(mockListener);
+//        deviceManager.addListener(mockListener);
+//        verify(mockListener);
+//        reset(mockListener);
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        expect(mockTopology.getL2DomainId(1L)).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(5L)).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(10L)).
+//        andReturn(10L).anyTimes();
+//        expect(mockTopology.getL2DomainId(50L)).
+//        andReturn(10L).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(anyLong(), anyShort())).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(),
+//                                                    anyLong(), anyShort())).andReturn(false).anyTimes();
+//
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).andReturn(true).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)1, 5L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(5L, (short)1, 10L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(10L, (short)1, 50L, (short)1)).
+//        andReturn(false).anyTimes();
+//
+//        Date topologyUpdateTime = new Date();
+//        expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime).
+//        anyTimes();
+//
+//        replay(mockTopology);
+//
+//        deviceManager.topology = mockTopology;
+//
+//        Calendar c = Calendar.getInstance();
+//        Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime());
+//        Entity entity0 = new Entity(1L, null, null, null, null, c.getTime());
+//        c.add(Calendar.SECOND, 1);
+//        Entity entity2 = new Entity(1L, null, null, 5L, 1, c.getTime());
+//        c.add(Calendar.SECOND, 1);
+//        Entity entity3 = new Entity(1L, null, null, 10L, 1, c.getTime());
+//        c.add(Calendar.SECOND, 1);
+//        Entity entity4 = new Entity(1L, null, null, 50L, 1, c.getTime());
+//
+//        IDevice d;
+//        SwitchPort[] aps;
+//        Integer[] ips;
+//
+//        mockListener.deviceAdded(isA(IDevice.class));
+//        replay(mockListener);
+//
+//        deviceManager.learnDeviceByEntity(entity1);
+//        d = deviceManager.learnDeviceByEntity(entity0);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps);
+//        ips = d.getIPv4Addresses();
+//        assertArrayEquals(new Integer[] { 1 }, ips);
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceMoved((isA(IDevice.class)));
+//        replay(mockListener);
+//
+//        d = deviceManager.learnDeviceByEntity(entity2);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1) }, aps);
+//        ips = d.getIPv4Addresses();
+//        assertArrayEquals(new Integer[] { 1 }, ips);
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceMoved((isA(IDevice.class)));
+//        replay(mockListener);
+//
+//        d = deviceManager.learnDeviceByEntity(entity3);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] {new SwitchPort(5L, 1), new SwitchPort(10L, 1)}, aps);
+//        ips = d.getIPv4Addresses();
+//        assertArrayEquals(new Integer[] { 1 }, ips);
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceMoved((isA(IDevice.class)));
+//        replay(mockListener);
+//
+//        d = deviceManager.learnDeviceByEntity(entity4);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1),
+//                                             new SwitchPort(50L, 1) }, aps);
+//        ips = d.getIPv4Addresses();
+//        assertArrayEquals(new Integer[] { 1 }, ips);
+//        verify(mockListener);
+//    }
+//
+//    private void verifyEntityArray(Entity[] expected, Device d) {
+//        Arrays.sort(expected);
+//        assertArrayEquals(expected, d.entities);
+//    }
+//
+//    @Test
+//    public void testNoLearningOnInternalPorts() throws Exception {
+//        IDeviceListener mockListener =
+//                createMock(IDeviceListener.class);
+//
+//        expect(mockListener.getName()).andReturn("mockListener").anyTimes();
+//        expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//        expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//
+//        replay(mockListener);
+//        deviceManager.addListener(mockListener);
+//        verify(mockListener);
+//        reset(mockListener);
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        expect(mockTopology.getL2DomainId(1L)).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(2L)).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(3L)).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(4L)).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(anyLong(), anyShort()))
+//                .andReturn(false).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(),
+//                                                    anyLong(), anyShort()))
+//                .andReturn(false).anyTimes();
+//
+//        expect(mockTopology.isAttachmentPointPort(or(eq(1L), eq(3L)), anyShort()))
+//                .andReturn(true).anyTimes();
+//        // Switches 2 and 4 have only internal ports
+//        expect(mockTopology.isAttachmentPointPort(or(eq(2L), eq(4L)), anyShort()))
+//                .andReturn(false).anyTimes();
+//
+//        expect(mockTopology.isConsistent(1L, (short)1, 3L, (short)1))
+//                .andReturn(false).once();
+//
+//        Date topologyUpdateTime = new Date();
+//        expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime).
+//        anyTimes();
+//
+//        replay(mockTopology);
+//
+//        deviceManager.topology = mockTopology;
+//
+//        Calendar c = Calendar.getInstance();
+//        Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime());
+//        c.add(Calendar.SECOND, 1);
+//        Entity entity2 = new Entity(1L, null, 2, 2L, 1, c.getTime());
+//        c.add(Calendar.SECOND, 1);
+//        Entity entity3 = new Entity(1L, null, 3, 3L, 1, c.getTime());
+//        c.add(Calendar.SECOND, 1);
+//        Entity entity4 = new Entity(1L, null, 4, 4L, 1, c.getTime());
+//
+//        IDevice d;
+//        SwitchPort[] aps;
+//        Integer[] ips;
+//
+//        mockListener.deviceAdded(isA(IDevice.class));
+//        expectLastCall().once();
+//        replay(mockListener);
+//
+//        // cannot learn device internal ports
+//        d = deviceManager.learnDeviceByEntity(entity2);
+//        assertNull(d);
+//        d = deviceManager.learnDeviceByEntity(entity4);
+//        assertNull(d);
+//
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps);
+//        verifyEntityArray(new Entity[] { entity1 } , (Device)d);
+//        ips = d.getIPv4Addresses();
+//        assertArrayEquals(new Integer[] { 1 }, ips);
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        replay(mockListener);
+//
+//        // don't learn
+//        d = deviceManager.learnDeviceByEntity(entity2);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps);
+//        verifyEntityArray(new Entity[] { entity1 } , (Device)d);
+//        ips = d.getIPv4Addresses();
+//        assertArrayEquals(new Integer[] { 1 }, ips);
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceMoved(isA(IDevice.class));
+//        mockListener.deviceIPV4AddrChanged(isA(IDevice.class));
+//        replay(mockListener);
+//
+//        // learn
+//        d = deviceManager.learnDeviceByEntity(entity3);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(3L, 1) }, aps);
+//        verifyEntityArray(new Entity[] { entity1, entity3 } , (Device)d);
+//        ips = d.getIPv4Addresses();
+//        Arrays.sort(ips);
+//        assertArrayEquals(new Integer[] { 1, 3 }, ips);
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        replay(mockListener);
+//
+//        // don't learn
+//        d = deviceManager.learnDeviceByEntity(entity4);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(3L, 1) }, aps);
+//        verifyEntityArray(new Entity[] { entity1, entity3 } , (Device)d);
+//        ips = d.getIPv4Addresses();
+//        Arrays.sort(ips);
+//        assertArrayEquals(new Integer[] { 1, 3 }, ips);
+//        verify(mockListener);
+//    }
+//
+//    @Test
+//    public void testAttachmentPointSuppression() throws Exception {
+//        IDeviceListener mockListener =
+//                createMock(IDeviceListener.class);
+//
+//        expect(mockListener.getName()).andReturn("mockListener").anyTimes();
+//        expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//        expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//
+//        replay(mockListener);
+//        deviceManager.addListener(mockListener);
+//        verify(mockListener);
+//        reset(mockListener);
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        expect(mockTopology.getL2DomainId(1L)).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(5L)).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(10L)).
+//        andReturn(10L).anyTimes();
+//        expect(mockTopology.getL2DomainId(50L)).
+//        andReturn(10L).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(anyLong(), anyShort()))
+//                .andReturn(false).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(),
+//                                                    anyLong(), anyShort()))
+//                .andReturn(false).anyTimes();
+//
+//        expect(mockTopology.isAttachmentPointPort(anyLong(), anyShort()))
+//                .andReturn(true).anyTimes();
+//        expect(mockTopology.isConsistent(5L, (short)1, 50L, (short)1))
+//                .andReturn(false).anyTimes();
+//
+//        Date topologyUpdateTime = new Date();
+//        expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime).
+//        anyTimes();
+//
+//        replay(mockTopology);
+//
+//        deviceManager.topology = mockTopology;
+//        // suppress (1L, 1) and (10L, 1)
+//        deviceManager.addSuppressAPs(1L, (short)1);
+//        deviceManager.addSuppressAPs(10L, (short)1);
+//
+//        Calendar c = Calendar.getInstance();
+//        Entity entity0 = new Entity(1L, null, null, null, null, c.getTime());
+//        // No attachment point should be learnt on 1L, 1
+//        Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime());
+//        c.add(Calendar.SECOND, 1);
+//        Entity entity2 = new Entity(1L, null, 1, 5L, 1, c.getTime());
+//        c.add(Calendar.SECOND, 1);
+//        Entity entity3 = new Entity(1L, null, null, 10L, 1, c.getTime());
+//        c.add(Calendar.SECOND, 1);
+//        Entity entity4 = new Entity(1L, null, null, 50L, 1, c.getTime());
+//
+//        IDevice d;
+//        SwitchPort[] aps;
+//        Integer[] ips;
+//
+//        mockListener.deviceAdded(isA(IDevice.class));
+//        mockListener.deviceIPV4AddrChanged((isA(IDevice.class)));
+//        replay(mockListener);
+//
+//        // TODO: we currently do learn entities on suppressed APs
+//        // // cannot learn device on suppressed AP
+//        // d = deviceManager.learnDeviceByEntity(entity1);
+//        // assertNull(d);
+//
+//        deviceManager.learnDeviceByEntity(entity0);
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertEquals(aps.length, 0);
+//        verifyEntityArray(new Entity[] { entity0, entity1} , (Device)d);
+//        ips = d.getIPv4Addresses();
+//        assertArrayEquals(new Integer[] { 1 }, ips);
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceMoved((isA(IDevice.class)));
+//        //mockListener.deviceIPV4AddrChanged((isA(IDevice.class)));
+//        replay(mockListener);
+//        d = deviceManager.learnDeviceByEntity(entity2);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1) }, aps);
+//        verifyEntityArray(new Entity[] { entity0, entity1, entity2 } , (Device)d);
+//        ips = d.getIPv4Addresses();
+//        assertArrayEquals(new Integer[] { 1 }, ips);
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        replay(mockListener);
+//
+//        d = deviceManager.learnDeviceByEntity(entity3);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1) }, aps);
+//        verifyEntityArray(new Entity[] { entity0, entity1, entity2, entity3 } , (Device)d);
+//        ips = d.getIPv4Addresses();
+//        assertArrayEquals(new Integer[] { 1 }, ips);
+//        verify(mockListener);
+//
+//        reset(mockListener);
+//        mockListener.deviceMoved((isA(IDevice.class)));
+//        replay(mockListener);
+//
+//        d = deviceManager.learnDeviceByEntity(entity4);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1),
+//                                             new SwitchPort(50L, 1) }, aps);
+//        verifyEntityArray(new Entity[] { entity0, entity1, entity2, entity3, entity4} , (Device)d);
+//        ips = d.getIPv4Addresses();
+//        assertArrayEquals(new Integer[] { 1 }, ips);
+//        verify(mockListener);
+//    }
+//
+//    @Test
+//    public void testBDAttachmentPointLearning() throws Exception {
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        expect(mockTopology.getL2DomainId(anyLong())).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.isAttachmentPointPort(anyLong(), anyShort())).
+//        andReturn(true).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(1L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(1L, (short)2)).
+//        andReturn(true).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(1L, (short)1,
+//                                                    1L, (short)2)).andReturn(true).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(1L, (short)2,
+//                                                    1L, (short)1)).andReturn(true).anyTimes();
+//        expect(mockTopology.isConsistent(anyLong(), anyShort(), anyLong(), anyShort())).andReturn(false).anyTimes();
+//
+//        Date topologyUpdateTime = new Date();
+//        expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime).
+//        anyTimes();
+//
+//        replay(mockTopology);
+//
+//        deviceManager.topology = mockTopology;
+//
+//        Calendar c = Calendar.getInstance();
+//        Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime());
+//        c.add(Calendar.MILLISECOND,
+//              (int)AttachmentPoint.OPENFLOW_TO_EXTERNAL_TIMEOUT/ 2);
+//        Entity entity2 = new Entity(1L, null, null, 1L, 2, c.getTime());
+//        c.add(Calendar.MILLISECOND,
+//              (int)AttachmentPoint.OPENFLOW_TO_EXTERNAL_TIMEOUT / 2 + 1);
+//        Entity entity3 = new Entity(1L, null, null, 1L, 2, c.getTime());
+//
+//        IDevice d;
+//        SwitchPort[] aps;
+//
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps);
+//
+//        // this timestamp is too soon; don't switch
+//        d = deviceManager.learnDeviceByEntity(entity2);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps);
+//
+//        // it should switch when we learn with a timestamp after the
+//        // timeout
+//        d = deviceManager.learnDeviceByEntity(entity3);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 2) }, aps);
+//    }
+//
+//    /**
+//     * This test verifies that the learning behavior on OFPP_LOCAL ports.
+//     * Once a host is learned on OFPP_LOCAL, it is allowed to move only from
+//     * one OFPP_LOCAL to another OFPP_LOCAL port.
+//     * @throws Exception
+//     */
+//    @Test
+//    public void testLOCALAttachmentPointLearning() throws Exception {
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        expect(mockTopology.getL2DomainId(anyLong())).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.isAttachmentPointPort(anyLong(), anyShort())).
+//        andReturn(true).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(1L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(1L, OFPort.OFPP_LOCAL.getValue())).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(1L, (short)2)).
+//        andReturn(true).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(1L, (short)1,
+//                                                    1L, OFPort.OFPP_LOCAL.getValue())).andReturn(true).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(1L, OFPort.OFPP_LOCAL.getValue(),
+//                                                    1L, (short)2)).andReturn(true).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(1L, (short)2,
+//                                                    1L, OFPort.OFPP_LOCAL.getValue())).andReturn(true).anyTimes();
+//        expect(mockTopology.isConsistent(anyLong(), anyShort(), anyLong(), anyShort())).andReturn(false).anyTimes();
+//
+//        Date topologyUpdateTime = new Date();
+//        expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime).
+//        anyTimes();
+//
+//        replay(mockTopology);
+//
+//        deviceManager.topology = mockTopology;
+//
+//        Calendar c = Calendar.getInstance();
+//        Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime());
+//        c.add(Calendar.MILLISECOND,
+//              (int)AttachmentPoint.OPENFLOW_TO_EXTERNAL_TIMEOUT/ 2);
+//        Entity entity2 = new Entity(1L, null, null, 1L, (int)OFPort.OFPP_LOCAL.getValue(), c.getTime());
+//        c.add(Calendar.MILLISECOND,
+//              (int)AttachmentPoint.OPENFLOW_TO_EXTERNAL_TIMEOUT + 1);
+//        Entity entity3 = new Entity(1L, null, null, 1L, 2, c.getTime());
+//
+//        IDevice d;
+//        SwitchPort[] aps;
+//
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps);
+//
+//        // Ensure that the attachment point changes to OFPP_LOCAL
+//        d = deviceManager.learnDeviceByEntity(entity2);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, OFPort.OFPP_LOCAL.getValue()) }, aps);
+//
+//        // Even though the new attachment point is consistent with old
+//        // and the time has elapsed, OFPP_LOCAL attachment point should
+//        // be maintained.
+//        d = deviceManager.learnDeviceByEntity(entity3);
+//        assertEquals(1, deviceManager.getAllDevices().size());
+//        aps = d.getAttachmentPoints();
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, OFPort.OFPP_LOCAL.getValue()) }, aps);
+//    }
+//
+//    @Test
+//    public void testPacketInBasic(byte[] deviceMac, OFPacketIn packetIn) {
+//        // Mock up our expected behavior
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        deviceManager.topology = mockTopology;
+//        expect(mockTopology.isAttachmentPointPort(EasyMock.anyLong(),
+//                EasyMock.anyShort())).
+//                andReturn(true).anyTimes();
+//        expect(mockTopology.isConsistent(EasyMock.anyLong(),
+//                EasyMock.anyShort(),
+//                EasyMock.anyLong(),
+//                EasyMock.anyShort())).andReturn(false).
+//                anyTimes();
+//        expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes();
+//        replay(mockTopology);
+//
+//        Date currentDate = new Date();
+//
+//        // build our expected Device
+//        Integer ipaddr = IPv4.toIPv4Address("192.168.1.1");
+//        Device device =
+//                new Device(deviceManager,
+//                        new Long(deviceManager.deviceKeyCounter),
+//                        new Entity(Ethernet.toLong(deviceMac),
+//                                (short)5,
+//                                ipaddr,
+//                                1L,
+//                                1,
+//                                currentDate),
+//                                DefaultEntityClassifier.entityClass);
+//
+//        // Get the listener and trigger the packet in
+//        IOFSwitch switch1 = mockFloodlightProvider.getSwitch(1L);
+//        mockFloodlightProvider.dispatchMessage(switch1, packetIn);
+//
+//        // Verify the replay matched our expectations
+//        // verify(mockTopology);
+//
+//        // Verify the device
+//        Device rdevice = (Device)
+//                deviceManager.findDevice(Ethernet.toLong(deviceMac),
+//                        (short)5, null, null, null);
+//
+//        assertEquals(device, rdevice);
+//        assertEquals(new Short((short)5), rdevice.getVlanId()[0]);
+//
+//        Device result = null;
+//        Iterator<? extends IDevice> dstiter =
+//                deviceManager.queryClassDevices(device.getEntityClass(),
+//                        null, null, ipaddr,
+//                        null, null);
+//        if (dstiter.hasNext()) {
+//            result = (Device)dstiter.next();
+//        }
+//
+//        assertEquals(device, result);
+//
+//        device =
+//                new Device(device,
+//                        new Entity(Ethernet.toLong(deviceMac),
+//                                (short)5,
+//                                ipaddr,
+//                                5L,
+//                                2,
+//                                currentDate),
+//                                -1);
+//
+//        reset(mockTopology);
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                anyShort())).
+//                andReturn(true).
+//                anyTimes();
+//        expect(mockTopology.isConsistent(EasyMock.anyLong(),
+//                EasyMock.anyShort(),
+//                EasyMock.anyLong(),
+//                EasyMock.anyShort())).andReturn(false).
+//                anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(EasyMock.anyLong(),
+//                EasyMock.anyShort()))
+//                .andReturn(false)
+//                .anyTimes();
+//        expect(mockTopology.getL2DomainId(1L)).andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(5L)).andReturn(1L).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(1L, (short)1, 5L, (short)2)).
+//        andReturn(false).anyTimes();
+//
+//        // Start recording the replay on the mocks
+//        replay(mockTopology);
+//        // Get the listener and trigger the packet in
+//        IOFSwitch switch5 = mockFloodlightProvider.getSwitch(5L);
+//        mockFloodlightProvider.
+//        dispatchMessage(switch5, this.packetIn_1.setInPort((short)2));
+//
+//        // Verify the replay matched our expectations
+//        verify(mockTopology);
+//
+//        // Verify the device
+//        rdevice = (Device)
+//                deviceManager.findDevice(Ethernet.toLong(deviceMac),
+//                        (short)5, null, null, null);
+//        assertEquals(device, rdevice);
+//    }
+//
+//    @Test
+//    public void testPacketIn() throws Exception {
+//        byte[] deviceMac1 =
+//                ((Ethernet)this.testARPReplyPacket_1).getSourceMACAddress();
+//        testPacketInBasic(deviceMac1, packetIn_1);
+//    }
+//
+//    /**
+//     * This test ensures the device manager learns the source device
+//     * corresponding to the senderHardwareAddress and senderProtocolAddress
+//     * in an ARP response whenever the senderHardwareAddress is different
+//     * from the source MAC address of the Ethernet frame.
+//     *
+//     * This test is the same as testPacketIn method, except for the
+//     * packet-in that's used.
+//     * @throws Exception
+//     */
+//    @Test
+//    public void testDeviceLearningFromArpResponseData() throws Exception {
+//        ARP arp = (ARP)((Ethernet)this.testARPReplyPacket_2).getPayload();
+//        byte[] deviceMac2 = arp.getSenderHardwareAddress();
+//
+//        testPacketInBasic(deviceMac2, packetIn_2);
+//    }
+//
+//    /**
+//     * Note: Entity expiration does not result in device moved notification.
+//     * @throws Exception
+//     */
+//    public void doTestEntityExpiration() throws Exception {
+//        IDeviceListener mockListener =
+//                createMock(IDeviceListener.class);
+//        expect(mockListener.getName()).andReturn("mockListener").anyTimes();
+//        expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//        expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).
+//                                                  andReturn(true).anyTimes();
+//
+//        expect(mockTopology.isBroadcastDomainPort(1L, (short)1)).andReturn(false).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(5L, (short)1)).andReturn(false).anyTimes();
+//        expect(mockTopology.getL2DomainId(1L)).andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(5L)).andReturn(5L).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)1, 5L, (short)1)).
+//        andReturn(false).anyTimes();
+//
+//        Date topologyUpdateTime = new Date();
+//        expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime).
+//        anyTimes();
+//
+//        replay(mockTopology);
+//        deviceManager.topology = mockTopology;
+//
+//        Calendar c = Calendar.getInstance();
+//        Entity entity1 = new Entity(1L, null, 2, 1L, 1, c.getTime());
+//        c.add(Calendar.MILLISECOND, -DeviceManagerImpl.ENTITY_TIMEOUT-1);
+//        Entity entity2 = new Entity(1L, null, 1, 5L, 1, c.getTime());
+//
+//        deviceManager.learnDeviceByEntity(entity1);
+//        IDevice d = deviceManager.learnDeviceByEntity(entity2);
+//        assertArrayEquals(new Integer[] { 1, 2 }, d.getIPv4Addresses());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
+//                                             new SwitchPort(5L, 1)},
+//                                             d.getAttachmentPoints());
+//        Iterator<? extends IDevice> diter =
+//                deviceManager.queryClassDevices(d.getEntityClass(),
+//                                                null, null, 1, null, null);
+//        assertTrue(diter.hasNext());
+//        assertEquals(d.getDeviceKey(), diter.next().getDeviceKey());
+//        diter = deviceManager.queryClassDevices(d.getEntityClass(),
+//                                                null, null, 2, null, null);
+//        assertTrue(diter.hasNext());
+//        assertEquals(d.getDeviceKey(), diter.next().getDeviceKey());
+//
+//        replay(mockListener);
+//        deviceManager.addListener(mockListener);
+//        verify(mockListener);
+//        reset(mockListener);
+//
+//        mockListener.deviceIPV4AddrChanged(isA(IDevice.class));
+//        replay(mockListener);
+//        deviceManager.entityCleanupTask.reschedule(0, null);
+//
+//        d = deviceManager.getDevice(d.getDeviceKey());
+//        assertArrayEquals(new Integer[] { 2 }, d.getIPv4Addresses());
+//
+//        // Attachment points are not removed, previous ones are still valid.
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
+//                                             new SwitchPort(5L, 1) },
+//                          d.getAttachmentPoints());
+//        diter = deviceManager.queryClassDevices(d.getEntityClass(),
+//                                                null, null, 2, null, null);
+//        assertTrue(diter.hasNext());
+//        assertEquals(d.getDeviceKey(), diter.next().getDeviceKey());
+//        diter = deviceManager.queryClassDevices(d.getEntityClass(),
+//                                                null, null, 1, null, null);
+//        assertFalse(diter.hasNext());
+//
+//        d = deviceManager.findDevice(1L, null, null, null, null);
+//        assertArrayEquals(new Integer[] { 2 }, d.getIPv4Addresses());
+//
+//        // Attachment points are not removed, previous ones are still valid.
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
+//                                             new SwitchPort(5L, 1) },
+//                          d.getAttachmentPoints());
+//
+//        verify(mockListener);
+//    }
+//
+//    public void doTestDeviceExpiration() throws Exception {
+//        IDeviceListener mockListener =
+//                createMock(IDeviceListener.class);
+//        expect(mockListener.getName()).andReturn("mockListener").anyTimes();
+//        expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//        expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject()))
+//        .andReturn(false).atLeastOnce();
+//
+//        Calendar c = Calendar.getInstance();
+//        c.add(Calendar.MILLISECOND, -DeviceManagerImpl.ENTITY_TIMEOUT-1);
+//        Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime());
+//        Entity entity2 = new Entity(1L, null, 2, 5L, 1, c.getTime());
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        deviceManager.topology = mockTopology;
+//
+//        expect(mockTopology.isAttachmentPointPort(EasyMock.anyLong(),
+//                                           EasyMock.anyShort())).
+//                                           andReturn(true).
+//                                           anyTimes();
+//        expect(mockTopology.getL2DomainId(1L)).andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(5L)).andReturn(1L).anyTimes();
+//        expect(mockTopology.isConsistent(EasyMock.anyLong(),
+//                                         EasyMock.anyShort(),
+//                                         EasyMock.anyLong(),
+//                                         EasyMock.anyShort())).andReturn(false).
+//                                         anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(EasyMock.anyLong(),
+//                                                  EasyMock.anyShort())).
+//                                                  andReturn(false).anyTimes();
+//        replay(mockTopology);
+//
+//        IDevice d = deviceManager.learnDeviceByEntity(entity2);
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//        assertArrayEquals(new Integer[] { 1, 2 }, d.getIPv4Addresses());
+//
+//        replay(mockListener);
+//        deviceManager.addListener(mockListener);
+//        verify(mockListener);
+//        reset(mockListener);
+//
+//        mockListener.deviceRemoved(isA(IDevice.class));
+//        replay(mockListener);
+//        deviceManager.entityCleanupTask.reschedule(0, null);
+//
+//        IDevice r = deviceManager.getDevice(d.getDeviceKey());
+//        assertNull(r);
+//        Iterator<? extends IDevice> diter =
+//                deviceManager.queryClassDevices(d.getEntityClass(),
+//                                                null, null, 1, null, null);
+//        assertFalse(diter.hasNext());
+//
+//        r = deviceManager.findDevice(1L, null, null, null, null);
+//        assertNull(r);
+//
+//        verify(mockListener);
+//    }
+//
+//    /*
+//     * A ConcurrentHashMap for devices (deviceMap) that can be used to test
+//     * code that specially handles concurrent modification situations. In
+//     * particular, we overwrite values() and will replace / remove all the
+//     * elements returned by values.
+//     *
+//     * The remove flag in the constructor specifies if devices returned by
+//     * values() should be removed or replaced.
+//     */
+//    protected static class ConcurrentlyModifiedDeviceMap
+//                            extends ConcurrentHashMap<Long, Device> {
+//        private static final long serialVersionUID = 7784938535441180562L;
+//        protected boolean remove;
+//        public ConcurrentlyModifiedDeviceMap(boolean remove) {
+//            super();
+//            this.remove = remove;
+//        }
+//
+//        @Override
+//        public Collection<Device> values() {
+//            // Get the values from the real map and copy them since
+//            // the collection returned by values can reflect changed
+//            Collection<Device> devs = new ArrayList<Device>(super.values());
+//            for (Device d: devs) {
+//                if (remove) {
+//                    // We remove the device from the underlying map
+//                    super.remove(d.getDeviceKey());
+//                } else {
+//                    super.remove(d.getDeviceKey());
+//                    // We add a different Device instance with the same
+//                    // key to the map. We'll do some hackery so the device
+//                    // is different enough to compare differently in equals
+//                    // but otherwise looks the same.
+//                    // It's ugly but it works.
+//                    // clone entities
+//                    Device newDevice = d;
+//                    for (Entity e: d.getEntities()) {
+//                        Entity newEntity = new Entity (e.macAddress,
+//                                                       e.vlan,
+//                                                       e.ipv4Address,
+//                                                       e.switchDPID,
+//                                                       e.switchPort,
+//                                                       e.lastSeenTimestamp);
+//                        if (e.vlan == null)
+//                            newEntity.vlan = (short)1;
+//                        else
+//                             newEntity.vlan = (short)((e.vlan + 1 % 4095)+1);
+//                        newDevice = new Device(newDevice, newEntity, -1);
+//                    }
+//                    assertEquals(false, newDevice.equals(d));
+//                    super.put(newDevice.getDeviceKey(), newDevice);
+//                }
+//            }
+//            return devs;
+//        }
+//    }
+//
+//    @Test
+//    public void testEntityExpiration() throws Exception {
+//        doTestEntityExpiration();
+//    }
+//
+//    @Test
+//    public void testDeviceExpiration() throws Exception {
+//        doTestDeviceExpiration();
+//    }
+//
+//    /* Test correct entity cleanup behavior when a concurrent modification
+//     * occurs.
+//     */
+//    @Test
+//    public void testEntityExpirationConcurrentModification() throws Exception {
+//        deviceManager.deviceMap = new ConcurrentlyModifiedDeviceMap(false);
+//        doTestEntityExpiration();
+//    }
+//
+//    /* Test correct entity cleanup behavior when a concurrent remove
+//     * occurs.
+//     */
+//    @Test
+//    public void testDeviceExpirationConcurrentRemove() throws Exception {
+//        deviceManager.deviceMap = new ConcurrentlyModifiedDeviceMap(true);
+//        doTestDeviceExpiration();
+//    }
+//
+//    /* Test correct entity cleanup behavior when a concurrent modification
+//     * occurs.
+//     */
+//    @Test
+//    public void testDeviceExpirationConcurrentModification() throws Exception {
+//        deviceManager.deviceMap = new ConcurrentlyModifiedDeviceMap(false);
+//        doTestDeviceExpiration();
+//    }
+//
+//
+//    @Test
+//    public void testAttachmentPointFlapping() throws Exception {
+//        Calendar c = Calendar.getInstance();
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).andReturn(true).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(anyLong(),
+//                                                  anyShort())).
+//                                                  andReturn(false).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(),
+//                                                    anyLong(), anyShort())).andReturn(false).anyTimes();
+//        expect(mockTopology.getL2DomainId(anyLong())).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)1, 1L, (short)1)).
+//        andReturn(true).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)1, 5L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)1, 10L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(5L, (short)1, 10L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(10L, (short)1, 1L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(5L, (short)1, 1L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(10L, (short)1, 5L, (short)1)).
+//        andReturn(false).anyTimes();
+//
+//        Date topologyUpdateTime = new Date();
+//        expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime).
+//        anyTimes();
+//
+//
+//        replay(mockTopology);
+//        deviceManager.topology = mockTopology;
+//
+//        Entity entity1 = new Entity(1L, null, null, 1L, 1, c.getTime());
+//        Entity entity1a = new Entity(1L, null, 1, 1L, 1, c.getTime());
+//        Entity entity2 = new Entity(1L, null, null, 5L, 1, c.getTime());
+//        Entity entity3 = new Entity(1L, null, null, 10L, 1, c.getTime());
+//        entity1.setLastSeenTimestamp(c.getTime());
+//        c.add(Calendar.MILLISECOND, Entity.ACTIVITY_TIMEOUT/2);
+//        entity1a.setLastSeenTimestamp(c.getTime());
+//        c.add(Calendar.MILLISECOND, 1);
+//        entity2.setLastSeenTimestamp(c.getTime());
+//        c.add(Calendar.MILLISECOND, 1);
+//        entity3.setLastSeenTimestamp(c.getTime());
+//
+//
+//
+//        IDevice d;
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//        d = deviceManager.learnDeviceByEntity(entity1a);
+//        d = deviceManager.learnDeviceByEntity(entity2);
+//        d = deviceManager.learnDeviceByEntity(entity3);
+//
+//        // all entities are active, so entity3 should win
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(10L, 1) },
+//                          d.getAttachmentPoints());
+//
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(10L, 1),},
+//                              d.getAttachmentPoints(true));
+//
+//        c.add(Calendar.MILLISECOND, Entity.ACTIVITY_TIMEOUT/4);
+//        entity1.setLastSeenTimestamp(c.getTime());
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//
+//        // all are still active; entity3 should still win
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) },
+//                          d.getAttachmentPoints());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
+//                                             new SwitchPort(5L, 1,
+//                                                            ErrorStatus.DUPLICATE_DEVICE),
+//                                                            new SwitchPort(10L, 1,
+//                                                                           ErrorStatus.DUPLICATE_DEVICE) },
+//                                                                           d.getAttachmentPoints(true));
+//
+//        c.add(Calendar.MILLISECOND, Entity.ACTIVITY_TIMEOUT+2000);
+//        entity1.setLastSeenTimestamp(c.getTime());
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//
+//        assertEquals(entity1.getActiveSince(), entity1.getLastSeenTimestamp());
+//        // entity1 should now be the only active entity
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) },
+//                          d.getAttachmentPoints());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) },
+//                          d.getAttachmentPoints(true));
+//    }
+//
+//
+//    @Test
+//    public void testAttachmentPointFlappingTwoCluster() throws Exception {
+//        Calendar c = Calendar.getInstance();
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).andReturn(true).anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(anyLong(),
+//                                                  anyShort())).
+//                                                  andReturn(false).anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(),
+//                                                    anyLong(), anyShort())).andReturn(false).anyTimes();
+//        expect(mockTopology.getL2DomainId(1L)).
+//        andReturn(1L).anyTimes();
+//        expect(mockTopology.getL2DomainId(5L)).
+//        andReturn(5L).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)1, 1L, (short)2)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)2, 5L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(5L, (short)1, 5L, (short)2)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)2, 1L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)1, 5L, (short)1)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(1L, (short)1, 5L, (short)2)).
+//        andReturn(false).anyTimes();
+//        expect(mockTopology.isConsistent(5L, (short)2, 5L, (short)1)).
+//        andReturn(false).anyTimes();
+//
+//        Date topologyUpdateTime = new Date();
+//        expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime).
+//        anyTimes();
+//
+//        replay(mockTopology);
+//        deviceManager.topology = mockTopology;
+//
+//        Entity entity1 = new Entity(1L, null, null, 1L, 1, c.getTime());
+//        Entity entity2 = new Entity(1L, null, null, 1L, 2, c.getTime());
+//        Entity entity3 = new Entity(1L, null, null, 5L, 1, c.getTime());
+//        Entity entity4 = new Entity(1L, null, null, 5L, 2, c.getTime());
+//        entity1.setLastSeenTimestamp(c.getTime());
+//        c.add(Calendar.MILLISECOND, Entity.ACTIVITY_TIMEOUT/2);
+//        c.add(Calendar.MILLISECOND, 1);
+//        entity2.setLastSeenTimestamp(c.getTime());
+//        c.add(Calendar.MILLISECOND, 1);
+//        entity3.setLastSeenTimestamp(c.getTime());
+//        c.add(Calendar.MILLISECOND, 1);
+//        entity4.setLastSeenTimestamp(c.getTime());
+//
+//        deviceManager.learnDeviceByEntity(entity1);
+//        deviceManager.learnDeviceByEntity(entity2);
+//        deviceManager.learnDeviceByEntity(entity3);
+//        IDevice d = deviceManager.learnDeviceByEntity(entity4);
+//
+//        // all entities are active, so entities 2,4 should win
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 2),
+//                                             new SwitchPort(5L, 2) },
+//                                             d.getAttachmentPoints());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 2),
+//                                             new SwitchPort(5L, 2)},
+//                                             d.getAttachmentPoints(true));
+//
+//        c.add(Calendar.MILLISECOND, 1);
+//        entity1.setLastSeenTimestamp(c.getTime());
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//
+//        // all entities are active, so entities 2,4 should win
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
+//                                             new SwitchPort(5L, 2) },
+//                                             d.getAttachmentPoints());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
+//                                             new SwitchPort(5L, 2),
+//                                             new SwitchPort(1L, 2, ErrorStatus.DUPLICATE_DEVICE)},
+//                                             d.getAttachmentPoints(true));
+//
+//        c.add(Calendar.MILLISECOND, Entity.ACTIVITY_TIMEOUT+1);
+//        entity1.setLastSeenTimestamp(c.getTime());
+//        d = deviceManager.learnDeviceByEntity(entity1);
+//
+//        // entities 3,4 are still in conflict, but 1 should be resolved
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
+//                                             new SwitchPort(5L, 2) },
+//                                             d.getAttachmentPoints());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
+//                                             new SwitchPort(5L, 2)},
+//                                             d.getAttachmentPoints(true));
+//
+//        entity3.setLastSeenTimestamp(c.getTime());
+//        d = deviceManager.learnDeviceByEntity(entity3);
+//
+//        // no conflicts, 1 and 3 will win
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
+//                                             new SwitchPort(5L, 1) },
+//                                             d.getAttachmentPoints());
+//        assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1),
+//                                             new SwitchPort(5L, 1) },
+//                                             d.getAttachmentPoints(true));
+//
+//    }
+//
+//    protected void doTestDeviceQuery() throws Exception {
+//        Entity entity1 = new Entity(1L, (short)1, 1, 1L, 1, new Date());
+//        Entity entity2 = new Entity(2L, (short)2, 2, 1L, 2, new Date());
+//        Entity entity3 = new Entity(3L, (short)3, 3, 5L, 1, new Date());
+//        Entity entity4 = new Entity(4L, (short)4, 3, 5L, 2, new Date());
+//        Entity entity5 = new Entity(1L, (short)4, 3, 5L, 2, new Date());
+//
+//        Device d1 = deviceManager.learnDeviceByEntity(entity1);
+//        deviceManager.learnDeviceByEntity(entity2);
+//        Device d3 = deviceManager.learnDeviceByEntity(entity3);
+//        Device d4 = deviceManager.learnDeviceByEntity(entity4);
+//
+//        IDevice d;
+//
+//        Iterator<? extends IDevice> iter =
+//                deviceManager.queryDevices(null, (short)1, 1, null, null);
+//        int count = 0;
+//        while (iter.hasNext()) {
+//            count += 1;
+//            d = iter.next();
+//            assertEquals(d1.getDeviceKey(), d.getDeviceKey());
+//        }
+//        assertEquals(1, count);
+//
+//        iter = deviceManager.queryDevices(null, (short)3, 3, null, null);
+//        count = 0;
+//        while (iter.hasNext()) {
+//            count += 1;
+//            d = iter.next();
+//            assertEquals(d3.getDeviceKey(), d.getDeviceKey());
+//        }
+//        assertEquals(1, count);
+//
+//        iter = deviceManager.queryDevices(null, (short)1, 3, null, null);
+//        count = 0;
+//        while (iter.hasNext()) {
+//            count += 1;
+//            iter.next();
+//        }
+//        assertEquals(0, count);
+//
+//        Device d5 = deviceManager.learnDeviceByEntity(entity5);
+//        iter = deviceManager.queryDevices(null, (short)4, 3, null, null);
+//        count = 0;
+//        Set<Long> deviceKeysFromIterator = new HashSet<Long>();
+//        while (iter.hasNext()) {
+//            count += 1;
+//            d = iter.next();
+//            deviceKeysFromIterator.add(d.getDeviceKey());
+//        }
+//        Set<Long> expectedDeviceKeys = new HashSet<Long>();
+//        expectedDeviceKeys.add(d4.getDeviceKey());
+//        expectedDeviceKeys.add(d5.getDeviceKey());
+//        assertEquals(expectedDeviceKeys, deviceKeysFromIterator);
+//        assertEquals(2, count);
+//
+//
+//        iter = deviceManager.queryDevices(1L, null, null, null, null);
+//        count = 0;
+//        deviceKeysFromIterator = new HashSet<Long>();
+//        while (iter.hasNext()) {
+//            count += 1;
+//            d = iter.next();
+//            deviceKeysFromIterator.add(d.getDeviceKey());
+//        }
+//        expectedDeviceKeys = new HashSet<Long>();
+//        expectedDeviceKeys.add(d1.getDeviceKey());
+//        expectedDeviceKeys.add(d5.getDeviceKey());
+//        assertEquals(expectedDeviceKeys, deviceKeysFromIterator);
+//        assertEquals(2, count);
+//    }
+//
+//    @Test
+//    public void testDeviceIndex() throws Exception {
+//        EnumSet<IDeviceService.DeviceField> indexFields =
+//                EnumSet.noneOf(IDeviceService.DeviceField.class);
+//        indexFields.add(IDeviceService.DeviceField.IPV4);
+//        indexFields.add(IDeviceService.DeviceField.VLAN);
+//        deviceManager.addIndex(false, indexFields);
+//
+//        indexFields = EnumSet.noneOf(IDeviceService.DeviceField.class);
+//        deviceManager.addIndex(false, indexFields);
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        deviceManager.topology = mockTopology;
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).
+//                                                  andReturn(true).anyTimes();
+//        expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes();
+//        replay(mockTopology);
+//        doTestDeviceQuery();
+//    }
+//
+//    @Test
+//    public void testDeviceQuery() throws Exception {
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        deviceManager.topology = mockTopology;
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).
+//                                                  andReturn(true).anyTimes();
+//        expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes();
+//        replay(mockTopology);
+//
+//        doTestDeviceQuery();
+//    }
+//
+//    protected void doTestDeviceClassQuery() throws Exception {
+//        Entity entity1 = new Entity(1L, (short)1, 1, 1L, 1, new Date());
+//        Entity entity2 = new Entity(2L, (short)2, 2, 1L, 2, new Date());
+//        Entity entity3 = new Entity(3L, (short)3, 3, 5L, 1, new Date());
+//        Entity entity4 = new Entity(4L, (short)4, 3, 5L, 2, new Date());
+//        Entity entity5 = new Entity(1L, (short)4, 3, 5L, 2, new Date());
+//
+//        IDevice d1 = deviceManager.learnDeviceByEntity(entity1);
+//        IDevice d2 = deviceManager.learnDeviceByEntity(entity2);
+//        IDevice d3 = deviceManager.learnDeviceByEntity(entity3);
+//        IDevice d4 = deviceManager.learnDeviceByEntity(entity4);
+//        assertEquals(d1.getEntityClass(), d2.getEntityClass());
+//        assertEquals(d1.getEntityClass(), d3.getEntityClass());
+//        assertEquals(d1.getEntityClass(), d4.getEntityClass());
+//
+//        IDevice d;
+//
+//        Iterator<? extends IDevice> iter =
+//                deviceManager.queryClassDevices(d1.getEntityClass(), null,
+//                                                (short)1, 1, null, null);
+//        int count = 0;
+//        while (iter.hasNext()) {
+//            count += 1;
+//            d = iter.next();
+//            assertEquals(d1.getDeviceKey(), d.getDeviceKey());
+//        }
+//        assertEquals(1, count);
+//
+//        iter = deviceManager.queryClassDevices(d1.getEntityClass(), null,
+//                                               (short)3, 3, null, null);
+//        count = 0;
+//        while (iter.hasNext()) {
+//            count += 1;
+//            d = iter.next();
+//            assertEquals(d3.getDeviceKey(), d.getDeviceKey());
+//
+//        }
+//        assertEquals(1, count);
+//
+//        iter = deviceManager.queryClassDevices(d1.getEntityClass(), null,
+//                                               (short)1, 3, null, null);
+//        count = 0;
+//        while (iter.hasNext()) {
+//            count += 1;
+//            iter.next();
+//        }
+//        assertEquals(0, count);
+//
+//        IDevice d5 = deviceManager.learnDeviceByEntity(entity5);
+//        assertEquals(d1.getEntityClass(), d5.getEntityClass());
+//        iter = deviceManager.queryClassDevices(d1.getEntityClass(), null,
+//                                               (short)4, 3, null, null);
+//        count = 0;
+//        Set<Long> deviceKeysFromIterator = new HashSet<Long>();
+//        while (iter.hasNext()) {
+//            count += 1;
+//            d = iter.next();
+//            deviceKeysFromIterator.add(d.getDeviceKey());
+//        }
+//        Set<Long> expectedDeviceKeys = new HashSet<Long>();
+//        expectedDeviceKeys.add(d4.getDeviceKey());
+//        expectedDeviceKeys.add(d5.getDeviceKey());
+//        assertEquals(expectedDeviceKeys, deviceKeysFromIterator);
+//        assertEquals(2, count);
+//    }
+//
+//    @Test
+//    public void testDeviceClassIndex() throws Exception {
+//        EnumSet<IDeviceService.DeviceField> indexFields =
+//                EnumSet.noneOf(IDeviceService.DeviceField.class);
+//        indexFields.add(IDeviceService.DeviceField.IPV4);
+//        indexFields.add(IDeviceService.DeviceField.VLAN);
+//        deviceManager.addIndex(true, indexFields);
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        deviceManager.topology = mockTopology;
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).
+//                                                  andReturn(true).anyTimes();
+//        expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes();
+//        replay(mockTopology);
+//
+//        doTestDeviceClassQuery();
+//    }
+//
+//    @Test
+//    public void testDeviceClassQuery() throws Exception {
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        deviceManager.topology = mockTopology;
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).
+//                                                  andReturn(true).anyTimes();
+//        expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes();
+//        replay(mockTopology);
+//
+//        doTestDeviceClassQuery();
+//    }
+//
+//    @Test
+//    public void testFindDevice() throws FloodlightModuleException {
+//        boolean exceptionCaught;
+//        deviceManager.entityClassifier= new MockEntityClassifierMac();
+//        deviceManager.startUp(null);
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        deviceManager.topology = mockTopology;
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).
+//                                                  andReturn(true).anyTimes();
+//        expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes();
+//        replay(mockTopology);
+//
+//        Entity entity1 = new Entity(1L, (short)1, 1, 1L, 1, new Date());
+//        Entity entity2 = new Entity(2L, (short)2, 2, 1L, 2, new Date());
+//        Entity entity2b = new Entity(22L, (short)2, 2, 1L, 2, new Date());
+//
+//        Entity entity3 = new Entity(3L, (short)1, 3, 2L, 1, new Date());
+//        Entity entity4 = new Entity(4L, (short)2, 4, 2L, 2, new Date());
+//
+//        Entity entity5 = new Entity(5L, (short)1, 5, 3L, 1, new Date());
+//
+//
+//        IDevice d1 = deviceManager.learnDeviceByEntity(entity1);
+//        IDevice d2 = deviceManager.learnDeviceByEntity(entity2);
+//        IDevice d3 = deviceManager.learnDeviceByEntity(entity3);
+//        IDevice d4 = deviceManager.learnDeviceByEntity(entity4);
+//        IDevice d5 = deviceManager.learnDeviceByEntity(entity5);
+//
+//        // Make sure the entity classifier worked as expected
+//        assertEquals(MockEntityClassifierMac.testECMac1, d1.getEntityClass());
+//        assertEquals(MockEntityClassifierMac.testECMac1, d2.getEntityClass());
+//        assertEquals(MockEntityClassifierMac.testECMac2, d3.getEntityClass());
+//        assertEquals(MockEntityClassifierMac.testECMac2, d4.getEntityClass());
+//        assertEquals(DefaultEntityClassifier.entityClass,
+//                     d5.getEntityClass());
+//
+//        // Look up the device using findDevice() which uses only the primary
+//        // index
+//        assertEquals(d1, deviceManager.findDevice(entity1.getMacAddress(),
+//                                                  entity1.getVlan(),
+//                                                  entity1.getIpv4Address(),
+//                                                  entity1.getSwitchDPID(),
+//                                                  entity1.getSwitchPort()));
+//        // port changed. Device will be found through class index
+//        assertEquals(d1, deviceManager.findDevice(entity1.getMacAddress(),
+//                                                  entity1.getVlan(),
+//                                                  entity1.getIpv4Address(),
+//                                                  entity1.getSwitchDPID(),
+//                                                  entity1.getSwitchPort()+1));
+//        // VLAN changed. No device matches
+//        assertEquals(null, deviceManager.findDevice(entity1.getMacAddress(),
+//                                                  (short)42,
+//                                                  entity1.getIpv4Address(),
+//                                                  entity1.getSwitchDPID(),
+//                                                  entity1.getSwitchPort()));
+//        assertEquals(null, deviceManager.findDevice(entity1.getMacAddress(),
+//                                                  null,
+//                                                  entity1.getIpv4Address(),
+//                                                  entity1.getSwitchDPID(),
+//                                                  entity1.getSwitchPort()));
+//        assertEquals(d2, deviceManager.findDeviceByEntity(entity2));
+//        assertEquals(null, deviceManager.findDeviceByEntity(entity2b));
+//        assertEquals(d3, deviceManager.findDevice(entity3.getMacAddress(),
+//                                                  entity3.getVlan(),
+//                                                  entity3.getIpv4Address(),
+//                                                  entity3.getSwitchDPID(),
+//                                                  entity3.getSwitchPort()));
+//        // switch and port not set. throws exception
+//        exceptionCaught = false;
+//        try {
+//            assertEquals(null, deviceManager.findDevice(entity3.getMacAddress(),
+//                                                        entity3.getVlan(),
+//                                                        entity3.getIpv4Address(),
+//                                                        null,
+//                                                        null));
+//        }
+//        catch (IllegalArgumentException e) {
+//            exceptionCaught = true;
+//        }
+//        if (!exceptionCaught)
+//            fail("findDevice() did not throw IllegalArgumentException");
+//        assertEquals(d4, deviceManager.findDeviceByEntity(entity4));
+//        assertEquals(d5, deviceManager.findDevice(entity5.getMacAddress(),
+//                                                  entity5.getVlan(),
+//                                                  entity5.getIpv4Address(),
+//                                                  entity5.getSwitchDPID(),
+//                                                  entity5.getSwitchPort()));
+//        // switch and port not set. throws exception (swith/port are key
+//        // fields of IEntityClassifier but not d5.entityClass
+//        exceptionCaught = false;
+//        try {
+//            assertEquals(d5, deviceManager.findDevice(entity5.getMacAddress(),
+//                                                      entity5.getVlan(),
+//                                                      entity5.getIpv4Address(),
+//                                                      null,
+//                                                      null));
+//        }
+//        catch (IllegalArgumentException e) {
+//            exceptionCaught = true;
+//        }
+//        if (!exceptionCaught)
+//            fail("findDevice() did not throw IllegalArgumentException");
+//
+//
+//        Entity entityNoClass = new Entity(5L, (short)1, 5, -1L, 1, new Date());
+//        assertEquals(null, deviceManager.findDeviceByEntity(entityNoClass));
+//
+//
+//        // Now look up destination devices
+//        assertEquals(d1, deviceManager.findClassDevice(d2.getEntityClass(),
+//                                                  entity1.getMacAddress(),
+//                                                  entity1.getVlan(),
+//                                                  entity1.getIpv4Address()));
+//        assertEquals(d1, deviceManager.findClassDevice(d2.getEntityClass(),
+//                                                  entity1.getMacAddress(),
+//                                                  entity1.getVlan(),
+//                                                  null));
+//        assertEquals(null, deviceManager.findClassDevice(d2.getEntityClass(),
+//                                                  entity1.getMacAddress(),
+//                                                  (short) -1,
+//                                                  0));
+//    }
+//
+//
+//
+//    @Test
+//    public void testGetIPv4Addresses() {
+//        // Looks like Date is only 1s granularity
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        deviceManager.topology = mockTopology;
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).
+//                                                  andReturn(true).anyTimes();
+//        expect(mockTopology.getL2DomainId(anyLong())).andReturn(1L).anyTimes();
+//        expect(mockTopology.isConsistent(EasyMock.anyLong(),
+//                                         EasyMock.anyShort(),
+//                                         EasyMock.anyLong(),
+//                                         EasyMock.anyShort()))
+//                                         .andReturn(false)
+//                                         .anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(EasyMock.anyLong(),
+//                                                  EasyMock.anyShort()))
+//                                                  .andReturn(false)
+//                                                  .anyTimes();
+//        expect(mockTopology.isInSameBroadcastDomain(EasyMock.anyLong(),
+//                                                    EasyMock.anyShort(),
+//                                                    EasyMock.anyLong(),
+//                                                    EasyMock.anyShort())).
+//                                                    andReturn(false).anyTimes();
+//        replay(mockTopology);
+//
+//        Entity e1 = new Entity(1L, (short)1, null, null, null, new Date(2000));
+//        Device d1 = deviceManager.learnDeviceByEntity(e1);
+//        assertArrayEquals(new Integer[0], d1.getIPv4Addresses());
+//
+//
+//        Entity e2 = new Entity(2L, (short)2, 2, null, null, new Date(2000));
+//        Device d2 = deviceManager.learnDeviceByEntity(e2);
+//        d2 = deviceManager.learnDeviceByEntity(e2);
+//        assertArrayEquals(new Integer[] { 2 }, d2.getIPv4Addresses());
+//        // More than one entity
+//        Entity e2b = new Entity(2L, (short)2, null, 2L, 2, new Date(3000));
+//        d2 = deviceManager.learnDeviceByEntity(e2b);
+//        assertEquals(2, d2.entities.length);
+//        assertArrayEquals(new Integer[] { 2 }, d2.getIPv4Addresses());
+//        // and now add an entity with an IP
+//        Entity e2c = new Entity(2L, (short)2, 2, 2L, 3, new Date(3000));
+//        d2 = deviceManager.learnDeviceByEntity(e2c);
+//        assertArrayEquals(new Integer[] { 2 }, d2.getIPv4Addresses());
+//        assertEquals(3, d2.entities.length);
+//
+//        // Other devices with different IPs shouldn't interfere
+//        Entity e3 = new Entity(3L, (short)3, 3, null, null, new Date(4000));
+//        Entity e3b = new Entity(3L, (short)3, 3, 3L, 3, new Date(4400));
+//        Device d3 = deviceManager.learnDeviceByEntity(e3);
+//        d3 = deviceManager.learnDeviceByEntity(e3b);
+//        assertArrayEquals(new Integer[] { 2 }, d2.getIPv4Addresses());
+//        assertArrayEquals(new Integer[] { 3 }, d3.getIPv4Addresses());
+//
+//        // Add another IP to d3
+//        Entity e3c = new Entity(3L, (short)3, 33, 3L, 3, new Date(4400));
+//        d3 = deviceManager.learnDeviceByEntity(e3c);
+//        Integer[] ips = d3.getIPv4Addresses();
+//        Arrays.sort(ips);
+//        assertArrayEquals(new Integer[] { 3, 33 }, ips);
+//
+//        // Add another device that also claims IP2 but is older than e2
+//        Entity e4 = new Entity(4L, (short)4, 2, null, null, new Date(1000));
+//        Entity e4b = new Entity(4L, (short)4, null, 4L, 4, new Date(1000));
+//        Device d4 = deviceManager.learnDeviceByEntity(e4);
+//        assertArrayEquals(new Integer[] { 2 }, d2.getIPv4Addresses());
+//        assertArrayEquals(new Integer[0],  d4.getIPv4Addresses());
+//        // add another entity to d4
+//        d4 = deviceManager.learnDeviceByEntity(e4b);
+//        assertArrayEquals(new Integer[0], d4.getIPv4Addresses());
+//
+//        // Make e4 and e4a newer
+//        Entity e4c = new Entity(4L, (short)4, 2, null, null, new Date(5000));
+//        Entity e4d = new Entity(4L, (short)4, null, 4L, 5, new Date(5000));
+//        d4 = deviceManager.learnDeviceByEntity(e4c);
+//        d4 = deviceManager.learnDeviceByEntity(e4d);
+//        assertArrayEquals(new Integer[0], d2.getIPv4Addresses());
+//        // FIXME: d4 should not return IP4
+//        assertArrayEquals(new Integer[] { 2 }, d4.getIPv4Addresses());
+//
+//        // Add another newer entity to d2 but with different IP
+//        Entity e2d = new Entity(2L, (short)2, 22, 4L, 6, new Date(6000));
+//        d2 = deviceManager.learnDeviceByEntity(e2d);
+//        assertArrayEquals(new Integer[] { 22 }, d2.getIPv4Addresses());
+//        assertArrayEquals(new Integer[] { 2 }, d4.getIPv4Addresses());
+//
+//        // new IP for d2,d4 but with same timestamp. Both devices get the IP
+//        Entity e2e = new Entity(2L, (short)2, 42, 2L, 4, new Date(7000));
+//        d2 = deviceManager.learnDeviceByEntity(e2e);
+//        ips= d2.getIPv4Addresses();
+//        Arrays.sort(ips);
+//        assertArrayEquals(new Integer[] { 22, 42 }, ips);
+//        Entity e4e = new Entity(4L, (short)4, 42, 4L, 7, new Date(7000));
+//        d4 = deviceManager.learnDeviceByEntity(e4e);
+//        ips= d4.getIPv4Addresses();
+//        Arrays.sort(ips);
+//        assertArrayEquals(new Integer[] { 2, 42 }, ips);
+//
+//        // add a couple more IPs
+//        Entity e2f = new Entity(2L, (short)2, 4242, 2L, 5, new Date(8000));
+//        d2 = deviceManager.learnDeviceByEntity(e2f);
+//        ips= d2.getIPv4Addresses();
+//        Arrays.sort(ips);
+//        assertArrayEquals(new Integer[] { 22, 42, 4242 }, ips);
+//        Entity e4f = new Entity(4L, (short)4, 4242, 4L, 8, new Date(9000));
+//        d4 = deviceManager.learnDeviceByEntity(e4f);
+//        ips= d4.getIPv4Addresses();
+//        Arrays.sort(ips);
+//        assertArrayEquals(new Integer[] { 2, 42, 4242 }, ips);
+//    }
+//
+//    // TODO: this test should really go into a separate class that collects
+//    // unit tests for Device
+//    @Test
+//    public void testGetSwitchPortVlanId() {
+//            Entity entity1 = new Entity(1L, (short)1, null, 10L, 1, new Date());
+//            Entity entity2 = new Entity(1L, null, null, 10L, 1, new Date());
+//            Entity entity3 = new Entity(1L, (short)3, null,  1L, 1, new Date());
+//            Entity entity4 = new Entity(1L, (short)42, null,  1L, 1, new Date());
+//            Entity[] entities = new Entity[] { entity1, entity2,
+//                                               entity3, entity4
+//                                             };
+//            Device d = new Device(null,1L, null, null, null,
+//                                  Arrays.asList(entities), null);
+//            SwitchPort swp1x1 = new SwitchPort(1L, 1);
+//            SwitchPort swp1x2 = new SwitchPort(1L, 2);
+//            SwitchPort swp2x1 = new SwitchPort(2L, 1);
+//            SwitchPort swp10x1 = new SwitchPort(10L, 1);
+//            assertArrayEquals(new Short[] { -1, 1},
+//                              d.getSwitchPortVlanIds(swp10x1));
+//            assertArrayEquals(new Short[] { 3, 42},
+//                              d.getSwitchPortVlanIds(swp1x1));
+//            assertArrayEquals(new Short[0],
+//                              d.getSwitchPortVlanIds(swp1x2));
+//            assertArrayEquals(new Short[0],
+//                              d.getSwitchPortVlanIds(swp2x1));
+//    }
+//
+//    @Test
+//    public void testReclassifyDevice() throws FloodlightModuleException {
+//        MockFlexEntityClassifier flexClassifier =
+//                new MockFlexEntityClassifier();
+//        deviceManager.entityClassifier= flexClassifier;
+//        deviceManager.startUp(null);
+//
+//        ITopologyService mockTopology = createMock(ITopologyService.class);
+//        deviceManager.topology = mockTopology;
+//        expect(mockTopology.isAttachmentPointPort(anyLong(),
+//                                                  anyShort())).
+//                                                  andReturn(true).anyTimes();
+//        expect(mockTopology.getL2DomainId(anyLong())).andReturn(1L).anyTimes();
+//        expect(mockTopology.isConsistent(EasyMock.anyLong(),
+//                                         EasyMock.anyShort(),
+//                                         EasyMock.anyLong(),
+//                                         EasyMock.anyShort()))
+//                                         .andReturn(false)
+//                                         .anyTimes();
+//        expect(mockTopology.isBroadcastDomainPort(EasyMock.anyLong(),
+//                                                  EasyMock.anyShort()))
+//                                                  .andReturn(false)
+//                                                  .anyTimes();
+//        replay(mockTopology);
+//
+//        //flexClassifier.createTestEntityClass("Class1");
+//
+//        Entity entity1 = new Entity(1L, (short)1, 1, 1L, 1, new Date());
+//        Entity entity1b = new Entity(1L, (short)2, 1, 1L, 1, new Date());
+//        Entity entity2 = new Entity(2L, (short)1, 2, 2L, 2, new Date());
+//        Entity entity2b = new Entity(2L, (short)2, 2, 2L, 2, new Date());
+//
+//
+//        Device d1 = deviceManager.learnDeviceByEntity(entity1);
+//        Device d2 = deviceManager.learnDeviceByEntity(entity2);
+//        Device d1b = deviceManager.learnDeviceByEntity(entity1b);
+//        Device d2b = deviceManager.learnDeviceByEntity(entity2b);
+//
+//        d1 = deviceManager.getDeviceIteratorForQuery(entity1.getMacAddress(),
+//                        entity1.getVlan(), entity1.getIpv4Address(),
+//                        entity1.getSwitchDPID(), entity1.getSwitchPort())
+//                        .next();
+//        d1b = deviceManager.getDeviceIteratorForQuery(entity1b.getMacAddress(),
+//                entity1b.getVlan(), entity1b.getIpv4Address(),
+//                entity1b.getSwitchDPID(), entity1b.getSwitchPort()).next();
+//
+//        assertEquals(d1, d1b);
+//
+//        d2 = deviceManager.getDeviceIteratorForQuery(entity2.getMacAddress(),
+//                entity2.getVlan(), entity2.getIpv4Address(),
+//                entity2.getSwitchDPID(), entity2.getSwitchPort()).next();
+//        d2b = deviceManager.getDeviceIteratorForQuery(entity2b.getMacAddress(),
+//                entity2b.getVlan(), entity2b.getIpv4Address(),
+//                entity2b.getSwitchDPID(), entity2b.getSwitchPort()).next();
+//        assertEquals(d2, d2b);
+//
+//        IEntityClass eC1 = flexClassifier.createTestEntityClass("C1");
+//        IEntityClass eC2 = flexClassifier.createTestEntityClass("C2");
+//
+//        flexClassifier.addVlanEntities((short)1, eC1);
+//        flexClassifier.addVlanEntities((short)2, eC1);
+//
+//        deviceManager.reclassifyDevice(d1);
+//        deviceManager.reclassifyDevice(d2);
+//
+//        d1 = deviceManager.deviceMap.get(
+//                deviceManager.primaryIndex.findByEntity(entity1));
+//        d1b = deviceManager.deviceMap.get(
+//                deviceManager.primaryIndex.findByEntity(entity1b));
+//
+//        assertEquals(d1, d1b);
+//
+//        d2 = deviceManager.deviceMap.get(
+//                deviceManager.primaryIndex.findByEntity(entity2));
+//        d2b = deviceManager.deviceMap.get(
+//                deviceManager.primaryIndex.findByEntity(entity2b));
+//
+//        assertEquals(d2, d2b);
+//
+//        flexClassifier.addVlanEntities((short)1, eC2);
+//
+//        deviceManager.reclassifyDevice(d1);
+//        deviceManager.reclassifyDevice(d2);
+//        d1 = deviceManager.deviceMap.get(
+//                deviceManager.primaryIndex.findByEntity(entity1));
+//        d1b = deviceManager.deviceMap.get(
+//                deviceManager.primaryIndex.findByEntity(entity1b));
+//        d2 = deviceManager.deviceMap.get(
+//                deviceManager.primaryIndex.findByEntity(entity2));
+//        d2b = deviceManager.deviceMap.get(
+//                deviceManager.primaryIndex.findByEntity(entity2b));
+//
+//        assertNotSame(d1, d1b);
+//
+//        assertNotSame(d2, d2b);
+//
+//        flexClassifier.addVlanEntities((short)1, eC1);
+//        deviceManager.reclassifyDevice(d1);
+//        deviceManager.reclassifyDevice(d2);
+//        ClassState classState = deviceManager.classStateMap.get(eC1.getName());
+//
+//        Long deviceKey1 = null;
+//        Long deviceKey1b = null;
+//        Long deviceKey2 = null;
+//        Long deviceKey2b = null;
+//
+//        deviceKey1 =
+//                classState.classIndex.findByEntity(entity1);
+//        deviceKey1b =
+//                classState.classIndex.findByEntity(entity1b);
+//        deviceKey2 =
+//                classState.classIndex.findByEntity(entity2);
+//        deviceKey2b =
+//                classState.classIndex.findByEntity(entity2b);
+//
+//        assertEquals(deviceKey1, deviceKey1b);
+//
+//        assertEquals(deviceKey2, deviceKey2b);
+//    }
+//
+//    @Test
+//    public void testSyncEntity() {
+//        Date d1 = new Date();
+//        Date d2 = new Date(0);
+//        Entity e1 = new Entity(1L, (short)2, 3, 4L, 5, d1);
+//        e1.setActiveSince(d2);
+//        SyncEntity se1 = new SyncEntity(e1);
+//        assertEntityEquals(e1, se1);
+//        assertEquals(1L, se1.macAddress);
+//        assertEquals(Short.valueOf((short)2), se1.vlan);
+//        assertEquals(Integer.valueOf(3), se1.ipv4Address);
+//        assertEquals(Long.valueOf(4L), se1.switchDPID);
+//        assertEquals(Integer.valueOf(5), se1.switchPort);
+//        assertEquals(d1, se1.lastSeenTimestamp);
+//        assertEquals(d2, se1.activeSince);
+//        assertNotSame(d1, se1.lastSeenTimestamp);
+//        assertNotSame(d2, se1.activeSince);
+//
+//        Entity e2 = new Entity(42L, null, null, null, null, null);
+//        SyncEntity se2 = new SyncEntity(e2);
+//        assertEntityEquals(e2, se2);
+//
+//        SyncEntity se3 = new SyncEntity();
+//        SyncEntity se4 = new SyncEntity();
+//        se3.lastSeenTimestamp = new Date(1000);
+//        se4.lastSeenTimestamp = new Date(2000);
+//        assertTrue("", se3.compareTo(se4) < 0);
+//        assertTrue("", se4.compareTo(se3) > 0);
+//        se4.lastSeenTimestamp = new Date(1000);
+//        assertTrue("", se3.compareTo(se4) == 0);
+//        assertTrue("", se4.compareTo(se3) == 0);
+//        se4.lastSeenTimestamp = new Date(500);
+//        assertTrue("", se3.compareTo(se4) > 0);
+//        assertTrue("", se4.compareTo(se3) < 0);
+//    }
+//
+//    /* Test basic DeviceSyncRepresentation behavior */
+//    @Test
+//    public void testDeviceSyncRepresentationBasics() {
+//        DeviceSyncRepresentation dsr = new DeviceSyncRepresentation();
+//        assertNull(dsr.getKey());
+//        assertNull(dsr.getEntities());
+//        dsr.setKey("MyKey");
+//        assertEquals("MyKey", dsr.getKey());
+//        assertEquals("MyKey", dsr.toString());
+//
+//        List<SyncEntity> entities = new ArrayList<SyncEntity>();
+//        Entity e1a = new Entity(1L, (short)2, 3, 4L, 5, new Date(1000));
+//        Entity e1b = new Entity(1L, (short)2, null, 4L, 5, new Date(0));
+//        entities.add(new SyncEntity(e1a));
+//        entities.add(new SyncEntity(e1b));
+//        // e1b comes before e1 (lastSeen) but we add it after it to test
+//        // sorting
+//        dsr.setEntities(entities);
+//
+//        assertEquals(2, dsr.getEntities().size());
+//        // e1b has earlier time
+//        assertEquals(e1b, dsr.getEntities().get(0).asEntity());
+//        assertEquals(e1a, dsr.getEntities().get(1).asEntity());
+//
+//        dsr.setKey(null);
+//        dsr.setEntities(null);
+//        assertNull(dsr.getKey());
+//        assertNull(dsr.getEntities());
+//    }
+//
+//    @Test
+//    public void testDeviceSyncRepresentationFromDevice() {
+//        ITopologyService mockTopology = makeMockTopologyAllPortsAp();
+//        replay(mockTopology);
+//        deviceManager.topology = mockTopology;
+//
+//        deviceManager.entityClassifier = new MockEntityClassifier();
+//
+//        //**************************************
+//        // Test 1: a single entity
+//        Entity e1 = new Entity(1L, (short)2, 3, 4L, 5, new Date(1000));
+//        Device d1 = deviceManager.learnDeviceByEntity(e1);
+//        assertEquals("Sanity check failed. Device doesn't have the expected " +
+//                     "entity class. Something with the test setup is strange",
+//                     "DefaultEntityClass", d1.getEntityClass().getName());
+//        assertEquals("Sanity check failed. Device doesn't have the expected " +
+//                     "entity class. Something with the test setup is strange",
+//                     EnumSet.of(DeviceField.MAC, DeviceField.VLAN),
+//                     d1.getEntityClass().getKeyFields());
+//
+//        Long deviceKey = d1.getDeviceKey();
+//        DeviceSyncRepresentation dsr1 = new DeviceSyncRepresentation(d1);
+//        assertEquals("DefaultEntityClass::00:00:00:00:00:01::[2]::",
+//                     dsr1.getKey());
+//        assertEquals(1, dsr1.getEntities().size());
+//        assertEquals(e1, dsr1.getEntities().get(0).asEntity());
+//
+//        //**************************************
+//        // Test 1b: same device, now with a second entity (no IP).
+//        // this second entity has a lastSeen time that is earlier than the
+//        // first entity
+//        Entity e1b = new Entity(1L, (short)2, null, 4L, 5, new Date(0));
+//        d1 = deviceManager.learnDeviceByEntity(e1b);
+//        assertEquals("Sanity check failed. Should still be same device but " +
+//                     "deviceKeys differs", deviceKey, d1.getDeviceKey());
+//        dsr1 = new DeviceSyncRepresentation(d1);
+//        assertEquals("DefaultEntityClass::00:00:00:00:00:01::[2]::",
+//                     dsr1.getKey());
+//        assertEquals(2, dsr1.getEntities().size());
+//        // Entities are ordered by their lastSeen time. e1b should come
+//        // before e1.
+//        assertEquals(e1, dsr1.getEntities().get(1).asEntity());
+//        assertEquals(e1b, dsr1.getEntities().get(0).asEntity());
+//
+//        //**************************************
+//        // Test 1c: same device with a third entity that does not have a
+//        // switch port. It should be added to the DeviceSyncRepresentation
+//        Entity e1c = new Entity(1L, (short)2, 33, null, null, new Date(2000));
+//        d1 = deviceManager.learnDeviceByEntity(e1c);
+//        assertEquals("Sanity check failed. Should still be same device but " +
+//                     "deviceKeys differs", deviceKey, d1.getDeviceKey());
+//        dsr1 = new DeviceSyncRepresentation(d1);
+//        assertEquals("DefaultEntityClass::00:00:00:00:00:01::[2]::",
+//                     dsr1.getKey());
+//        assertEquals(3, dsr1.getEntities().size());
+//        // Entities are ordered by their lastSeen time
+//        assertEquals(e1c, dsr1.getEntities().get(2).asEntity());
+//        assertEquals(e1, dsr1.getEntities().get(1).asEntity());
+//        assertEquals(e1b, dsr1.getEntities().get(0).asEntity());
+//
+//        //**************************************
+//        // Test 1d: same device with a fourth entity that has a different
+//        // attachment point and that is newer. Device should move and
+//        // non-attachment point entities should be removed (e1b). Although
+//        // e1 is non-attachment point it will remain because it has an IP
+//        Entity e1d = new Entity(1L, (short)2, 33, 4L, 6, new Date(3000));
+//        d1 = deviceManager.learnDeviceByEntity(e1d);
+//        assertEquals("Sanity check failed. Should still be same device but " +
+//                     "deviceKeys differs", deviceKey, d1.getDeviceKey());
+//        dsr1 = new DeviceSyncRepresentation(d1);
+//        assertEquals("DefaultEntityClass::00:00:00:00:00:01::[2]::",
+//                     dsr1.getKey());
+//        assertEquals(3, dsr1.getEntities().size());
+//        assertEquals(e1, dsr1.getEntities().get(0).asEntity());
+//        assertEquals(e1c, dsr1.getEntities().get(1).asEntity());
+//        assertEquals(e1d, dsr1.getEntities().get(2).asEntity());
+//
+//        d1 = null;
+//
+//
+//        //**************************************
+//        // Test 2: a second device with a different entity class. The
+//        // mock entity classifier will return an entity class where all
+//        // fields are keys if the DPID is > 10L
+//        Entity e2 = new Entity(2L, (short)23, 24, 11L, 1, new Date(0));
+//        Device d2 = deviceManager.learnDeviceByEntity(e2);
+//        DeviceSyncRepresentation dsr2 = new DeviceSyncRepresentation(d2);
+//        assertEquals("Sanity check failed. Device doesn't have the expected " +
+//                     "entity class. Something with the test setup is strange",
+//                     "TestEntityClass", d2.getEntityClass().getName());
+//        assertEquals("Sanity check failed. Device doesn't have the expected " +
+//                     "entity class. Something with the test setup is strange",
+//                     EnumSet.of(DeviceField.MAC, DeviceField.VLAN,
+//                                DeviceField.SWITCH, DeviceField.PORT),
+//                     d2.getEntityClass().getKeyFields());
+//        SwitchPort swp = new SwitchPort(11L, 1, null);
+//        assertEquals("TestEntityClass::00:00:00:00:00:02::[23]::[" +
+//                     swp.toString() + "]::",
+//                     dsr2.getKey());
+//    }
+//
+//    /* interate through all entries in the sync store and return them as
+//     * list. We don't return the key from the store however, we assert
+//     * that the key from the store matches the key in the representation.
+//     * If we have a null value (tombstone) we simply add the null value to
+//     * the list to return.
+//     */
+//    private List<DeviceSyncRepresentation> getEntriesFromStore()
+//            throws Exception {
+//        List<DeviceSyncRepresentation> entries =
+//                new ArrayList<DeviceSyncRepresentation>();
+//        IClosableIterator<Entry<String, Versioned<DeviceSyncRepresentation>>> iter =
+//                storeClient.entries();
+//        try {
+//            while(iter.hasNext()) {
+//                Entry<String, Versioned<DeviceSyncRepresentation>> entry =
+//                        iter.next();
+//                DeviceSyncRepresentation dsr = entry.getValue().getValue();
+//                if (dsr != null)
+//                    assertEquals(entry.getKey(), dsr.getKey());
+//                entries.add(dsr);
+//            }
+//        } finally {
+//            if (iter != null)
+//                iter.close();
+//        }
+//        return entries;
+//    }
+//
+//    /*
+//     * assert whether the given Entity expected is equals to the given
+//     * SyncEntity actual. This method also compares the times (lastSeen,
+//     * activeSince). Entity.equals will not do that!
+//     */
+//    private static void assertEntityEquals(Entity expected, SyncEntity actual) {
+//        assertNotNull(actual);
+//        assertNotNull(expected);
+//        Entity actualEntity = actual.asEntity();
+//        assertEquals("entityFields", expected, actualEntity);
+//        assertEquals("lastSeenTimestamp",
+//                     expected.getLastSeenTimestamp(),
+//                     actualEntity.getLastSeenTimestamp());
+//        assertEquals("activeSince",
+//                     expected.getActiveSince(), actualEntity.getActiveSince());
+//    }
+//
+//    /* This test tests the normal operation as master when we write to the sync
+//     * store or delete from the store.
+//     */
+//    @Test
+//    public void testWriteToSyncStore() throws Exception {
+//        int syncStoreIntervalMs = 50;
+//        ITopologyService mockTopology = makeMockTopologyAllPortsAp();
+//        replay(mockTopology);
+//        deviceManager.topology = mockTopology;
+//        deviceManager.setSyncStoreWriteInterval(syncStoreIntervalMs);
+//
+//        Entity e1a = new Entity(1L, (short)2, 3, 4L, 5, new Date(1000));
+//        e1a.setActiveSince(new Date(0));
+//        deviceManager.learnDeviceByEntity(e1a);
+//
+//        //storeClient.put("FooBar", new DeviceSyncRepresentation());
+//
+//        List<DeviceSyncRepresentation> entries = getEntriesFromStore();
+//        assertEquals(1, entries.size());
+//        DeviceSyncRepresentation dsr1 = entries.get(0);
+//        assertEquals(1, dsr1.getEntities().size());
+//        assertEntityEquals(e1a, dsr1.getEntities().get(0));
+//
+//        // Same entity but newer timestamp. Since the device hasn't changed,
+//        // only the timestamp is updated and the write should be throttled.
+//        Entity e1b = new Entity(1L, (short)2, 3, 4L, 5, new Date(2000));
+//        e1b.setActiveSince(new Date(0));
+//        deviceManager.learnDeviceByEntity(e1a);
+//        entries = getEntriesFromStore();
+//        assertEquals(1, entries.size());
+//        dsr1 = entries.get(0);
+//        assertEquals(1, dsr1.getEntities().size());
+//        assertEntityEquals(e1a, dsr1.getEntities().get(0)); //e1a not e1b !!!
+//
+//        // Wait for the write interval to expire then write again.
+//        Thread.sleep(syncStoreIntervalMs+5);
+//        Entity e1c = new Entity(1L, (short)2, 3, 4L, 5, new Date(3000));
+//        e1c.setActiveSince(new Date(0));
+//        deviceManager.learnDeviceByEntity(e1c);
+//        entries = getEntriesFromStore();
+//        assertEquals(1, entries.size());
+//        dsr1 = entries.get(0);
+//        assertEquals(1, dsr1.getEntities().size());
+//        assertEntityEquals(e1c, dsr1.getEntities().get(0)); // e1c !!
+//
+//        // Entity for same device but with different IP. should be added
+//        // immediately
+//        Entity e1d = new Entity(1L, (short)2, 33, 4L, 5, new Date(4000));
+//        e1d.setActiveSince(new Date(0));
+//        deviceManager.learnDeviceByEntity(e1d);
+//        entries = getEntriesFromStore();
+//        assertEquals(1, entries.size());
+//        dsr1 = entries.get(0);
+//        assertEquals(2, dsr1.getEntities().size());
+//        assertEntityEquals(e1c, dsr1.getEntities().get(0)); // e1c !!
+//        assertEntityEquals(e1d, dsr1.getEntities().get(1)); // e1d !!
+//
+//        // Entity for same device with new switch port ==> moved ==> write
+//        // update immediately without throttle.
+//        // Note: the previous entities will still be there because they have
+//        // IPs (even though they aren't for the current attachment point)
+//        Entity e1e = new Entity(1L, (short)2, 33, 4L, 6, new Date(5000));
+//        e1e.setActiveSince(new Date(0));
+//        deviceManager.learnDeviceByEntity(e1e);
+//        entries = getEntriesFromStore();
+//        assertEquals(1, entries.size());
+//        dsr1 = entries.get(0);
+//        assertEquals(3, dsr1.getEntities().size());
+//        assertEntityEquals(e1c, dsr1.getEntities().get(0));
+//        assertEntityEquals(e1d, dsr1.getEntities().get(1));
+//        assertEntityEquals(e1e, dsr1.getEntities().get(2));
+//
+//        // Add a second device
+//        Entity e2 = new Entity(2L, null, null, 5L, 5, new Date());
+//        deviceManager.learnDeviceByEntity(e2);
+//        entries = getEntriesFromStore();
+//        assertEquals(2, entries.size());
+//        for (DeviceSyncRepresentation dsr: entries) {
+//            // This is a kinda ugly way to ensure we have the two
+//            // devices we need..... but it will work for now
+//            if (dsr.getKey().contains("::00:00:00:00:00:01::")) {
+//                assertEquals(3, dsr.getEntities().size());
+//                assertEntityEquals(e1c, dsr.getEntities().get(0));
+//                assertEntityEquals(e1d, dsr.getEntities().get(1));
+//                assertEntityEquals(e1e, dsr.getEntities().get(2));
+//            } else if (dsr.getKey().contains("::00:00:00:00:00:02::")) {
+//                assertEquals(1, dsr.getEntities().size());
+//                assertEntityEquals(e2, dsr.getEntities().get(0));
+//            } else {
+//                fail("Unknown entry in store: " + dsr);
+//            }
+//        }
+//
+//
+//        // Run entity cleanup. Since we've used phony time stamps for
+//        // device 1 its entities should be cleared and the device should be
+//        // removed from the store. Device 2 should remain in the store.
+//        deviceManager.cleanupEntities();
+//        entries = getEntriesFromStore();
+//        assertEquals(2, entries.size());
+//        for (DeviceSyncRepresentation dsr: entries) {
+//            if (dsr == null) {
+//                // pass
+//            } else if (dsr.getKey().contains("::00:00:00:00:00:02::")) {
+//                assertEquals(1, dsr.getEntities().size());
+//                assertEntityEquals(e2, dsr.getEntities().get(0));
+//            } else {
+//                fail("Unknown entry in store: " + dsr);
+//            }
+//        }
+//    }
+//
+//
+//    private void assertDeviceIps(Integer[] expected, IDevice d) {
+//        List<Integer> expectedList = Arrays.asList(expected);
+//        Collections.sort(expectedList);
+//        List<Integer> actualList = Arrays.asList(d.getIPv4Addresses());
+//        Collections.sort(actualList);
+//        assertEquals(expectedList, actualList);
+//    }
+//
+//    private IDevice getSingleDeviceFromDeviceManager(long mac) {
+//        Iterator<? extends IDevice> diter =
+//                deviceManager.queryDevices(mac, null, null, null, null);
+//        assertTrue("Query didn't return a device", diter.hasNext());
+//        IDevice d = diter.next();
+//        assertFalse("Query returned more than one device", diter.hasNext());
+//        return d;
+//    }
+//
+//    @Test
+//    public void testToMaster() throws Exception {
+//        int syncStoreWriteIntervalMs = 0;
+//        int initialSyncStoreConsolidateIntervalMs = 50;
+//        ITopologyService mockTopology = makeMockTopologyAllPortsAp();
+//        replay(mockTopology);
+//        deviceManager.topology = mockTopology;
+//        // We want an EntityClassifier that has switch/port as key fields
+//        deviceManager.entityClassifier = new MockEntityClassifier();
+//        deviceManager.setSyncStoreWriteInterval(syncStoreWriteIntervalMs);
+//        deviceManager.setInitialSyncStoreConsolidateMs(initialSyncStoreConsolidateIntervalMs);
+//
+//        // Add Device1 with two entities with two different IPs
+//        Entity e1a = new Entity(1L, null, 3, 4L, 5, new Date(1000));
+//        Entity e1b = new Entity(1L, null, 33,  4L, 5, new Date(2000));
+//        Device d1 = deviceManager.allocateDevice(1L, e1a,
+//                                                 DefaultEntityClassifier.entityClass);
+//        d1 = deviceManager.allocateDevice(d1, e1b, -1);
+//        DeviceSyncRepresentation dsr = new DeviceSyncRepresentation(d1);
+//        storeClient.put(dsr.getKey(), dsr);
+//
+//        // Add Device2 with different switch-ports. Only the most recent
+//        // one should be the attachment point
+//        Entity e2a = new Entity(2L, null, null, 4L, 4, new Date(1000));
+//        Entity e2b = new Entity(2L, null, null, 4L, 5, new Date(2000));
+//        Device d2 = deviceManager.allocateDevice(2L, e2a,
+//                                                 DefaultEntityClassifier.entityClass);
+//        d2 = deviceManager.allocateDevice(d2, e2b, -1);
+//        d2.updateAttachmentPoint(4L, (short)5,
+//                                 e2b.getLastSeenTimestamp().getTime());
+//        SwitchPort swp = new SwitchPort(4L, 5);
+//        SwitchPort[] aps = d2.getAttachmentPoints();
+//        // sanity check
+//        assertArrayEquals("Sanity check: should only have AP(4L,5)",
+//                          new SwitchPort[] {swp}, aps);
+//        dsr = new DeviceSyncRepresentation(d2);
+//        storeClient.put(dsr.getKey(), dsr);
+//
+//        // Add a tombstone entry to the store to make sure we don't trip a
+//        // NPE
+//        dsr = null;
+//        Versioned<DeviceSyncRepresentation> versionedDsr =
+//                storeClient.get("FooBar");
+//        storeClient.put("FooBar", versionedDsr);
+//
+//        deviceManager.getHAListener().transitionToMaster();
+//
+//        // Query for the Device1. Make sure we have the two IPs we stored.
+//        IDevice d = getSingleDeviceFromDeviceManager(1L);
+//        assertDeviceIps(new Integer[] {3, 33}, d);
+//        assertArrayEquals(new Short[] { Ethernet.VLAN_UNTAGGED }, d.getVlanId());
+//        swp = new SwitchPort(4L, 5);
+//        assertArrayEquals(new SwitchPort[] { swp }, d.getAttachmentPoints());
+//
+//        // Query for Device2. Make sure we only have the more recent AP
+//        // Query for the Device1. Make sure we have the two IPs we stored.
+//        d = getSingleDeviceFromDeviceManager(2L);
+//        assertArrayEquals(new Integer[0], d.getIPv4Addresses());
+//        assertArrayEquals(new Short[] { Ethernet.VLAN_UNTAGGED }, d.getVlanId());
+//        swp = new SwitchPort(4L, 5);
+//        assertArrayEquals(new SwitchPort[] { swp }, d.getAttachmentPoints());
+//
+//        //----------------------------
+//        // add another entry device to the store. since device manager is
+//        // already master we won't read this device and it should be
+//        // removed from the store by the consolidate task
+//        Entity e3 = new Entity(3L, null, null, 1L, 1, null);
+//        dsr = new DeviceSyncRepresentation();
+//        dsr.setKey("Device3");
+//        dsr.setEntities(Collections.singletonList(new SyncEntity(e3)));
+//        storeClient.put(dsr.getKey(), dsr);
+//
+//        // make sure it's in the store
+//        List<DeviceSyncRepresentation> entries = getEntriesFromStore();
+//        boolean found = false;
+//        for (DeviceSyncRepresentation entry: entries) {
+//            if (entry!=null && entry.getKey().equals("Device3"))
+//                found = true;
+//        }
+//        assertTrue("Device3 not in store. Entries in store: " + entries, found);
+//        // make sure it's not in DevManager
+//        Iterator<? extends IDevice> diter =
+//                deviceManager.queryDevices(3L, null, null, null, null);
+//        assertFalse("Device3 found in DeviceManager. Should be there",
+//                    diter.hasNext());
+//
+//        // Wait for consolidate
+//        Thread.sleep(initialSyncStoreConsolidateIntervalMs + 5);
+//        // make sure it's in NOT the store
+//        entries = getEntriesFromStore();
+//        found = false;
+//        for (DeviceSyncRepresentation entry: entries) {
+//            if (entry!=null && entry.getKey().equals("Device3"))
+//                found = true;
+//        }
+//        assertFalse("Device3 not is still in the store. Entries in store: "
+//                    + entries, found);
+//        // make sure it's not in DevManager
+//        diter = deviceManager.queryDevices(3L, null, null, null, null);
+//        assertFalse("Device3 found in DeviceManager. Should be there",
+//                    diter.hasNext());
+//    }
+//
+//
+//    @Test
+//    public void testConsolitateStore() throws Exception {
+//        int syncStoreInternalMs = 0;
+//        ITopologyService mockTopology = makeMockTopologyAllPortsAp();
+//        replay(mockTopology);
+//        deviceManager.topology = mockTopology;
+//        // We want an EntityClassifier that has switch/port as key fields
+//        deviceManager.entityClassifier = new MockEntityClassifier();
+//        deviceManager.setSyncStoreWriteInterval(syncStoreInternalMs);
+//
+//        // Add Device1 with two entities to store and let device manager
+//        // learn
+//        Entity e1a = new Entity(1L, null, null, 4L, 5, new Date(1000));
+//        Entity e1b = new Entity(1L, null, 3,  4L, 5, new Date(2000));
+//        Device d1 = deviceManager.learnDeviceByEntity(e1a);
+//        deviceManager.learnDeviceByEntity(e1b);
+//        String dev1Key = DeviceSyncRepresentation.computeKey(d1);
+//
+//
+//        // Add a second device to the store but do NOT add to device manager
+//        Entity e2 = new Entity(2L, null, null, 5L, 5, new Date());
+//        Device d2 = deviceManager.allocateDevice(42L, e2,
+//                                                 DefaultEntityClassifier.entityClass);
+//        DeviceSyncRepresentation dsr = new DeviceSyncRepresentation(d2);
+//        storeClient.put(dsr.getKey(), dsr);
+//        String dev2Key = DeviceSyncRepresentation.computeKey(d2);
+//
+//        // Make sure we have two devices in the store
+//        List<DeviceSyncRepresentation> entries = getEntriesFromStore();
+//        assertEquals(2, entries.size());
+//
+//        deviceManager.scheduleConsolidateStoreNow();
+//        Thread.sleep(25); // give the scheduler time to run the task
+//
+//        // We should still have two entries, however one of them will be a
+//        // tombstone
+//        entries = getEntriesFromStore();
+//        assertEquals(2, entries.size());
+//
+//        // Device 1 should still be in store
+//        Versioned<DeviceSyncRepresentation> versioned =
+//                storeClient.get(dev1Key);
+//        dsr = versioned.getValue();
+//        assertNotNull(dsr);
+//        assertEquals(2, dsr.getEntities().size());
+//        assertEntityEquals(e1a, dsr.getEntities().get(0));
+//        assertEntityEquals(e1b, dsr.getEntities().get(1));
+//
+//        // Device2 should be gone
+//        versioned = storeClient.get(dev2Key);
+//        assertNull(versioned.getValue());
+//
+//        // Run consolitate again. This time we check that tombstones in
+//        // the store are handled correctly
+//        deviceManager.scheduleConsolidateStoreNow();
+//        Thread.sleep(25); // give the scheduler time to run the task
+//
+//        // Now write a device to the store that doesn't have any switch-port
+//        // it should be removed
+//        Entity e3 = new Entity(3L, null, null, null, null, null);
+//        dsr.setKey("Device3");
+//        dsr.setEntities(Collections.singletonList(new SyncEntity(e3)));
+//        storeClient.put(dsr.getKey(), dsr);
+//
+//        // Run consolitate again. This time we check that tombstones in
+//        // the store are handled correctly
+//        deviceManager.scheduleConsolidateStoreNow();
+//        Thread.sleep(25); // give the scheduler time to run the task
+//        versioned = storeClient.get("Device3");
+//        assertNull(versioned.getValue());
+//
+//    }
+//
+// }
diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndexTest.java b/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndexTest.java
new file mode 100644 (file)
index 0000000..a2a1004
--- /dev/null
@@ -0,0 +1,175 @@
+/*
+ * Copyright (c) 2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.internal;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+import org.junit.Test;
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
+
+/**
+ *
+ * @author gregor
+ *
+ */
+public class DeviceUniqueIndexTest extends TestCase {
+    protected Entity e1a;
+    protected Entity e1b;
+    protected Device d1;
+    protected Entity e2;
+    protected Entity e2alt;
+    protected Entity e3;
+    protected Entity e3_ip;
+    protected Entity e4;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        Node n1 = new Node(Node.NodeIDType.OPENFLOW, Long.valueOf(1L));
+        NodeConnector n1_1 = new NodeConnector(NodeConnectorIDType.OPENFLOW,
+                Short.valueOf((short) 1), n1);
+        e1a = new Entity(1L, (short) 1, 1, n1_1, new Date());
+        e1b = new Entity(1L, (short) 2, 1, n1_1, new Date());
+        List<Entity> d1Entities = new ArrayList<Entity>(2);
+        d1Entities.add(e1a);
+        d1Entities.add(e1b);
+        d1 = new Device(null, Long.valueOf(1), null, null, null, d1Entities,
+                null);
+
+        Node n2 = new Node(Node.NodeIDType.OPENFLOW, Long.valueOf(2L));
+        NodeConnector n2_2 = new NodeConnector(NodeConnectorIDType.OPENFLOW,
+                Short.valueOf((short) 2), n2);
+        Node n3 = new Node(Node.NodeIDType.OPENFLOW, Long.valueOf(3L));
+        NodeConnector n3_3 = new NodeConnector(NodeConnectorIDType.OPENFLOW,
+                Short.valueOf((short) 3), n3);
+
+        // e2 and e2 alt match in MAC and VLAN
+        e2 = new Entity(2L, (short) 2, 2, n2_2, new Date());
+        e2alt = new Entity(2, (short) 2, null, null, null);
+
+        // IP is null
+        e3 = new Entity(3L, (short) 3, null, n3_3, new Date());
+        e3_ip = new Entity(3L, (short) 3, 3, n3_3, new Date());
+
+        // IP and switch and port are null
+        e4 = new Entity(4L, (short) 4, null, null, new Date());
+    }
+
+    /*
+     * Checks that the iterator it returns the elements in the Set expected
+     * Doesn't check how often an element is returned as long it's at least once
+     */
+    protected void verifyIterator(Set<Long> expected, Iterator<Long> it) {
+        HashSet<Long> actual = new HashSet<Long>();
+        while (it.hasNext()) {
+            actual.add(it.next());
+        }
+        assertEquals(expected, actual);
+    }
+
+    @Test
+    public void testDeviceUniqueIndex() {
+        DeviceUniqueIndex idx1 = new DeviceUniqueIndex(EnumSet.of(
+                DeviceField.MAC, DeviceField.VLAN));
+
+        idx1.updateIndex(d1, d1.getDeviceKey());
+        idx1.updateIndex(e2, 2L);
+
+        // -------------
+        // Test findByEntity lookups
+        assertEquals(Long.valueOf(1L), idx1.findByEntity(e1a));
+        assertEquals(Long.valueOf(1L), idx1.findByEntity(e1b));
+        assertEquals(Long.valueOf(2L), idx1.findByEntity(e2));
+        // we didn't add e2alt but since they key fields are the same we
+        // should find it
+        assertEquals(Long.valueOf(2L), idx1.findByEntity(e2alt));
+        assertEquals(null, idx1.findByEntity(e3));
+        assertEquals(null, idx1.findByEntity(e4));
+
+        // -------------
+        // Test getAll()
+        HashSet<Long> expectedKeys = new HashSet<Long>();
+        expectedKeys.add(1L);
+        expectedKeys.add(2L);
+        verifyIterator(expectedKeys, idx1.getAll());
+
+        // -------------
+        // Test queryByEntity()
+        verifyIterator(Collections.<Long> singleton(1L),
+                idx1.queryByEntity(e1a));
+        verifyIterator(Collections.<Long> singleton(1L),
+                idx1.queryByEntity(e1b));
+        verifyIterator(Collections.<Long> singleton(2L), idx1.queryByEntity(e2));
+        verifyIterator(Collections.<Long> singleton(2L),
+                idx1.queryByEntity(e2alt));
+        assertEquals(false, idx1.queryByEntity(e3).hasNext());
+        assertEquals(false, idx1.queryByEntity(e3).hasNext());
+
+        // -------------
+        // Test removal
+        idx1.removeEntity(e1a, 42L); // No-op. e1a isn't mapped to this key
+        assertEquals(Long.valueOf(1L), idx1.findByEntity(e1a));
+        idx1.removeEntity(e1a, 1L);
+        assertEquals(null, idx1.findByEntity(e1a));
+        assertEquals(Long.valueOf(1L), idx1.findByEntity(e1b));
+        assertEquals(Long.valueOf(2L), idx1.findByEntity(e2));
+        idx1.removeEntity(e2);
+        assertEquals(null, idx1.findByEntity(e2));
+        assertEquals(Long.valueOf(1L), idx1.findByEntity(e1b));
+
+        // -------------
+        // Test null keys
+        DeviceUniqueIndex idx2 = new DeviceUniqueIndex(EnumSet.of(
+                DeviceField.IPV4, DeviceField.SWITCHPORT));
+        // only one key field is null
+        idx2.updateIndex(e3, 3L);
+        assertEquals(Long.valueOf(3L), idx2.findByEntity(e3));
+        assertEquals(null, idx2.findByEntity(e3_ip));
+        // all key fields are null
+        idx2.updateIndex(e4, 4L);
+        assertEquals(null, idx2.findByEntity(e4));
+        Device d4 = new Device(null, 4L, null, null, null,
+                Collections.<Entity> singleton(e4), null);
+        idx2.updateIndex(d4, 4L);
+        assertEquals(null, idx2.findByEntity(e4));
+
+        // -------------
+        // entity already exists with different deviceKey
+        DeviceUniqueIndex idx3 = new DeviceUniqueIndex(EnumSet.of(
+                DeviceField.MAC, DeviceField.VLAN));
+        idx3.updateIndex(e1a, 42L);
+        assertEquals(false, idx3.updateIndex(d1, 1L));
+        // TODO: shouldn't this fail as well so that the behavior
+        // is consistent?
+        idx3.updateIndex(e1a, 1L);
+        // anyways. We can now add d1 ;-)
+        assertEquals(true, idx3.updateIndex(d1, 1L));
+    }
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDevice.java b/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDevice.java
new file mode 100644 (file)
index 0000000..03f0598
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2011,2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.TreeSet;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IEntityClass;
+import org.opendaylight.controller.hosttracker.SwitchPort;
+import org.opendaylight.controller.hosttracker.internal.AttachmentPoint;
+import org.opendaylight.controller.hosttracker.internal.Device;
+import org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl;
+
+/**
+ * This mock device removes the dependency on topology and a parent device
+ * manager and simply assumes all its entities are current and correct
+ */
+public class MockDevice extends Device {
+
+    public MockDevice(DeviceManagerImpl deviceManager, Long deviceKey,
+            Entity entity, IEntityClass entityClass) {
+        super(deviceManager, deviceKey, entity, entityClass);
+    }
+
+    public MockDevice(Device device, Entity newEntity, int insertionpoint) {
+        super(device, newEntity, insertionpoint);
+    }
+
+    public MockDevice(DeviceManagerImpl deviceManager, Long deviceKey,
+            List<AttachmentPoint> aps, List<AttachmentPoint> trueAPs,
+            Collection<Entity> entities, IEntityClass entityClass) {
+        super(deviceManager, deviceKey, null, aps, trueAPs, entities,
+                entityClass);
+    }
+
+    @Override
+    public Integer[] getIPv4Addresses() {
+        TreeSet<Integer> vals = new TreeSet<Integer>();
+        for (Entity e : entities) {
+            if (e.getIpv4Address() == null)
+                continue;
+            vals.add(e.getIpv4Address());
+        }
+
+        return vals.toArray(new Integer[vals.size()]);
+    }
+
+    @Override
+    public SwitchPort[] getAttachmentPoints() {
+        ArrayList<SwitchPort> vals = new ArrayList<SwitchPort>(entities.length);
+        for (Entity e : entities) {
+            if (e.getPort() != null
+                    && deviceManager.isValidAttachmentPoint(e.getPort())) {
+                SwitchPort sp = new SwitchPort(e.getPort());
+                vals.add(sp);
+            }
+        }
+        return vals.toArray(new SwitchPort[vals.size()]);
+    }
+
+    @Override
+    public String toString() {
+        return "MockDevice [getEntityClass()=" + getEntityClass()
+                + ", getEntities()=" + Arrays.toString(getEntities()) + "]";
+    }
+
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDeviceManager.java b/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDeviceManager.java
new file mode 100644 (file)
index 0000000..af2feb1
--- /dev/null
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2013 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.test;
+
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDevice;
+import org.opendaylight.controller.hosttracker.IDeviceListener;
+import org.opendaylight.controller.hosttracker.IEntityClass;
+import org.opendaylight.controller.hosttracker.IEntityClassifierService;
+import org.opendaylight.controller.hosttracker.internal.AttachmentPoint;
+import org.opendaylight.controller.hosttracker.internal.Device;
+import org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl;
+import org.opendaylight.controller.sal.core.NodeConnector;
+
+/**
+ * Mock device manager useful for unit tests
+ *
+ * @author readams
+ */
+public class MockDeviceManager extends DeviceManagerImpl {
+    /**
+     * Set a new IEntityClassifier Use this as a quick way to use a particular
+     * entity classifier in a single test without having to setup the full
+     * FloodlightModuleContext again.
+     *
+     * @param ecs
+     */
+    public void setEntityClassifier(IEntityClassifierService ecs) {
+        this.entityClassifier = ecs;
+        // setSyncServiceIfNotSet(new MockSyncService());
+        this.start();
+    }
+
+    /**
+     * Learn a device using the given characteristics.
+     *
+     * @param macAddress
+     *            the MAC
+     * @param vlan
+     *            the VLAN (can be null)
+     * @param ipv4Address
+     *            the IP (can be null)
+     * @param switchDPID
+     *            the attachment point switch DPID (can be null)
+     * @param switchPort
+     *            the attachment point switch port (can be null)
+     * @param processUpdates
+     *            if false, will not send updates. Note that this method is not
+     *            thread safe if this is false
+     * @return the device, either new or not
+     */
+    public IDevice learnEntity(long macAddress, Short vlan,
+            Integer ipv4Address, NodeConnector port, boolean processUpdates) {
+        List<IDeviceListener> listeners = deviceListeners.getOrderedListeners();
+        if (!processUpdates) {
+            deviceListeners.clearListeners();
+        }
+
+        if (vlan != null && vlan.shortValue() <= 0)
+            vlan = null;
+        if (ipv4Address != null && ipv4Address == 0)
+            ipv4Address = null;
+        IDevice res = learnDeviceByEntity(new Entity(macAddress, vlan,
+                ipv4Address, port, new Date()));
+        // Restore listeners
+        if (listeners != null) {
+            for (IDeviceListener listener : listeners) {
+                deviceListeners.addListener("device", listener);
+            }
+        }
+        return res;
+    }
+
+    @Override
+    public void deleteDevice(Device device) {
+        super.deleteDevice(device);
+    }
+
+    /**
+     * Learn a device using the given characteristics.
+     *
+     * @param macAddress
+     *            the MAC
+     * @param vlan
+     *            the VLAN (can be null)
+     * @param ipv4Address
+     *            the IP (can be null)
+     * @param switchDPID
+     *            the attachment point switch DPID (can be null)
+     * @param switchPort
+     *            the attachment point switch port (can be null)
+     * @return the device, either new or not
+     */
+    public IDevice learnEntity(long macAddress, Short vlan,
+            Integer ipv4Address, NodeConnector port) {
+        return learnEntity(macAddress, vlan, ipv4Address, port, true);
+    }
+
+    @Override
+    protected Device allocateDevice(Long deviceKey, Entity entity,
+            IEntityClass entityClass) {
+        return new MockDevice(this, deviceKey, entity, entityClass);
+    }
+
+    @Override
+    protected Device allocateDevice(Long deviceKey, String dhcpClientName,
+            List<AttachmentPoint> aps, List<AttachmentPoint> trueAPs,
+            Collection<Entity> entities, IEntityClass entityClass) {
+        return new MockDevice(this, deviceKey, aps, trueAPs, entities,
+                entityClass);
+    }
+
+    @Override
+    protected Device allocateDevice(Device device, Entity entity,
+            int insertionpoint) {
+        return new MockDevice(device, entity, insertionpoint);
+    }
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifier.java b/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifier.java
new file mode 100644 (file)
index 0000000..e9f919e
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2013 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.test;
+
+import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.MAC;
+import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.SWITCHPORT;
+import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.VLAN;
+
+import java.util.EnumSet;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDeviceService;
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+import org.opendaylight.controller.hosttracker.IEntityClass;
+import org.opendaylight.controller.hosttracker.internal.DefaultEntityClassifier;
+
+/**
+ * A simple IEntityClassifier. Useful for tests that need IEntityClassifiers and
+ * IEntityClass'es with switch and/or port key fields
+ */
+public class MockEntityClassifier extends DefaultEntityClassifier {
+    public static class TestEntityClass implements IEntityClass {
+        @Override
+        public EnumSet<DeviceField> getKeyFields() {
+            return EnumSet.of(MAC, VLAN, SWITCHPORT);
+        }
+
+        @Override
+        public String getName() {
+            return "TestEntityClass";
+        }
+    }
+
+    public static IEntityClass testEC = new MockEntityClassifier.TestEntityClass();
+
+    @Override
+    public IEntityClass classifyEntity(Entity entity) {
+        if (((Long) entity.getPort().getNode().getID()) >= 10L) {
+            return testEC;
+        }
+        return DefaultEntityClassifier.entityClass;
+    }
+
+    @Override
+    public EnumSet<IDeviceService.DeviceField> getKeyFields() {
+        return EnumSet.of(MAC, VLAN, SWITCHPORT);
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifierMac.java b/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifierMac.java
new file mode 100644 (file)
index 0000000..436e6fa
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2013 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.test;
+
+import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.MAC;
+import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.SWITCHPORT;
+import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.VLAN;
+
+import java.util.EnumSet;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDeviceService;
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+import org.opendaylight.controller.hosttracker.IEntityClass;
+import org.opendaylight.controller.hosttracker.internal.DefaultEntityClassifier;
+
+/**
+ * A simple IEntityClassifier. Useful for tests that need an IEntityClassifier
+ * with switch/port as key fields.
+ */
+public class MockEntityClassifierMac extends DefaultEntityClassifier {
+    public static class TestEntityClassMac implements IEntityClass {
+        protected String name;
+
+        public TestEntityClassMac(String name) {
+            this.name = name;
+        }
+
+        @Override
+        public EnumSet<DeviceField> getKeyFields() {
+            return EnumSet.of(MAC, VLAN);
+        }
+
+        @Override
+        public String getName() {
+            return name;
+        }
+    }
+
+    public static IEntityClass testECMac1 = new MockEntityClassifierMac.TestEntityClassMac(
+            "testECMac1");
+    public static IEntityClass testECMac2 = new MockEntityClassifierMac.TestEntityClassMac(
+            "testECMac2");
+
+    @Override
+    public IEntityClass classifyEntity(Entity entity) {
+        if (((Long) entity.getPort().getNode().getID()) == null) {
+            throw new IllegalArgumentException("Not all key fields specified."
+                    + " Required fields: " + getKeyFields());
+        } else if (((Long) entity.getPort().getNode().getID()) == 1L) {
+            return testECMac1;
+        } else if (((Long) entity.getPort().getNode().getID()) == 2L) {
+            return testECMac2;
+        } else if (((Long) entity.getPort().getNode().getID()) == -1L) {
+            return null;
+        }
+        return DefaultEntityClassifier.entityClass;
+    }
+
+    @Override
+    public EnumSet<IDeviceService.DeviceField> getKeyFields() {
+        return EnumSet.of(MAC, VLAN, SWITCHPORT);
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockFlexEntityClassifier.java b/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockFlexEntityClassifier.java
new file mode 100644 (file)
index 0000000..fe2dd30
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2013 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.hosttracker.test;
+
+import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.MAC;
+import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.SWITCHPORT;
+import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.VLAN;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.opendaylight.controller.hosttracker.Entity;
+import org.opendaylight.controller.hosttracker.IDeviceService;
+import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
+import org.opendaylight.controller.hosttracker.IEntityClass;
+import org.opendaylight.controller.hosttracker.internal.DefaultEntityClassifier;
+
+/**
+ * Extension to simple entity classifier to help in unit tests to provide table
+ * based multiple entity classification mock for reclassification tests
+ *
+ */
+public class MockFlexEntityClassifier extends DefaultEntityClassifier {
+    Map<Long, IEntityClass> switchEntities;
+    Map<Short, IEntityClass> vlanEntities;
+
+    public static class TestEntityClass implements IEntityClass {
+        String name;
+
+        public TestEntityClass(String name) {
+            this.name = name;
+        }
+
+        @Override
+        public EnumSet<DeviceField> getKeyFields() {
+            return EnumSet.of(MAC);
+        }
+
+        @Override
+        public String getName() {
+            return name;
+        }
+    }
+
+    public static IEntityClass defaultClass = new TestEntityClass("default");
+
+    public MockFlexEntityClassifier() {
+        switchEntities = new HashMap<Long, IEntityClass>();
+        vlanEntities = new HashMap<Short, IEntityClass>();
+    }
+
+    public IEntityClass createTestEntityClass(String name) {
+        return new TestEntityClass(name);
+    }
+
+    public void addSwitchEntity(Long dpid, IEntityClass entityClass) {
+        switchEntities.put(dpid, entityClass);
+    }
+
+    public void removeSwitchEntity(Long dpid) {
+        switchEntities.remove(dpid);
+    }
+
+    public void addVlanEntities(Short vlan, IEntityClass entityClass) {
+        vlanEntities.put(vlan, entityClass);
+    }
+
+    public void removeVlanEntities(Short vlan) {
+        vlanEntities.remove(vlan);
+    }
+
+    @Override
+    public IEntityClass classifyEntity(Entity entity) {
+        if (switchEntities.containsKey((Long) entity.getPort().getNode()
+                .getID()))
+            return switchEntities
+                    .get((Long) entity.getPort().getNode().getID());
+        if (vlanEntities.containsKey(entity.getVlan()))
+            return vlanEntities.get(entity.getVlan());
+        return defaultClass;
+    }
+
+    @Override
+    public EnumSet<IDeviceService.DeviceField> getKeyFields() {
+        return EnumSet.of(MAC, VLAN, SWITCHPORT);
+    }
+}
diff --git a/opendaylight/hosttracker_new/implementation/src/test/resources/logback.xml b/opendaylight/hosttracker_new/implementation/src/test/resources/logback.xml
new file mode 100644 (file)
index 0000000..5fa21fe
--- /dev/null
@@ -0,0 +1,13 @@
+<configuration scan="true">\r
+\r
+  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">\r
+    <encoder>\r
+      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n\r
+      </pattern>\r
+    </encoder>\r
+  </appender>\r
+\r
+  <root level="error">\r
+    <appender-ref ref="STDOUT" />\r
+  </root>\r
+</configuration>\r
index 6bafee0b2cdb053c09401f653dbbd5dcc56d3dbd..7061954e80e199b2a52c49eeace78ad27b9d4518 100644 (file)
@@ -56,7 +56,7 @@ public class Activator implements BundleActivator {
                         this.listener.logged(entry);
                     }
                 }
-                
+
                 /*
                  * Install the default exception handler so that the uncaught
                  * exceptions are handled by our customized handler. This new
@@ -65,13 +65,13 @@ public class Activator implements BundleActivator {
                  */
                 Thread.setDefaultUncaughtExceptionHandler(new org.opendaylight.
                         controller.logging.bridge.internal.UncaughtExceptionHandler());
-                
+
                 /*
                  * Install the Shutdown handler. This will intercept SIGTERM signal and
                  * close the system bundle. This allows for a graceful  closing of OSGI
                  * framework.
                  */
-                
+
                 Runtime.getRuntime().addShutdownHook(new shutdownHandler(context));
             } else {
                 this.log.error("Cannot register the LogListener because "
@@ -95,13 +95,13 @@ public class Activator implements BundleActivator {
         this.listener = null;
         this.log = null;
     }
-    
+
     private class shutdownHandler extends Thread {
         BundleContext bundlecontext;
         public shutdownHandler(BundleContext ctxt) {
                 this.bundlecontext = ctxt;
         }
-        
+
         public void run () {
             try {
                 this.bundlecontext.getBundle(0).stop();
@@ -109,7 +109,7 @@ public class Activator implements BundleActivator {
             } catch (BundleException e) {
                 log.debug("Bundle couldn't be stopped");
             }
-        }   
+        }
     }
 
 }
index 7c0835a9033b027381cc37f70d2d632468e1373a..56da363d3eaf6d748c4a4cdc0925710fe31f759e 100644 (file)
@@ -33,7 +33,7 @@
               org.opendaylight.controller.sal.authorization,
               org.opendaylight.controller.containermanager,
               org.opendaylight.controller.usermanager,
-              javax.servlet.http, 
+              javax.servlet.http,
               org.slf4j
             </Import-Package>
           </instructions>
index 7069ff041f6d5c8d1c7b33ca0f735287315d1f07..3fedd0c9f8ea9d4fe8d5a470ca603e3298776f0a 100644 (file)
@@ -9,11 +9,11 @@ import org.opendaylight.controller.usermanager.IUserManager;
 
 public class NorthboundUtils {
 
-    
+
     /**
      * Returns whether the current user has the required privilege on the
      * specified container
-     * 
+     *
      * @param userName
      *            The user name
      * @param containerName
@@ -21,21 +21,21 @@ public class NorthboundUtils {
      * @param required
      *            Operation to be performed - READ/WRITE
      * @param bundle
-     *            Class from where the function is invoked           
+     *            Class from where the function is invoked
      * @return The Status of the request, either Success or Unauthorized
      */
     public static boolean isAuthorized(String userName, String containerName,
             Privilege required,Object bundle) {
-        
+
          if (containerName.equals(GlobalConstants.DEFAULT.toString())) {
             IUserManager auth = (IUserManager) ServiceHelper.getGlobalInstance(
                     IUserManager.class, bundle);
-            
+
             switch (required) {
             case WRITE:
                 return (auth.getUserLevel(userName).ordinal() <= UserLevel.NETWORKADMIN.ordinal());
             case READ:
-                return (auth.getUserLevel(userName).ordinal() <= UserLevel.NETWORKOPERATOR.ordinal());                    
+                return (auth.getUserLevel(userName).ordinal() <= UserLevel.NETWORKOPERATOR.ordinal());
             default:
                 return false;
             }
@@ -56,5 +56,5 @@ public class NorthboundUtils {
         }
         return true;
     }
-    
+
 }
index a49d9f8265f4b0a9da8b24387a4a9d58337997f9..90bf6de1d67e13b542fb4d6a2e1a6896995d0e8e 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <enunciate label="full" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://enunciate.codehaus.org/schemas/enunciate-1.26.xsd">
-  
+
   <services>
     <rest defaultRestSubcontext="/controller/nb/v2/flow"/>
   </services>
index 0a873ca0651013728d404a71798d670ac8b03eb2..c7e9a771c1d71f7c7913e2c26b1e9fe11264979b 100644 (file)
@@ -24,7 +24,7 @@
             <version>0.5.0-SNAPSHOT</version>
           </dependency>
         </dependencies>
-      </plugin>    
+      </plugin>
       <plugin>
         <groupId>org.apache.felix</groupId>
         <artifactId>maven-bundle-plugin</artifactId>
@@ -43,7 +43,7 @@
               org.opendaylight.controller.northbound.commons.utils,
               org.opendaylight.controller.sal.authorization,
               org.opendaylight.controller.usermanager,
-                         com.sun.jersey.spi.container.servlet,                            
+                          com.sun.jersey.spi.container.servlet,
               javax.ws.rs,
               javax.ws.rs.core,
               javax.xml.bind.annotation,
@@ -70,7 +70,7 @@
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>switchmanager</artifactId>
       <version>0.4.0-SNAPSHOT</version>
-    </dependency>    
+    </dependency>
     <dependency>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>forwardingrulesmanager</artifactId>
       <version>${enunciate.version}</version>
     </dependency>
     <dependency>
-         <groupId>org.opendaylight.controller</groupId>
-         <artifactId>commons.northbound</artifactId>
-         <version>0.4.0-SNAPSHOT</version>
-       </dependency>
+          <groupId>org.opendaylight.controller</groupId>
+          <artifactId>commons.northbound</artifactId>
+          <version>0.4.0-SNAPSHOT</version>
+        </dependency>
     <dependency>
       <groupId>org.opendaylight.controller.thirdparty</groupId>
       <artifactId>com.sun.jersey.jersey-servlet</artifactId>
index f6a757ec2919133af9a2604505f89d7d347eecea..4b3761219ff6673f789dd870fa6852550a22c214 100644 (file)
@@ -21,22 +21,22 @@ import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class FlowConfigs {
-       @XmlElement
-       List<FlowConfig> flowConfig;
-       //To satisfy JAXB
-       private FlowConfigs() {
-               
-       }
-       
-       public FlowConfigs(List<FlowConfig> flowConfig) {
-               this.flowConfig = flowConfig;
-       }
-
-       public List<FlowConfig> getFlowConfig() {
-               return flowConfig;
-       }
-
-       public void setFlowConfig(List<FlowConfig> flowConfig) {
-               this.flowConfig = flowConfig;
-       }
+        @XmlElement
+        List<FlowConfig> flowConfig;
+        //To satisfy JAXB
+        private FlowConfigs() {
+
+        }
+
+        public FlowConfigs(List<FlowConfig> flowConfig) {
+                this.flowConfig = flowConfig;
+        }
+
+        public List<FlowConfig> getFlowConfig() {
+                return flowConfig;
+        }
+
+        public void setFlowConfig(List<FlowConfig> flowConfig) {
+                this.flowConfig = flowConfig;
+        }
 }
index 99452b4b21542b9a77a4dc73bbe83413e2fc1fc0..b419a9b29df1c25f5d044a279a085126457230f5 100644 (file)
@@ -48,7 +48,7 @@ import org.opendaylight.controller.switchmanager.ISwitchManager;
 
 /**
  * Flow Configuration Northbound API
- * 
+ *
  * <br>
  * <br>
  * Authentication scheme : <b>HTTP Basic</b><br>
@@ -60,7 +60,7 @@ import org.opendaylight.controller.switchmanager.ISwitchManager;
  * trusted authority.<br>
  * More info :
  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
- * 
+ *
  */
 @Path("/")
 public class FlowProgrammerNorthbound {
@@ -147,7 +147,7 @@ public class FlowProgrammerNorthbound {
 
     /**
      * Returns a list of Flows configured on the given container
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -177,7 +177,7 @@ public class FlowProgrammerNorthbound {
 
     /**
      * Returns a list of Flows configured on a Node in a given container
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -217,7 +217,7 @@ public class FlowProgrammerNorthbound {
     /**
      * Returns the flow configuration matching a human-readable name and nodeId
      * on a given Container.
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -266,7 +266,7 @@ public class FlowProgrammerNorthbound {
 
     /**
      * Add a flow configuration
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -330,9 +330,9 @@ public class FlowProgrammerNorthbound {
 
     /**
      * Delete a Flow configuration
-     * 
+     *
      * DELETE /flows/{containerName}/{nodeType}/{nodeId}/{name}
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -392,7 +392,7 @@ public class FlowProgrammerNorthbound {
 
     /**
      * Toggle a Flow configuration
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
index 83f7e4b35d89e9891ef99e0cebd38ec17d45b213..4cedf2df8975bd6414fd28920dcd8db5c41b3183 100644 (file)
@@ -1,51 +1,51 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
-  
-       <servlet>
-         <servlet-name>JAXRSFlowProgrammer</servlet-name>
-         <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
-         <init-param>
-           <param-name>javax.ws.rs.Application</param-name>
-           <param-value>org.opendaylight.controller.flowprogrammer.northbound.FlowProgrammerNorthboundRSApplication</param-value>
-         </init-param>
-         <load-on-startup>1</load-on-startup>
-       </servlet>
-       
-       <servlet-mapping>
-         <servlet-name>JAXRSFlowProgrammer</servlet-name>
-         <url-pattern>/*</url-pattern>
-       </servlet-mapping>
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
+
+        <servlet>
+          <servlet-name>JAXRSFlowProgrammer</servlet-name>
+          <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
+          <init-param>
+            <param-name>javax.ws.rs.Application</param-name>
+            <param-value>org.opendaylight.controller.flowprogrammer.northbound.FlowProgrammerNorthboundRSApplication</param-value>
+          </init-param>
+          <load-on-startup>1</load-on-startup>
+        </servlet>
+
+        <servlet-mapping>
+          <servlet-name>JAXRSFlowProgrammer</servlet-name>
+          <url-pattern>/*</url-pattern>
+        </servlet-mapping>
+
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>NB api</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>NB api</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
-    
     <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
-       
-       <login-config>
-               <auth-method>BASIC</auth-method>
-               <realm-name>opendaylight</realm-name>
-       </login-config>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
+
+        <login-config>
+                <auth-method>BASIC</auth-method>
+                <realm-name>opendaylight</realm-name>
+        </login-config>
 </web-app>
\ No newline at end of file
index 8f0d7e6ab8f9b5a865d4d0b5eabbc2e6c3220ae8..e0c7dcd2ac7a9e85bc293786b6fd8b1d606fa2cb 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <enunciate label="full" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://enunciate.codehaus.org/schemas/enunciate-1.26.xsd">
-  
+
   <services>
     <rest defaultRestSubcontext="/controller/nb/v2/host"/>
   </services>
index 853c54ec2c9f36c693f68095b1d30b361c5105ea..f0caa52d6396bf2bf97fd969475cbccb707aec43 100644 (file)
@@ -24,7 +24,7 @@
             <version>0.5.0-SNAPSHOT</version>
           </dependency>
         </dependencies>
-      </plugin>    
+      </plugin>
       <plugin>
         <groupId>org.apache.felix</groupId>
         <artifactId>maven-bundle-plugin</artifactId>
index a9f210e0eceebdad88e783640ae2bc120b6b7b31..dbc99d06e477bb238a5c49af13cade4dd30ae5dd 100644 (file)
@@ -56,7 +56,7 @@ import org.opendaylight.controller.sal.authorization.Privilege;
  * Location is represented by Host node connector which is essentially a logical
  * entity that represents a Switch/Port. A host is represented by it's
  * IP-address and mac-address.
- * 
+ *
  * <br>
  * <br>
  * Authentication scheme : <b>HTTP Basic</b><br>
@@ -68,7 +68,7 @@ import org.opendaylight.controller.sal.authorization.Privilege;
  * trusted authority.<br>
  * More info :
  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
- * 
+ *
  */
 
 @Path("/")
@@ -120,7 +120,7 @@ public class HostTrackerNorthbound {
     /**
      * Returns a list of all Hosts : both configured via PUT API and dynamically
      * learnt on the network.
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -135,7 +135,7 @@ public class HostTrackerNorthbound {
             @ResponseCode(code = 404, condition = "The containerName is not found"),
             @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
     public Hosts getActiveHosts(@PathParam("containerName") String containerName) {
+
         if (!NorthboundUtils.isAuthorized(
                 getUserName(), containerName, Privilege.READ, this)) {
             throw new UnauthorizedException(
@@ -154,7 +154,7 @@ public class HostTrackerNorthbound {
     /**
      * Returns a list of Hosts that are statically configured and are connected
      * to a NodeConnector that is down.
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -187,7 +187,7 @@ public class HostTrackerNorthbound {
 
     /**
      * Returns a host that matches the IP Address value passed as parameter.
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -236,7 +236,7 @@ public class HostTrackerNorthbound {
 
     /**
      * Add a Static Host configuration
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -320,7 +320,7 @@ public class HostTrackerNorthbound {
 
     /**
      * Delete a Static Host configuration
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -342,7 +342,7 @@ public class HostTrackerNorthbound {
     public Response deleteFlow(
             @PathParam(value = "containerName") String containerName,
             @PathParam(value = "networkAddress") String networkAddress) {
+
         if (!NorthboundUtils.isAuthorized(
                 getUserName(), containerName, Privilege.WRITE, this)) {
             throw new UnauthorizedException(
index 463b493536f8ebc71808046701c9b7de65d34be6..c9ada2aeedd528e615b756a562aa32e47b5e25fb 100644 (file)
@@ -21,18 +21,18 @@ import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class Hosts {
-       @XmlElement (name="host")
-       Set<HostNodeConnector> hostNodeConnector;
-       
-       public Hosts() {
-       }
-       public Hosts (Set<HostNodeConnector> hostNodeConnector) {
-               this.hostNodeConnector = hostNodeConnector;
-       }
-       public Set<HostNodeConnector> getHostNodeConnector() {
-               return hostNodeConnector;
-       }
-       public void setHostNodeConnector(Set<HostNodeConnector> hostNodeConnector) {
-               this.hostNodeConnector = hostNodeConnector;
-       }
+        @XmlElement (name="host")
+        Set<HostNodeConnector> hostNodeConnector;
+
+        public Hosts() {
+        }
+        public Hosts (Set<HostNodeConnector> hostNodeConnector) {
+                this.hostNodeConnector = hostNodeConnector;
+        }
+        public Set<HostNodeConnector> getHostNodeConnector() {
+                return hostNodeConnector;
+        }
+        public void setHostNodeConnector(Set<HostNodeConnector> hostNodeConnector) {
+                this.hostNodeConnector = hostNodeConnector;
+        }
 }
index 7eb940875a6b8af8366e4b4793418bcf3160149f..0fa8b95dd00368600f7cfcc26196b4eca07adda0 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
   <servlet>
     <servlet-name>JAXRSHostTracker</servlet-name>
     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
     <url-pattern>/*</url-pattern>
   </servlet-mapping>
 
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>NB api</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>NB api</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
-       <login-config>
-               <auth-method>BASIC</auth-method>
-               <realm-name>opendaylight</realm-name>
-       </login-config>
+        <login-config>
+                <auth-method>BASIC</auth-method>
+                <realm-name>opendaylight</realm-name>
+        </login-config>
 </web-app>
\ No newline at end of file
index aa4469e452f32ac793a1027724a4df98a289c97e..90acc8c59f0e9358a1bd735107c5093afcaa1988 100644 (file)
       <artifactId>jersey-core</artifactId>
       <version>${jersey.version}</version>
     </dependency>
-    <!-- <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-servlet</artifactId> 
+    <!-- <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-servlet</artifactId>
       <version>${jersey.version}</version> </dependency> -->
     <dependency>
       <groupId>com.sun.jersey</groupId>
 
   </dependencies>
 </project>
-
index 24eb3d7a4c0933380c2ed5914e8281c6f6d16265..103a515607a49b043475ca59925c545d6d439586 100644 (file)
@@ -41,11 +41,9 @@ import org.opendaylight.controller.sal.core.UpdateType;
 import org.opendaylight.controller.switchmanager.IInventoryListener;
 import org.opendaylight.controller.usermanager.IUserManager;
 
-
 @RunWith(PaxExam.class)
 public class NorthboundIT {
-    private Logger log = LoggerFactory
-            .getLogger(NorthboundIT.class);
+    private Logger log = LoggerFactory.getLogger(NorthboundIT.class);
     // get the OSGI bundle context
     @Inject
     private BundleContext bc;
@@ -167,8 +165,429 @@ public class NorthboundIT {
         }
     }
 
+    private void testNodeProperties(JSONObject node, Integer nodeId,
+            String nodeType, Integer timestamp, String timestampName,
+            Integer actionsValue, Integer capabilitiesValue,
+            Integer tablesValue, Integer buffersValue) throws JSONException {
+
+        JSONObject nodeInfo = node.getJSONObject("node");
+        Assert.assertEquals(nodeId, (Integer) nodeInfo.getInt("@id"));
+        Assert.assertEquals(nodeType, nodeInfo.getString("@type"));
+
+        JSONObject properties = node.getJSONObject("properties");
+
+        if (timestamp == null || timestampName == null) {
+            Assert.assertFalse(properties.has("timeStamp"));
+        } else {
+            Assert.assertEquals(
+                    timestamp,
+                    (Integer) properties.getJSONObject("timeStamp").getInt(
+                            "timestamp"));
+            Assert.assertEquals(
+                    timestampName,
+                    properties.getJSONObject("timeStamp").getString(
+                            "timestampName"));
+        }
+        if (actionsValue == null) {
+            Assert.assertFalse(properties.has("actions"));
+        } else {
+            Assert.assertEquals(actionsValue, (Integer) properties
+                    .getJSONObject("actions").getInt("actionsValue"));
+        }
+        if (capabilitiesValue == null) {
+            Assert.assertFalse(properties.has("capabilities"));
+        } else {
+            Assert.assertEquals(capabilitiesValue, (Integer) properties
+                    .getJSONObject("capabilities").getInt("capabilitiesValue"));
+        }
+        if (tablesValue == null) {
+            Assert.assertFalse(properties.has("tables"));
+        } else {
+            Assert.assertEquals(tablesValue, (Integer) properties
+                    .getJSONObject("tables").getInt("tablesValue"));
+        }
+        if (buffersValue == null) {
+            Assert.assertFalse(properties.has("buffers"));
+        } else {
+            Assert.assertEquals(buffersValue, (Integer) properties
+                    .getJSONObject("buffers").getInt("buffersValue"));
+        }
+    }
+
+    private void testNodeConnectorProperties(
+            JSONObject nodeConnectorProperties, Integer ncId, String ncType,
+            Integer nodeId, String nodeType, Integer state,
+            Integer capabilities, Integer bandwidth) throws JSONException {
+
+        JSONObject nodeConnector = nodeConnectorProperties
+                .getJSONObject("nodeconnector");
+        JSONObject node = nodeConnector.getJSONObject("node");
+        JSONObject properties = nodeConnectorProperties
+                .getJSONObject("properties");
+
+        Assert.assertEquals(ncId, (Integer) nodeConnector.getInt("@id"));
+        Assert.assertEquals(ncType, nodeConnector.getString("@type"));
+        Assert.assertEquals(nodeId, (Integer) node.getInt("@id"));
+        Assert.assertEquals(nodeType, node.getString("@type"));
+        if (state == null) {
+            Assert.assertFalse(properties.has("state"));
+        } else {
+            Assert.assertEquals(
+                    state,
+                    (Integer) properties.getJSONObject("state").getInt(
+                            "stateValue"));
+        }
+        if (capabilities == null) {
+            Assert.assertFalse(properties.has("capabilities"));
+        } else {
+            Assert.assertEquals(capabilities, (Integer) properties
+                    .getJSONObject("capabilities").getInt("capabilitiesValue"));
+        }
+        if (bandwidth == null) {
+            Assert.assertFalse(properties.has("bandwidth"));
+        } else {
+            Assert.assertEquals(
+                    bandwidth,
+                    (Integer) properties.getJSONObject("bandwidth").getInt(
+                            "bandwidthValue"));
+        }
+
+    }
+
+    @Test
+    public void testSubnetsNorthbound() throws JSONException {
+        String baseURL = "http://127.0.0.1:8080/controller/nb/v2/subnet/";
+
+        String name1 = "testSubnet1";
+        String subnet1 = "1.1.1.1/24";
+        String name2 = "testSubnet2";
+        String subnet2 = "2.2.2.2/24";
+
+        // Test GET subnets in default container
+        String result = getJsonResult(baseURL + "default");
+        JSONTokener jt = new JSONTokener(result);
+        JSONObject json = new JSONObject(jt);
+        Assert.assertEquals("{}", result);
+
+        // Test GET subnet1 expecting 404
+        result = getJsonResult(baseURL + "default/" + name1);
+        Assert.assertEquals(404, httpResponseCode.intValue());
+
+        // Test POST subnet1
+        String queryParameter = new QueryParameter("subnetName", name1).add(
+                "subnet", subnet1).getString();
+        result = getJsonResult(baseURL + "default/" + name1 + queryParameter,
+                "POST");
+        Assert.assertEquals(201, httpResponseCode.intValue());
+
+        // Test GET subnet1
+        result = getJsonResult(baseURL + "default/" + name1);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        Assert.assertEquals(200, httpResponseCode.intValue());
+        Assert.assertEquals(name1, json.getString("@name"));
+        Assert.assertEquals(subnet1, json.getString("@subnet"));
+
+        // Test POST subnet2
+        queryParameter = new QueryParameter("subnetName", name2).add("subnet",
+                subnet2).getString();
+        result = getJsonResult(baseURL + "default/" + name2 + queryParameter,
+                "POST");
+        Assert.assertEquals(201, httpResponseCode.intValue());
+
+        // Test GET all subnets in default container
+        result = getJsonResult(baseURL + "default");
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        JSONArray subnetConfigArray = json.getJSONArray("subnetConfig");
+        JSONObject subnetConfig;
+        Assert.assertEquals(2, subnetConfigArray.length());
+        for (int i = 0; i < subnetConfigArray.length(); i++) {
+            subnetConfig = subnetConfigArray.getJSONObject(i);
+            if (subnetConfig.getString("@name").equals(name1)) {
+                Assert.assertEquals(subnet1, subnetConfig.getString("@subnet"));
+            } else if (subnetConfig.getString("@name").equals(name2)) {
+                Assert.assertEquals(subnet2, subnetConfig.getString("@subnet"));
+            } else {
+                // Unexpected config name
+                Assert.assertTrue(false);
+            }
+        }
+
+        // Test DELETE subnet1
+        result = getJsonResult(baseURL + "default/" + name1, "DELETE");
+        Assert.assertEquals(200, httpResponseCode.intValue());
+
+        // Test GET deleted subnet1
+        result = getJsonResult(baseURL + "default/" + name1);
+        Assert.assertEquals(404, httpResponseCode.intValue());
+
+    }
+
+    @Test
+    public void testStaticRoutingNorthbound() throws JSONException {
+        String baseURL = "http://127.0.0.1:8080/controller/nb/v2/staticroute/";
+
+        String name1 = "testRoute1";
+        String prefix1 = "192.168.1.1/24";
+        String nextHop1 = "0.0.0.0";
+        String name2 = "testRoute2";
+        String prefix2 = "192.168.1.1/16";
+        String nextHop2 = "1.1.1.1";
+
+        // Test GET static routes in default container, expecting no results
+        String result = getJsonResult(baseURL + "default");
+        JSONTokener jt = new JSONTokener(result);
+        JSONObject json = new JSONObject(jt);
+        Assert.assertEquals("{}", result);
+
+        // Test insert static route
+        String requestBody = "{\"name\":\"" + name1 + "\", \"prefix\":\""
+                + prefix1 + "\", \"nextHop\":\"" + nextHop1 + "\"}";
+        result = getJsonResult(baseURL + "default/" + name1, "POST",
+                requestBody);
+        Assert.assertEquals(201, httpResponseCode.intValue());
+
+        requestBody = "{\"name\":\"" + name2 + "\", \"prefix\":\"" + prefix2
+                + "\", \"nextHop\":\"" + nextHop2 + "\"}";
+        result = getJsonResult(baseURL + "default/" + name2, "POST",
+                requestBody);
+        Assert.assertEquals(201, httpResponseCode.intValue());
+
+        // Test Get all static routes
+        result = getJsonResult(baseURL + "default");
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        JSONArray staticRoutes = json.getJSONArray("staticRoute");
+        Assert.assertEquals(2, staticRoutes.length());
+        JSONObject route;
+        for (int i = 0; i < staticRoutes.length(); i++) {
+            route = staticRoutes.getJSONObject(i);
+            if (route.getString("name").equals(name1)) {
+                Assert.assertEquals(prefix1, route.getString("prefix"));
+                Assert.assertEquals(nextHop1, route.getString("nextHop"));
+            } else if (route.getString("name").equals(name2)) {
+                Assert.assertEquals(prefix2, route.getString("prefix"));
+                Assert.assertEquals(nextHop2, route.getString("nextHop"));
+            } else {
+                // static route has unknown name
+                Assert.assertTrue(false);
+            }
+        }
+
+        // Test get specific static route
+        result = getJsonResult(baseURL + "default/" + name1);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+
+        Assert.assertEquals(name1, json.getString("name"));
+        Assert.assertEquals(prefix1, json.getString("prefix"));
+        Assert.assertEquals(nextHop1, json.getString("nextHop"));
+
+        result = getJsonResult(baseURL + "default/" + name2);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+
+        Assert.assertEquals(name2, json.getString("name"));
+        Assert.assertEquals(prefix2, json.getString("prefix"));
+        Assert.assertEquals(nextHop2, json.getString("nextHop"));
+
+        // Test delete static route
+        result = getJsonResult(baseURL + "default/" + name1, "DELETE");
+        Assert.assertEquals(200, httpResponseCode.intValue());
+
+        result = getJsonResult(baseURL + "default");
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        JSONObject singleStaticRoute = json.getJSONObject("staticRoute");
+        Assert.assertEquals(name2, singleStaticRoute.getString("name"));
+
+    }
+
+    @Test
+    public void testSwitchManager() throws JSONException {
+        String baseURL = "http://127.0.0.1:8080/controller/nb/v2/switch/default/";
+
+        // define Node/NodeConnector attributes for test
+        int nodeId_1 = 51966;
+        int nodeId_2 = 3366;
+        int nodeId_3 = 4477;
+        int nodeConnectorId_1 = 51966;
+        int nodeConnectorId_2 = 12;
+        int nodeConnectorId_3 = 34;
+        String nodeType = "STUB";
+        String ncType = "STUB";
+        int timestamp_1 = 100000;
+        String timestampName_1 = "connectedSince";
+        int actionsValue_1 = 2;
+        int capabilitiesValue_1 = 3;
+        int tablesValue_1 = 1;
+        int buffersValue_1 = 1;
+        int ncState = 1;
+        int ncCapabilities = 1;
+        int ncBandwidth = 1000000000;
+
+        // Test GET all nodes
+
+        String result = getJsonResult(baseURL + "nodes");
+        JSONTokener jt = new JSONTokener(result);
+        JSONObject json = new JSONObject(jt);
+
+        // Test for first node
+        JSONObject node = getJsonInstance(json, "nodeProperties", nodeId_1);
+        Assert.assertNotNull(node);
+        testNodeProperties(node, nodeId_1, nodeType, timestamp_1,
+                timestampName_1, actionsValue_1, capabilitiesValue_1,
+                tablesValue_1, buffersValue_1);
+
+        // Test 2nd node, properties of 2nd node same as first node
+        node = getJsonInstance(json, "nodeProperties", nodeId_2);
+        Assert.assertNotNull(node);
+        testNodeProperties(node, nodeId_2, nodeType, timestamp_1,
+                timestampName_1, actionsValue_1, capabilitiesValue_1,
+                tablesValue_1, buffersValue_1);
+
+        // Test 3rd node, properties of 3rd node same as first node
+        node = getJsonInstance(json, "nodeProperties", nodeId_3);
+        Assert.assertNotNull(node);
+        testNodeProperties(node, nodeId_3, nodeType, timestamp_1,
+                timestampName_1, actionsValue_1, capabilitiesValue_1,
+                tablesValue_1, buffersValue_1);
+
+        // Test GET nodeConnectors of a node
+        // Test first node
+        result = getJsonResult(baseURL + "node/STUB/" + nodeId_1);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        JSONObject nodeConnectorProperties = json
+                .getJSONObject("nodeConnectorProperties");
+
+        testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_1,
+                ncType, nodeId_1, nodeType, ncState, ncCapabilities,
+                ncBandwidth);
+
+        // Test second node
+        result = getJsonResult(baseURL + "node/STUB/" + nodeId_2);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        nodeConnectorProperties = json.getJSONObject("nodeConnectorProperties");
+
+        testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_2,
+                ncType, nodeId_2, nodeType, ncState, ncCapabilities,
+                ncBandwidth);
+
+        // Test third node
+        result = getJsonResult(baseURL + "node/STUB/" + nodeId_3);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+
+        nodeConnectorProperties = json.getJSONObject("nodeConnectorProperties");
+        testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_3,
+                ncType, nodeId_3, nodeType, ncState, ncCapabilities,
+                ncBandwidth);
+
+        // Test delete node property
+        // Delete timestamp property from node1
+        result = getJsonResult(baseURL + "node/STUB/" + nodeId_1
+                + "/property/timeStamp", "DELETE");
+        Assert.assertEquals(200, httpResponseCode.intValue());
+
+        // Check node1
+        result = getJsonResult(baseURL + "nodes");
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        node = getJsonInstance(json, "nodeProperties", nodeId_1);
+        Assert.assertNotNull(node);
+        testNodeProperties(node, nodeId_1, nodeType, null, null,
+                actionsValue_1, capabilitiesValue_1, tablesValue_1,
+                buffersValue_1);
+
+        // Delete actions property from node2
+        result = getJsonResult(baseURL + "node/STUB/" + nodeId_2
+                + "/property/actions", "DELETE");
+        Assert.assertEquals(200, httpResponseCode.intValue());
+
+        // Check node2
+        result = getJsonResult(baseURL + "nodes");
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        node = getJsonInstance(json, "nodeProperties", nodeId_2);
+        Assert.assertNotNull(node);
+        testNodeProperties(node, nodeId_2, nodeType, timestamp_1,
+                timestampName_1, null, capabilitiesValue_1, tablesValue_1,
+                buffersValue_1);
+
+        // Test add property to node
+        // Add Tier and Bandwidth property to node1
+        result = getJsonResult(baseURL + "node/STUB/" + nodeId_1
+                + "/property/tier/1001", "PUT");
+        Assert.assertEquals(201, httpResponseCode.intValue());
+        result = getJsonResult(baseURL + "node/STUB/" + nodeId_1
+                + "/property/bandwidth/1002", "PUT");
+        Assert.assertEquals(201, httpResponseCode.intValue());
+
+        // Test for first node
+        result = getJsonResult(baseURL + "nodes");
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        node = getJsonInstance(json, "nodeProperties", nodeId_1);
+        Assert.assertNotNull(node);
+        Assert.assertEquals(1001, node.getJSONObject("properties")
+                .getJSONObject("tier").getInt("tierValue"));
+        Assert.assertEquals(1002, node.getJSONObject("properties")
+                .getJSONObject("bandwidth").getInt("bandwidthValue"));
+
+        // Test delete nodeConnector property
+        // Delete state property of nodeconnector1
+        result = getJsonResult(baseURL + "nodeconnector/STUB/" + nodeId_1
+                + "/STUB/" + nodeConnectorId_1 + "/property/state", "DELETE");
+        Assert.assertEquals(200, httpResponseCode.intValue());
+
+        result = getJsonResult(baseURL + "node/STUB/" + nodeId_1);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        nodeConnectorProperties = json.getJSONObject("nodeConnectorProperties");
+
+        testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_1,
+                ncType, nodeId_1, nodeType, null, ncCapabilities, ncBandwidth);
+
+        // Delete capabilities property of nodeconnector2
+        result = getJsonResult(baseURL + "nodeconnector/STUB/" + nodeId_2
+                + "/STUB/" + nodeConnectorId_2 + "/property/capabilities",
+                "DELETE");
+        Assert.assertEquals(200, httpResponseCode.intValue());
+
+        result = getJsonResult(baseURL + "node/STUB/" + nodeId_2);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        nodeConnectorProperties = json.getJSONObject("nodeConnectorProperties");
+
+        testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_2,
+                ncType, nodeId_2, nodeType, ncState, null, ncBandwidth);
+
+        // Test PUT nodeConnector property
+        int newBandwidth = 1001;
+
+        // Add Name/Bandwidth property to nodeConnector1
+        result = getJsonResult(baseURL + "nodeconnector/STUB/" + nodeId_1
+                + "/STUB/" + nodeConnectorId_1 + "/property/bandwidth/"
+                + newBandwidth, "PUT");
+        Assert.assertEquals(201, httpResponseCode.intValue());
+
+        result = getJsonResult(baseURL + "node/STUB/" + nodeId_1);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        nodeConnectorProperties = json.getJSONObject("nodeConnectorProperties");
+
+        // Check for new bandwidth value, state value removed from previous
+        // test
+        testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_1,
+                ncType, nodeId_1, nodeType, null, ncCapabilities, newBandwidth);
+
+    }
+
     @Test
-    public void testStatistics() {
+    public void testStatistics() throws JSONException {
         String actionTypes[] = { "drop", "loopback", "flood", "floodAll",
                 "controller", "swPath", "hwPath", "output", "setDlSrc",
                 "setDlDst", "setDlType", "setVlanId", "setVlanPcp",
@@ -177,262 +596,247 @@ public class NorthboundIT {
         System.out.println("Starting Statistics JAXB client.");
 
         String baseURL = "http://127.0.0.1:8080/controller/nb/v2/statistics/default/";
-        try {
-            String result = getJsonResult(baseURL + "flowstats");
-            JSONTokener jt = new JSONTokener(result);
-            JSONObject json = new JSONObject(jt);
-            JSONObject flowStatistics = getJsonInstance(json, "flowStatistics",
-                    0xCAFE);
-            JSONObject node = flowStatistics.getJSONObject("node");
-            // test that node was returned properly
-            Assert.assertTrue(node.getInt("@id") == 0xCAFE);
-            Assert.assertTrue(node.getString("@type").equals("STUB"));
-
-            // test that flow statistics results are correct
-            JSONArray flowStats = flowStatistics.getJSONArray("flowStat");
-            for (int i = 0; i < flowStats.length(); i++) {
-
-                JSONObject flowStat = flowStats.getJSONObject(i);
-                testFlowStat(flowStat, actionTypes[i]);
 
-            }
+        String result = getJsonResult(baseURL + "flowstats");
+        JSONTokener jt = new JSONTokener(result);
+        JSONObject json = new JSONObject(jt);
+        JSONObject flowStatistics = getJsonInstance(json, "flowStatistics",
+                0xCAFE);
+        JSONObject node = flowStatistics.getJSONObject("node");
+        // test that node was returned properly
+        Assert.assertTrue(node.getInt("@id") == 0xCAFE);
+        Assert.assertTrue(node.getString("@type").equals("STUB"));
 
-            // for /controller/nb/v2/statistics/default/portstats
-            result = getJsonResult(baseURL + "portstats");
-            jt = new JSONTokener(result);
-            json = new JSONObject(jt);
-            JSONObject portStatistics = getJsonInstance(json, "portStatistics",
-                    0xCAFE);
-            JSONObject node2 = portStatistics.getJSONObject("node");
-            // test that node was returned properly
-            Assert.assertTrue(node2.getInt("@id") == 0xCAFE);
-            Assert.assertTrue(node2.getString("@type").equals("STUB"));
-
-            // test that port statistic results are correct
-            JSONObject portStat = portStatistics.getJSONObject("portStat");
-            Assert.assertTrue(portStat.getInt("receivePackets") == 250);
-            Assert.assertTrue(portStat.getInt("transmitPackets") == 500);
-            Assert.assertTrue(portStat.getInt("receiveBytes") == 1000);
-            Assert.assertTrue(portStat.getInt("transmitBytes") == 5000);
-            Assert.assertTrue(portStat.getInt("receiveDrops") == 2);
-            Assert.assertTrue(portStat.getInt("transmitDrops") == 50);
-            Assert.assertTrue(portStat.getInt("receiveErrors") == 3);
-            Assert.assertTrue(portStat.getInt("transmitErrors") == 10);
-            Assert.assertTrue(portStat.getInt("receiveFrameError") == 5);
-            Assert.assertTrue(portStat.getInt("receiveOverRunError") == 6);
-            Assert.assertTrue(portStat.getInt("receiveCrcError") == 1);
-            Assert.assertTrue(portStat.getInt("collisionCount") == 4);
-
-            // test for getting one specific node's stats
-            result = getJsonResult(baseURL + "flowstats/STUB/51966");
-            jt = new JSONTokener(result);
-            json = new JSONObject(jt);
-            node = json.getJSONObject("node");
-            // test that node was returned properly
-            Assert.assertTrue(node.getInt("@id") == 0xCAFE);
-            Assert.assertTrue(node.getString("@type").equals("STUB"));
-
-            // test that flow statistics results are correct
-            flowStats = json.getJSONArray("flowStat");
-            for (int i = 0; i < flowStats.length(); i++) {
-                JSONObject flowStat = flowStats.getJSONObject(i);
-                testFlowStat(flowStat, actionTypes[i]);
-            }
+        // test that flow statistics results are correct
+        JSONArray flowStats = flowStatistics.getJSONArray("flowStat");
+        for (int i = 0; i < flowStats.length(); i++) {
 
-            result = getJsonResult(baseURL + "portstats/STUB/51966");
-            jt = new JSONTokener(result);
-            json = new JSONObject(jt);
-            node2 = json.getJSONObject("node");
-            // test that node was returned properly
-            Assert.assertTrue(node2.getInt("@id") == 0xCAFE);
-            Assert.assertTrue(node2.getString("@type").equals("STUB"));
-
-            // test that port statistic results are correct
-            portStat = json.getJSONObject("portStat");
-            Assert.assertTrue(portStat.getInt("receivePackets") == 250);
-            Assert.assertTrue(portStat.getInt("transmitPackets") == 500);
-            Assert.assertTrue(portStat.getInt("receiveBytes") == 1000);
-            Assert.assertTrue(portStat.getInt("transmitBytes") == 5000);
-            Assert.assertTrue(portStat.getInt("receiveDrops") == 2);
-            Assert.assertTrue(portStat.getInt("transmitDrops") == 50);
-            Assert.assertTrue(portStat.getInt("receiveErrors") == 3);
-            Assert.assertTrue(portStat.getInt("transmitErrors") == 10);
-            Assert.assertTrue(portStat.getInt("receiveFrameError") == 5);
-            Assert.assertTrue(portStat.getInt("receiveOverRunError") == 6);
-            Assert.assertTrue(portStat.getInt("receiveCrcError") == 1);
-            Assert.assertTrue(portStat.getInt("collisionCount") == 4);
+            JSONObject flowStat = flowStats.getJSONObject(i);
+            testFlowStat(flowStat, actionTypes[i]);
 
-        } catch (Exception e) {
-            // Got an unexpected exception
-            Assert.assertTrue(false);
+        }
 
+        // for /controller/nb/v2/statistics/default/portstats
+        result = getJsonResult(baseURL + "portstats");
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        JSONObject portStatistics = getJsonInstance(json, "portStatistics",
+                0xCAFE);
+        JSONObject node2 = portStatistics.getJSONObject("node");
+        // test that node was returned properly
+        Assert.assertTrue(node2.getInt("@id") == 0xCAFE);
+        Assert.assertTrue(node2.getString("@type").equals("STUB"));
+
+        // test that port statistic results are correct
+        JSONObject portStat = portStatistics.getJSONObject("portStat");
+        Assert.assertTrue(portStat.getInt("receivePackets") == 250);
+        Assert.assertTrue(portStat.getInt("transmitPackets") == 500);
+        Assert.assertTrue(portStat.getInt("receiveBytes") == 1000);
+        Assert.assertTrue(portStat.getInt("transmitBytes") == 5000);
+        Assert.assertTrue(portStat.getInt("receiveDrops") == 2);
+        Assert.assertTrue(portStat.getInt("transmitDrops") == 50);
+        Assert.assertTrue(portStat.getInt("receiveErrors") == 3);
+        Assert.assertTrue(portStat.getInt("transmitErrors") == 10);
+        Assert.assertTrue(portStat.getInt("receiveFrameError") == 5);
+        Assert.assertTrue(portStat.getInt("receiveOverRunError") == 6);
+        Assert.assertTrue(portStat.getInt("receiveCrcError") == 1);
+        Assert.assertTrue(portStat.getInt("collisionCount") == 4);
+
+        // test for getting one specific node's stats
+        result = getJsonResult(baseURL + "flowstats/STUB/51966");
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        node = json.getJSONObject("node");
+        // test that node was returned properly
+        Assert.assertTrue(node.getInt("@id") == 0xCAFE);
+        Assert.assertTrue(node.getString("@type").equals("STUB"));
+
+        // test that flow statistics results are correct
+        flowStats = json.getJSONArray("flowStat");
+        for (int i = 0; i < flowStats.length(); i++) {
+            JSONObject flowStat = flowStats.getJSONObject(i);
+            testFlowStat(flowStat, actionTypes[i]);
         }
+
+        result = getJsonResult(baseURL + "portstats/STUB/51966");
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        node2 = json.getJSONObject("node");
+        // test that node was returned properly
+        Assert.assertTrue(node2.getInt("@id") == 0xCAFE);
+        Assert.assertTrue(node2.getString("@type").equals("STUB"));
+
+        // test that port statistic results are correct
+        portStat = json.getJSONObject("portStat");
+        Assert.assertTrue(portStat.getInt("receivePackets") == 250);
+        Assert.assertTrue(portStat.getInt("transmitPackets") == 500);
+        Assert.assertTrue(portStat.getInt("receiveBytes") == 1000);
+        Assert.assertTrue(portStat.getInt("transmitBytes") == 5000);
+        Assert.assertTrue(portStat.getInt("receiveDrops") == 2);
+        Assert.assertTrue(portStat.getInt("transmitDrops") == 50);
+        Assert.assertTrue(portStat.getInt("receiveErrors") == 3);
+        Assert.assertTrue(portStat.getInt("transmitErrors") == 10);
+        Assert.assertTrue(portStat.getInt("receiveFrameError") == 5);
+        Assert.assertTrue(portStat.getInt("receiveOverRunError") == 6);
+        Assert.assertTrue(portStat.getInt("receiveCrcError") == 1);
+        Assert.assertTrue(portStat.getInt("collisionCount") == 4);
     }
 
-    private void testFlowStat(JSONObject flowStat, String actionType) {
-        try {
-            Assert.assertTrue(flowStat.getInt("tableId") == 1);
-            Assert.assertTrue(flowStat.getInt("durationSeconds") == 40);
-            Assert.assertTrue(flowStat.getInt("durationNanoseconds") == 400);
-            Assert.assertTrue(flowStat.getInt("packetCount") == 200);
-            Assert.assertTrue(flowStat.getInt("byteCount") == 100);
-
-            // test that flow information is correct
-            JSONObject flow = flowStat.getJSONObject("flow");
-            Assert.assertTrue(flow.getInt("priority") == 3500);
-            Assert.assertTrue(flow.getInt("idleTimeout") == 1000);
-            Assert.assertTrue(flow.getInt("hardTimeout") == 2000);
-            Assert.assertTrue(flow.getInt("id") == 12345);
-
-            JSONObject match = (flow.getJSONObject("match")
-                    .getJSONObject("matchField"));
-            Assert.assertTrue(match.getString("type").equals("NW_DST"));
-            Assert.assertTrue(match.getString("value").equals("1.1.1.1"));
-
-            JSONObject act = flow.getJSONObject("actions");
-            Assert.assertTrue(act.getString("@type").equals(actionType));
-
-            if (act.getString("@type").equals("output")) {
-                JSONObject port = act.getJSONObject("port");
-                JSONObject port_node = port.getJSONObject("node");
-                Assert.assertTrue(port.getInt("@id") == 51966);
-                Assert.assertTrue(port.getString("@type").equals("STUB"));
-                Assert.assertTrue(port_node.getInt("@id") == 51966);
-                Assert.assertTrue(port_node.getString("@type").equals("STUB"));
-            }
+    private void testFlowStat(JSONObject flowStat, String actionType)
+            throws JSONException {
+        Assert.assertTrue(flowStat.getInt("tableId") == 1);
+        Assert.assertTrue(flowStat.getInt("durationSeconds") == 40);
+        Assert.assertTrue(flowStat.getInt("durationNanoseconds") == 400);
+        Assert.assertTrue(flowStat.getInt("packetCount") == 200);
+        Assert.assertTrue(flowStat.getInt("byteCount") == 100);
+
+        // test that flow information is correct
+        JSONObject flow = flowStat.getJSONObject("flow");
+        Assert.assertTrue(flow.getInt("priority") == 3500);
+        Assert.assertTrue(flow.getInt("idleTimeout") == 1000);
+        Assert.assertTrue(flow.getInt("hardTimeout") == 2000);
+        Assert.assertTrue(flow.getInt("id") == 12345);
+
+        JSONObject match = (flow.getJSONObject("match")
+                .getJSONObject("matchField"));
+        Assert.assertTrue(match.getString("type").equals("NW_DST"));
+        Assert.assertTrue(match.getString("value").equals("1.1.1.1"));
+
+        JSONObject act = flow.getJSONObject("actions");
+        Assert.assertTrue(act.getString("@type").equals(actionType));
+
+        if (act.getString("@type").equals("output")) {
+            JSONObject port = act.getJSONObject("port");
+            JSONObject port_node = port.getJSONObject("node");
+            Assert.assertTrue(port.getInt("@id") == 51966);
+            Assert.assertTrue(port.getString("@type").equals("STUB"));
+            Assert.assertTrue(port_node.getInt("@id") == 51966);
+            Assert.assertTrue(port_node.getString("@type").equals("STUB"));
+        }
 
-            if (act.getString("@type").equals("setDlSrc")) {
-                byte srcMatch[] = { (byte) 5, (byte) 4, (byte) 3, (byte) 2,
-                        (byte) 1 };
-                String src = act.getString("address");
-                byte srcBytes[] = new byte[5];
-                srcBytes[0] = Byte.parseByte(src.substring(0, 2));
-                srcBytes[1] = Byte.parseByte(src.substring(2, 4));
-                srcBytes[2] = Byte.parseByte(src.substring(4, 6));
-                srcBytes[3] = Byte.parseByte(src.substring(6, 8));
-                srcBytes[4] = Byte.parseByte(src.substring(8, 10));
-                Assert.assertTrue(Arrays.equals(srcBytes, srcMatch));
-            }
+        if (act.getString("@type").equals("setDlSrc")) {
+            byte srcMatch[] = { (byte) 5, (byte) 4, (byte) 3, (byte) 2,
+                    (byte) 1 };
+            String src = act.getString("address");
+            byte srcBytes[] = new byte[5];
+            srcBytes[0] = Byte.parseByte(src.substring(0, 2));
+            srcBytes[1] = Byte.parseByte(src.substring(2, 4));
+            srcBytes[2] = Byte.parseByte(src.substring(4, 6));
+            srcBytes[3] = Byte.parseByte(src.substring(6, 8));
+            srcBytes[4] = Byte.parseByte(src.substring(8, 10));
+            Assert.assertTrue(Arrays.equals(srcBytes, srcMatch));
+        }
 
-            if (act.getString("@type").equals("setDlDst")) {
-                byte dstMatch[] = { (byte) 1, (byte) 2, (byte) 3, (byte) 4,
-                        (byte) 5 };
-                String dst = act.getString("address");
-                byte dstBytes[] = new byte[5];
-                dstBytes[0] = Byte.parseByte(dst.substring(0, 2));
-                dstBytes[1] = Byte.parseByte(dst.substring(2, 4));
-                dstBytes[2] = Byte.parseByte(dst.substring(4, 6));
-                dstBytes[3] = Byte.parseByte(dst.substring(6, 8));
-                dstBytes[4] = Byte.parseByte(dst.substring(8, 10));
-                Assert.assertTrue(Arrays.equals(dstBytes, dstMatch));
-            }
-            if (act.getString("@type").equals("setDlType"))
-                Assert.assertTrue(act.getInt("dlType") == 10);
-            if (act.getString("@type").equals("setVlanId"))
-                Assert.assertTrue(act.getInt("vlanId") == 2);
-            if (act.getString("@type").equals("setVlanPcp"))
-                Assert.assertTrue(act.getInt("pcp") == 3);
-            if (act.getString("@type").equals("setVlanCfi"))
-                Assert.assertTrue(act.getInt("cfi") == 1);
-
-            if (act.getString("@type").equals("setNwSrc"))
-                Assert.assertTrue(act.getString("address").equals("2.2.2.2"));
-            if (act.getString("@type").equals("setNwDst"))
-                Assert.assertTrue(act.getString("address").equals("1.1.1.1"));
-
-            if (act.getString("@type").equals("pushVlan")) {
-                int head = act.getInt("VlanHeader");
-                // parsing vlan header
-                int id = head & 0xfff;
-                int cfi = (head >> 12) & 0x1;
-                int pcp = (head >> 13) & 0x7;
-                int tag = (head >> 16) & 0xffff;
-                Assert.assertTrue(id == 1234);
-                Assert.assertTrue(cfi == 1);
-                Assert.assertTrue(pcp == 1);
-                Assert.assertTrue(tag == 0x8100);
-            }
-            if (act.getString("@type").equals("setNwTos"))
-                Assert.assertTrue(act.getInt("tos") == 16);
-            if (act.getString("@type").equals("setTpSrc"))
-                Assert.assertTrue(act.getInt("port") == 4201);
-            if (act.getString("@type").equals("setTpDst"))
-                Assert.assertTrue(act.getInt("port") == 8080);
-        } catch (Exception e) {
-            Assert.assertTrue(false);
+        if (act.getString("@type").equals("setDlDst")) {
+            byte dstMatch[] = { (byte) 1, (byte) 2, (byte) 3, (byte) 4,
+                    (byte) 5 };
+            String dst = act.getString("address");
+            byte dstBytes[] = new byte[5];
+            dstBytes[0] = Byte.parseByte(dst.substring(0, 2));
+            dstBytes[1] = Byte.parseByte(dst.substring(2, 4));
+            dstBytes[2] = Byte.parseByte(dst.substring(4, 6));
+            dstBytes[3] = Byte.parseByte(dst.substring(6, 8));
+            dstBytes[4] = Byte.parseByte(dst.substring(8, 10));
+            Assert.assertTrue(Arrays.equals(dstBytes, dstMatch));
+        }
+        if (act.getString("@type").equals("setDlType"))
+            Assert.assertTrue(act.getInt("dlType") == 10);
+        if (act.getString("@type").equals("setVlanId"))
+            Assert.assertTrue(act.getInt("vlanId") == 2);
+        if (act.getString("@type").equals("setVlanPcp"))
+            Assert.assertTrue(act.getInt("pcp") == 3);
+        if (act.getString("@type").equals("setVlanCfi"))
+            Assert.assertTrue(act.getInt("cfi") == 1);
+
+        if (act.getString("@type").equals("setNwSrc"))
+            Assert.assertTrue(act.getString("address").equals("2.2.2.2"));
+        if (act.getString("@type").equals("setNwDst"))
+            Assert.assertTrue(act.getString("address").equals("1.1.1.1"));
+
+        if (act.getString("@type").equals("pushVlan")) {
+            int head = act.getInt("VlanHeader");
+            // parsing vlan header
+            int id = head & 0xfff;
+            int cfi = (head >> 12) & 0x1;
+            int pcp = (head >> 13) & 0x7;
+            int tag = (head >> 16) & 0xffff;
+            Assert.assertTrue(id == 1234);
+            Assert.assertTrue(cfi == 1);
+            Assert.assertTrue(pcp == 1);
+            Assert.assertTrue(tag == 0x8100);
         }
+        if (act.getString("@type").equals("setNwTos"))
+            Assert.assertTrue(act.getInt("tos") == 16);
+        if (act.getString("@type").equals("setTpSrc"))
+            Assert.assertTrue(act.getInt("port") == 4201);
+        if (act.getString("@type").equals("setTpDst"))
+            Assert.assertTrue(act.getInt("port") == 8080);
     }
 
     @Test
-    public void testFlowProgrammer() {
-        try {
-            String baseURL = "http://127.0.0.1:8080/controller/nb/v2/flow/default/";
-            // Attempt to get a flow that doesn't exit. Should return 404
-            // status.
-            String result = getJsonResult(baseURL + "STUB/51966/test1", "GET");
-            Assert.assertTrue(result.equals("404"));
-
-            // test add flow1
-            String fc = "{\"dynamic\":\"false\", \"name\":\"test1\", \"node\":{\"@id\":\"51966\",\"@type\":\"STUB\"}, \"actions\":[\"DROP\"]}";
-            result = getJsonResult(baseURL + "STUB/51966/test1", "POST", fc);
-            Assert.assertTrue(httpResponseCode == 201);
-
-            // test get returns flow that was added.
-            result = getJsonResult(baseURL + "STUB/51966/test1", "GET");
-            // check that result came out fine.
-            Assert.assertTrue(httpResponseCode == 200);
-            JSONTokener jt = new JSONTokener(result);
-            JSONObject json = new JSONObject(jt);
-            Assert.assertTrue(json.getString("name").equals("test1"));
-            Assert.assertTrue(json.getString("actions").equals("DROP"));
-            Assert.assertTrue(json.getString("installInHw").equals("true"));
-            JSONObject node = json.getJSONObject("node");
-            Assert.assertTrue(node.getString("@type").equals("STUB"));
-            Assert.assertTrue(node.getString("@id").equals("51966"));
-            // test adding same flow again fails due to repeat name..return 409
-            // code
-            result = getJsonResult(baseURL + "STUB/51966/test1", "POST", fc);
-            Assert.assertTrue(result.equals("409"));
-
-            fc = "{\"dynamic\":\"false\", \"name\":\"test2\", \"node\":{\"@id\":\"51966\",\"@type\":\"STUB\"}, \"actions\":[\"DROP\"]}";
-            result = getJsonResult(baseURL + "STUB/51966/test2", "POST", fc);
-            // test should return 500 for error due to same flow being added.
-            Assert.assertTrue(result.equals("500"));
-
-            // add second flow that's different
-            fc = "{\"dynamic\":\"false\", \"name\":\"test2\", \"nwSrc\":\"1.1.1.1\", \"node\":{\"@id\":\"51966\",\"@type\":\"STUB\"}, \"actions\":[\"DROP\"]}";
-            result = getJsonResult(baseURL + "STUB/51966/test2", "POST", fc);
-            Assert.assertTrue(httpResponseCode == 201);
-            
-            // check that request returns both flows given node.
-            result = getJsonResult(baseURL + "STUB/51966/", "GET");
-            jt = new JSONTokener(result);
-            json = new JSONObject(jt);
-            Assert.assertTrue(json.get("flowConfig") instanceof JSONArray);
-            JSONArray ja = json.getJSONArray("flowConfig");
-            Integer count = ja.length();
-            Assert.assertTrue(count == 2);
-
-            // check that request returns both flows given just container.
-            result = getJsonResult(baseURL);
-            jt = new JSONTokener(result);
-            json = new JSONObject(jt);
-            Assert.assertTrue(json.get("flowConfig") instanceof JSONArray);
-            ja = json.getJSONArray("flowConfig");
-            count = ja.length();
-            Assert.assertTrue(count == 2);
-
-            // delete a flow, check that it's no longer in list.
-            result = getJsonResult(baseURL + "STUB/51966/test2", "DELETE");
-            Assert.assertTrue(httpResponseCode == 200);
-
-            result = getJsonResult(baseURL + "STUB/51966/test2", "GET");
-            Assert.assertTrue(result.equals("404"));
-
-        } catch (Exception e) {
-            Assert.assertTrue(false);
-        }
-
+    public void testFlowProgrammer() throws JSONException {
+        String baseURL = "http://127.0.0.1:8080/controller/nb/v2/flow/default/";
+        // Attempt to get a flow that doesn't exit. Should return 404
+        // status.
+        String result = getJsonResult(baseURL + "STUB/51966/test1", "GET");
+        Assert.assertTrue(result.equals("404"));
+
+        // test add flow1
+        String fc = "{\"dynamic\":\"false\", \"name\":\"test1\", \"node\":{\"@id\":\"51966\",\"@type\":\"STUB\"}, \"actions\":[\"DROP\"]}";
+        result = getJsonResult(baseURL + "STUB/51966/test1", "POST", fc);
+        Assert.assertTrue(httpResponseCode == 201);
+
+        // test get returns flow that was added.
+        result = getJsonResult(baseURL + "STUB/51966/test1", "GET");
+        // check that result came out fine.
+        Assert.assertTrue(httpResponseCode == 200);
+        JSONTokener jt = new JSONTokener(result);
+        JSONObject json = new JSONObject(jt);
+        Assert.assertTrue(json.getString("name").equals("test1"));
+        Assert.assertTrue(json.getString("actions").equals("DROP"));
+        Assert.assertTrue(json.getString("installInHw").equals("true"));
+        JSONObject node = json.getJSONObject("node");
+        Assert.assertTrue(node.getString("@type").equals("STUB"));
+        Assert.assertTrue(node.getString("@id").equals("51966"));
+        // test adding same flow again fails due to repeat name..return 409
+        // code
+        result = getJsonResult(baseURL + "STUB/51966/test1", "POST", fc);
+        Assert.assertTrue(result.equals("409"));
+
+        fc = "{\"dynamic\":\"false\", \"name\":\"test2\", \"node\":{\"@id\":\"51966\",\"@type\":\"STUB\"}, \"actions\":[\"DROP\"]}";
+        result = getJsonResult(baseURL + "STUB/51966/test2", "POST", fc);
+        // test should return 500 for error due to same flow being added.
+        Assert.assertTrue(result.equals("500"));
+
+        // add second flow that's different
+        fc = "{\"dynamic\":\"false\", \"name\":\"test2\", \"nwSrc\":\"1.1.1.1\", \"node\":{\"@id\":\"51966\",\"@type\":\"STUB\"}, \"actions\":[\"DROP\"]}";
+        result = getJsonResult(baseURL + "STUB/51966/test2", "POST", fc);
+        Assert.assertTrue(httpResponseCode == 201);
+
+        // check that request returns both flows given node.
+        result = getJsonResult(baseURL + "STUB/51966/", "GET");
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        Assert.assertTrue(json.get("flowConfig") instanceof JSONArray);
+        JSONArray ja = json.getJSONArray("flowConfig");
+        Integer count = ja.length();
+        Assert.assertTrue(count == 2);
+
+        // check that request returns both flows given just container.
+        result = getJsonResult(baseURL);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        Assert.assertTrue(json.get("flowConfig") instanceof JSONArray);
+        ja = json.getJSONArray("flowConfig");
+        count = ja.length();
+        Assert.assertTrue(count == 2);
+
+        // delete a flow, check that it's no longer in list.
+        result = getJsonResult(baseURL + "STUB/51966/test2", "DELETE");
+        Assert.assertTrue(httpResponseCode == 200);
+
+        result = getJsonResult(baseURL + "STUB/51966/test2", "GET");
+        Assert.assertTrue(result.equals("404"));
     }
 
     // method to extract a JSONObject with specified node ID from a JSONObject
@@ -484,7 +888,7 @@ public class NorthboundIT {
     }
 
     @Test
-    public void testHostTracker() {
+    public void testHostTracker() throws JSONException {
 
         System.out.println("Starting HostTracker JAXB client.");
 
@@ -510,34 +914,29 @@ public class NorthboundIT {
         String baseURL = "http://127.0.0.1:8080/controller/nb/v2/host/default";
 
         // test POST method: addHost()
-        try {
-            String queryParameter = new QueryParameter("dataLayerAddress",
-                    dataLayerAddress_1).add("nodeType", nodeType_1)
-                    .add("nodeId", nodeId_1.toString())
-                    .add("nodeConnectorType", nodeConnectorType_1)
-                    .add("nodeConnectorId", nodeConnectorId_1.toString())
-                    .add("vlan", vlan_1).getString();
-
-            String result = getJsonResult(baseURL + "/" + networkAddress_1
-                    + queryParameter, "POST");
-            Assert.assertTrue(httpResponseCode.intValue() == (Integer) 201);
-
-            // vlan is not passed through query parameter but should be
-            // defaulted to "0"
-            queryParameter = new QueryParameter("dataLayerAddress",
-                    dataLayerAddress_2).add("nodeType", nodeType_2)
-                    .add("nodeId", nodeId_2.toString())
-                    .add("nodeConnectorType", nodeConnectorType_2)
-                    .add("nodeConnectorId", nodeConnectorId_2.toString())
-                    .getString();
-
-            result = getJsonResult(baseURL + "/" + networkAddress_2
-                    + queryParameter, "POST");
-            Assert.assertTrue(httpResponseCode.intValue() == (Integer) 201);
-        } catch (Exception e) {
-            // Got an unexpected exception
-            Assert.assertTrue(false);
-        }
+        String queryParameter = new QueryParameter("dataLayerAddress",
+                dataLayerAddress_1).add("nodeType", nodeType_1)
+                .add("nodeId", nodeId_1.toString())
+                .add("nodeConnectorType", nodeConnectorType_1)
+                .add("nodeConnectorId", nodeConnectorId_1.toString())
+                .add("vlan", vlan_1).getString();
+
+        String result = getJsonResult(baseURL + "/" + networkAddress_1
+                + queryParameter, "POST");
+        Assert.assertTrue(httpResponseCode.intValue() == (Integer) 201);
+
+        // vlan is not passed through query parameter but should be
+        // defaulted to "0"
+        queryParameter = new QueryParameter("dataLayerAddress",
+                dataLayerAddress_2).add("nodeType", nodeType_2)
+                .add("nodeId", nodeId_2.toString())
+                .add("nodeConnectorType", nodeConnectorType_2)
+                .add("nodeConnectorId", nodeConnectorId_2.toString())
+                .getString();
+
+        result = getJsonResult(baseURL + "/" + networkAddress_2
+                + queryParameter, "POST");
+        Assert.assertTrue(httpResponseCode.intValue() == (Integer) 201);
 
         // define variables for decoding returned strings
         String networkAddress;
@@ -545,69 +944,59 @@ public class NorthboundIT {
 
         // the two hosts should be in inactive host DB
         // test GET method: getInactiveHosts()
-        try {
-            String result = getJsonResult(baseURL + "/inactive", "GET");
-            Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
+        result = getJsonResult(baseURL + "/inactive", "GET");
+        Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
+
+        JSONTokener jt = new JSONTokener(result);
+        JSONObject json = new JSONObject(jt);
+        // there should be at least two hosts in the DB
+        Assert.assertTrue(json.get("host") instanceof JSONArray);
+        JSONArray ja = json.getJSONArray("host");
+        Integer count = ja.length();
+        Assert.assertTrue(count == 2);
+
+        for (int i = 0; i < count; i++) {
+            host_jo = ja.getJSONObject(i);
+            dl_jo = host_jo.getJSONObject("dataLayerAddress");
+            nc_jo = host_jo.getJSONObject("nodeConnector");
+            node_jo = nc_jo.getJSONObject("node");
 
-            JSONTokener jt = new JSONTokener(result);
-            JSONObject json = new JSONObject(jt);
-            // there should be at least two hosts in the DB
-            Assert.assertTrue(json.get("host") instanceof JSONArray);
-            JSONArray ja = json.getJSONArray("host");
-            Integer count = ja.length();
-            Assert.assertTrue(count == 2);
-
-            for (int i = 0; i < count; i++) {
-                host_jo = ja.getJSONObject(i);
-                dl_jo = host_jo.getJSONObject("dataLayerAddress");
-                nc_jo = host_jo.getJSONObject("nodeConnector");
-                node_jo = nc_jo.getJSONObject("node");
-
-                networkAddress = host_jo.getString("networkAddress");
-                if (networkAddress.equalsIgnoreCase(networkAddress_1)) {
-                    Assert.assertTrue(dl_jo.getString("macAddress")
-                            .equalsIgnoreCase(dataLayerAddress_1));
-                    Assert.assertTrue(nc_jo.getString("@type")
-                            .equalsIgnoreCase(nodeConnectorType_1));
-                    Assert.assertTrue(Integer.parseInt(nc_jo.getString("@id")) == nodeConnectorId_1);
-                    Assert.assertTrue(node_jo.getString("@type")
-                            .equalsIgnoreCase(nodeType_1));
-                    Assert.assertTrue(Integer.parseInt(node_jo.getString("@id")) == nodeId_1);
-                    Assert.assertTrue(host_jo.getString("vlan")
-                            .equalsIgnoreCase(vlan_1));
-                } else if (networkAddress.equalsIgnoreCase(networkAddress_2)) {
-                    Assert.assertTrue(dl_jo.getString("macAddress")
-                            .equalsIgnoreCase(dataLayerAddress_2));
-                    Assert.assertTrue(nc_jo.getString("@type")
-                            .equalsIgnoreCase(nodeConnectorType_2));
-                    Assert.assertTrue(Integer.parseInt(nc_jo.getString("@id")) == nodeConnectorId_2);
-                    Assert.assertTrue(node_jo.getString("@type")
-                            .equalsIgnoreCase(nodeType_2));
-                    Assert.assertTrue(Integer.parseInt(node_jo.getString("@id")) == nodeId_2);
-                    Assert.assertTrue(host_jo.getString("vlan")
-                            .equalsIgnoreCase(vlan_2));
-                } else {
-                    Assert.assertTrue(false);
-                }
+            networkAddress = host_jo.getString("networkAddress");
+            if (networkAddress.equalsIgnoreCase(networkAddress_1)) {
+                Assert.assertTrue(dl_jo.getString("macAddress")
+                        .equalsIgnoreCase(dataLayerAddress_1));
+                Assert.assertTrue(nc_jo.getString("@type").equalsIgnoreCase(
+                        nodeConnectorType_1));
+                Assert.assertTrue(Integer.parseInt(nc_jo.getString("@id")) == nodeConnectorId_1);
+                Assert.assertTrue(node_jo.getString("@type").equalsIgnoreCase(
+                        nodeType_1));
+                Assert.assertTrue(Integer.parseInt(node_jo.getString("@id")) == nodeId_1);
+                Assert.assertTrue(host_jo.getString("vlan").equalsIgnoreCase(
+                        vlan_1));
+            } else if (networkAddress.equalsIgnoreCase(networkAddress_2)) {
+                Assert.assertTrue(dl_jo.getString("macAddress")
+                        .equalsIgnoreCase(dataLayerAddress_2));
+                Assert.assertTrue(nc_jo.getString("@type").equalsIgnoreCase(
+                        nodeConnectorType_2));
+                Assert.assertTrue(Integer.parseInt(nc_jo.getString("@id")) == nodeConnectorId_2);
+                Assert.assertTrue(node_jo.getString("@type").equalsIgnoreCase(
+                        nodeType_2));
+                Assert.assertTrue(Integer.parseInt(node_jo.getString("@id")) == nodeId_2);
+                Assert.assertTrue(host_jo.getString("vlan").equalsIgnoreCase(
+                        vlan_2));
+            } else {
+                Assert.assertTrue(false);
             }
-        } catch (Exception e) {
-            // Got an unexpected exception
-            Assert.assertTrue(false);
         }
 
         // test GET method: getActiveHosts() - no host expected
-        try {
-            String result = getJsonResult(baseURL, "GET");
-            Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
+        result = getJsonResult(baseURL, "GET");
+        Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
 
-            JSONTokener jt = new JSONTokener(result);
-            JSONObject json = new JSONObject(jt);
-            Assert.assertFalse(hostInJson(json, networkAddress_1));
-            Assert.assertFalse(hostInJson(json, networkAddress_2));
-        } catch (Exception e) {
-            // Got an unexpected exception
-            Assert.assertTrue(false);
-        }
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+        Assert.assertFalse(hostInJson(json, networkAddress_1));
+        Assert.assertFalse(hostInJson(json, networkAddress_2));
 
         // put the 1st host into active host DB
         Node nd;
@@ -623,75 +1012,57 @@ public class NorthboundIT {
         }
 
         // verify the host shows up in active host DB
-        try {
-            String result = getJsonResult(baseURL, "GET");
-            Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
 
-            JSONTokener jt = new JSONTokener(result);
-            JSONObject json = new JSONObject(jt);
+        result = getJsonResult(baseURL, "GET");
+        Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
 
-            Assert.assertTrue(hostInJson(json, networkAddress_1));
-        } catch (Exception e) {
-            // Got an unexpected exception
-            Assert.assertTrue(false);
-        }
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+
+        Assert.assertTrue(hostInJson(json, networkAddress_1));
 
         // test GET method for getHostDetails()
-        try {
-            String result = getJsonResult(baseURL + "/" + networkAddress_1,
-                    "GET");
-            Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
 
-            JSONTokener jt = new JSONTokener(result);
-            JSONObject json = new JSONObject(jt);
+        result = getJsonResult(baseURL + "/" + networkAddress_1, "GET");
+        Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
 
-            Assert.assertFalse(json.length() == 0);
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
 
-            dl_jo = json.getJSONObject("dataLayerAddress");
-            nc_jo = json.getJSONObject("nodeConnector");
-            node_jo = nc_jo.getJSONObject("node");
+        Assert.assertFalse(json.length() == 0);
 
-            Assert.assertTrue(json.getString("networkAddress")
-                    .equalsIgnoreCase(networkAddress_1));
-            Assert.assertTrue(dl_jo.getString("macAddress").equalsIgnoreCase(
-                    dataLayerAddress_1));
-            Assert.assertTrue(nc_jo.getString("@type").equalsIgnoreCase(
-                    nodeConnectorType_1));
-            Assert.assertTrue(Integer.parseInt(nc_jo.getString("@id")) == nodeConnectorId_1);
-            Assert.assertTrue(node_jo.getString("@type").equalsIgnoreCase(
-                    nodeType_1));
-            Assert.assertTrue(Integer.parseInt(node_jo.getString("@id")) == nodeId_1);
-            Assert.assertTrue(json.getString("vlan").equalsIgnoreCase(vlan_1));
-        } catch (Exception e) {
-            // Got an unexpected exception
-            Assert.assertTrue(false);
-        }
+        dl_jo = json.getJSONObject("dataLayerAddress");
+        nc_jo = json.getJSONObject("nodeConnector");
+        node_jo = nc_jo.getJSONObject("node");
+
+        Assert.assertTrue(json.getString("networkAddress").equalsIgnoreCase(
+                networkAddress_1));
+        Assert.assertTrue(dl_jo.getString("macAddress").equalsIgnoreCase(
+                dataLayerAddress_1));
+        Assert.assertTrue(nc_jo.getString("@type").equalsIgnoreCase(
+                nodeConnectorType_1));
+        Assert.assertTrue(Integer.parseInt(nc_jo.getString("@id")) == nodeConnectorId_1);
+        Assert.assertTrue(node_jo.getString("@type").equalsIgnoreCase(
+                nodeType_1));
+        Assert.assertTrue(Integer.parseInt(node_jo.getString("@id")) == nodeId_1);
+        Assert.assertTrue(json.getString("vlan").equalsIgnoreCase(vlan_1));
 
         // test DELETE method for deleteFlow()
-        try {
-            String result = getJsonResult(baseURL + "/" + networkAddress_1,
-                    "DELETE");
-            Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
 
-        } catch (Exception e) {
-            // Got an unexpected exception
-            Assert.assertTrue(false);
-        }
+        result = getJsonResult(baseURL + "/" + networkAddress_1, "DELETE");
+        Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
 
         // verify host_1 removed from active host DB
         // test GET method: getActiveHosts() - no host expected
-        try {
-            String result = getJsonResult(baseURL, "GET");
-            Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
 
-            JSONTokener jt = new JSONTokener(result);
-            JSONObject json = new JSONObject(jt);
+        result = getJsonResult(baseURL, "GET");
+        Assert.assertTrue(httpResponseCode.intValue() == (Integer) 200);
+
+        jt = new JSONTokener(result);
+        json = new JSONObject(jt);
+
+        Assert.assertFalse(hostInJson(json, networkAddress_1));
 
-            Assert.assertFalse(hostInJson(json, networkAddress_1));
-        } catch (Exception e) {
-            // Got an unexpected exception
-            Assert.assertTrue(false);
-        }
     }
 
     private Boolean hostInJson(JSONObject json, String hostIp)
@@ -796,6 +1167,8 @@ public class NorthboundIT {
 
                 mavenBundle("org.opendaylight.controller", "usermanager",
                         "0.4.0-SNAPSHOT"),
+                mavenBundle("org.opendaylight.controller",
+                        "usermanager.implementation", "0.4.0-SNAPSHOT"),
                 mavenBundle("org.opendaylight.controller", "logging.bridge",
                         "0.4.0-SNAPSHOT"),
                 mavenBundle("org.opendaylight.controller", "clustering.test",
@@ -982,4 +1355,4 @@ public class NorthboundIT {
                 mavenBundle("com.sun.jersey", "jersey-json", "1.17")
                         .startLevel(2), junitBundles());
     }
-}
\ No newline at end of file
+}
index 4be075451e9c31f90260e6e39b7dc43008a47c1f..56d469b59932f591b93cd91eb7e491ab3c683085 100644 (file)
                connectionTimeout="20000"
                redirectPort="8443" />
 
-<!-- 
-       Please remove the comments around the following Connector tag to enable HTTPS Authentication support.
-       Remember to add a valid keystore in the configuration folder.
-       More info : http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration 
+<!--
+        Please remove the comments around the following Connector tag to enable HTTPS Authentication support.
+        Remember to add a valid keystore in the configuration folder.
+        More info : http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
 -->
- <!-- 
+
+ <!--
     <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
                maxThreads="150" scheme="https" secure="true"
                clientAuth="false" sslProtocol="TLS"
             unpackWARs="false" autoDeploy="false"
             deployOnStartup="false" createDirs="false">
         <Realm className="org.opendaylight.controller.security.ControllerCustomRealm" />
-           <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-     
+            <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
+
         <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
-                       prefix="web_access_log_" suffix=".txt" resolveHosts="false"
-                       rotatable="true" fileDateFormat="yyyy-MM"
-                       pattern="%{yyyy-MM-dd HH:mm:ss.SSS z}t - [%a] - %r"/>
-               
+                        prefix="web_access_log_" suffix=".txt" resolveHosts="false"
+                        rotatable="true" fileDateFormat="yyyy-MM"
+                        pattern="%{yyyy-MM-dd HH:mm:ss.SSS z}t - [%a] - %r"/>
+
       </Host>
     </Engine>
   </Service>
index 4d6bed028a0fc3d30ff0ab932c9552af4409f902..402b6553718852daf6b4fb863a114939925ecfb4 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <enunciate label="full" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://enunciate.codehaus.org/schemas/enunciate-1.26.xsd">
-  
+
   <services>
     <rest defaultRestSubcontext="/controller/nb/v2/staticroute"/>
   </services>
index f656faf3080a2c1277c5ee0bd81758f9c3b62cea..bb88465907191dd2bc2fea0d7f7061190a3d1aee 100644 (file)
@@ -91,6 +91,6 @@
       <groupId>org.opendaylight.controller.thirdparty</groupId>
       <artifactId>com.sun.jersey.jersey-servlet</artifactId>
       <version>1.17-SNAPSHOT</version>
-    </dependency>   
+    </dependency>
   </dependencies>
 </project>
index 9511b8c7caed25de41a5378acf3f2a4e79e3691e..683a9a2d906a285b37dab19bdb4b36b528aa8b57 100644 (file)
@@ -21,22 +21,22 @@ import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class StaticRoutes {
-       @XmlElement
-       List<StaticRoute> staticRoute;
-       //To satisfy JAXB
-       private StaticRoutes() {
-               
-       }
-       
-       public StaticRoutes(List<StaticRoute> staticRoute) {
-               this.staticRoute = staticRoute;
-       }
-
-       public List<StaticRoute> getFlowConfig() {
-               return staticRoute;
-       }
-
-       public void setFlowConfig(List<StaticRoute> staticRoute) {
-               this.staticRoute = staticRoute;
-       }
+        @XmlElement
+        List<StaticRoute> staticRoute;
+        //To satisfy JAXB
+        private StaticRoutes() {
+
+        }
+
+        public StaticRoutes(List<StaticRoute> staticRoute) {
+                this.staticRoute = staticRoute;
+        }
+
+        public List<StaticRoute> getFlowConfig() {
+                return staticRoute;
+        }
+
+        public void setFlowConfig(List<StaticRoute> staticRoute) {
+                this.staticRoute = staticRoute;
+        }
 }
index c48d7ec02684463962909ec2d60b600e3b270167..b85f5641c73ea9af99fd3b201909220367c8240b 100644 (file)
@@ -51,7 +51,7 @@ import org.opendaylight.controller.sal.utils.Status;
  * Authentication realm : <b>opendaylight</b><br>
  * Transport : <b>HTTP and HTTPS</b><br>
  * <br>
- * HTTPS Authentication is disabled by default. Administrator can enable it in tomcat-server.xml after adding 
+ * HTTPS Authentication is disabled by default. Administrator can enable it in tomcat-server.xml after adding
  * a proper keystore / SSL certificate from a trusted authority.<br>
  * More info : http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
  */
@@ -59,18 +59,18 @@ import org.opendaylight.controller.sal.utils.Status;
 public class StaticRoutingNorthbound {
 
 
-       private String username;
-       
+        private String username;
+
     @Context
     public void setSecurityContext(SecurityContext context) {
-       username = context.getUserPrincipal().getName();
+        username = context.getUserPrincipal().getName();
     }
     protected String getUserName() {
         return username;
     }
-       
 
-       
+
+
     private List<StaticRoute> getStaticRoutesInternal(String containerName) {
 
         IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
@@ -109,9 +109,9 @@ public class StaticRoutingNorthbound {
     public StaticRoutes getStaticRoutes(
             @PathParam("containerName") String containerName) {
 
-        if(!NorthboundUtils.isAuthorized(getUserName(), containerName, 
+        if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
                 Privilege.WRITE, this)){
-            throw new 
+            throw new
                 UnauthorizedException("User is not authorized to perform this operation on container "
                             + containerName);
         }
@@ -136,9 +136,9 @@ public class StaticRoutingNorthbound {
             @PathParam("containerName") String containerName,
             @PathParam("name") String name) {
 
-        if(!NorthboundUtils.isAuthorized(getUserName(), containerName, 
+        if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
                 Privilege.WRITE, this)){
-            throw new 
+            throw new
                 UnauthorizedException("User is not authorized to perform this operation on container "
                             + containerName);
         }
@@ -174,10 +174,10 @@ public class StaticRoutingNorthbound {
             @PathParam(value = "name") String name,
             @TypeHint(StaticRoute.class) JAXBElement<StaticRoute> staticRouteData) {
 
-   
-        if(!NorthboundUtils.isAuthorized(getUserName(), containerName, 
+
+        if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
                 Privilege.WRITE, this)){
-            throw new 
+            throw new
                 UnauthorizedException("User is not authorized to perform this operation on container "
                             + containerName);
         }
@@ -221,10 +221,10 @@ public class StaticRoutingNorthbound {
     public Response removeStaticRoute(
             @PathParam(value = "containerName") String containerName,
             @PathParam(value = "name") String name) {
-        if(!NorthboundUtils.isAuthorized(getUserName(), containerName, 
+
+        if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
                 Privilege.WRITE, this)){
-            throw new 
+            throw new
                 UnauthorizedException("User is not authorized to perform this operation on container "
                             + containerName);
         }
index 37901a68a8445536e06b87aafc502f12e275a3b8..4a040c1a1f861e3f38e0bf762cb5170832710b19 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
   <servlet>
     <servlet-name>JAXRSStaticRouting</servlet-name>
     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
     <load-on-startup>1</load-on-startup>
   </servlet>
 
-       <servlet-mapping>
-               <servlet-name>JAXRSStaticRouting</servlet-name>
-               <url-pattern>/*</url-pattern>
-       </servlet-mapping>
+        <servlet-mapping>
+                <servlet-name>JAXRSStaticRouting</servlet-name>
+                <url-pattern>/*</url-pattern>
+        </servlet-mapping>
 
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>NB api</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>NB api</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
-       <login-config>
-               <auth-method>BASIC</auth-method>
-               <realm-name>opendaylight</realm-name>
-       </login-config>  
+        <login-config>
+                <auth-method>BASIC</auth-method>
+                <realm-name>opendaylight</realm-name>
+        </login-config>
 </web-app>
\ No newline at end of file
index 3f2759dceaa37641f4fac291417bb58949c5e787..63ae43975858f63284e2ad2ad51c0b532efb65be 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <enunciate label="full" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://enunciate.codehaus.org/schemas/enunciate-1.26.xsd">
-  
+
   <services>
     <rest defaultRestSubcontext="/controller/nb/v2/statistics"/>
   </services>
index 7ce5c43d12e031a0359cd09d0de06fbe4c316bb7..cad50e299834a633a03b36e95776e93120bd9abe 100644 (file)
@@ -24,7 +24,7 @@
             <version>0.5.0-SNAPSHOT</version>
           </dependency>
         </dependencies>
-      </plugin>        
+      </plugin>
       <plugin>
         <groupId>org.apache.felix</groupId>
         <artifactId>maven-bundle-plugin</artifactId>
index 0e96c5411c2c3e0649407dd5776b61eb11af4d09..7f37afec21eb4c2e1201af6696c4076e2beda05b 100644 (file)
@@ -19,22 +19,22 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class AllFlowStatistics {
-       @XmlElement
-       List<FlowStatistics> flowStatistics;
-       //To satisfy JAXB
-       private AllFlowStatistics() {
-       }
-       
-       public AllFlowStatistics(List<FlowStatistics> flowStatistics) {
-               this.flowStatistics = flowStatistics;
-       }
-
-       public List<FlowStatistics> getFlowStatistics() {
-               return flowStatistics;
-       }
-
-       public void setFlowStatistics(List<FlowStatistics> flowStatistics) {
-               this.flowStatistics = flowStatistics;
-       }
+        @XmlElement
+        List<FlowStatistics> flowStatistics;
+        //To satisfy JAXB
+        private AllFlowStatistics() {
+        }
+
+        public AllFlowStatistics(List<FlowStatistics> flowStatistics) {
+                this.flowStatistics = flowStatistics;
+        }
+
+        public List<FlowStatistics> getFlowStatistics() {
+                return flowStatistics;
+        }
+
+        public void setFlowStatistics(List<FlowStatistics> flowStatistics) {
+                this.flowStatistics = flowStatistics;
+        }
 
 }
index a1bf1904e4d7fc6dcc0d796a1206a86a50e63b64..e377de2b8836a10c1089eddb098533e2bf95820b 100644 (file)
@@ -19,22 +19,22 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class AllPortStatistics {
-       @XmlElement
-       List<PortStatistics> portStatistics;
-       //To satisfy JAXB
-       private AllPortStatistics() {
-       }
-       
-       public AllPortStatistics(List<PortStatistics> portStatistics) {
-               this.portStatistics = portStatistics;
-       }
-
-       public List<PortStatistics> getPortStatistics() {
-               return portStatistics;
-       }
-
-       public void setPortStatistics(List<PortStatistics> portStatistics) {
-               this.portStatistics = portStatistics;
-       }
+        @XmlElement
+        List<PortStatistics> portStatistics;
+        //To satisfy JAXB
+        private AllPortStatistics() {
+        }
+
+        public AllPortStatistics(List<PortStatistics> portStatistics) {
+                this.portStatistics = portStatistics;
+        }
+
+        public List<PortStatistics> getPortStatistics() {
+                return portStatistics;
+        }
+
+        public void setPortStatistics(List<PortStatistics> portStatistics) {
+                this.portStatistics = portStatistics;
+        }
 
 }
index 146e95ab32a457fc1f6e90bbc112b70c191f900f..25b671c1a881d44cd7e61137fdaca09621aa1885 100644 (file)
@@ -27,7 +27,7 @@ public class FlowStatistics {
 
     // To satisfy JAXB
     @SuppressWarnings("unused")
-       private FlowStatistics() {
+        private FlowStatistics() {
     }
 
     public FlowStatistics(Node node, List<FlowOnNode> flowStat) {
index 068baa15fac733e015fe53565c46be0e7b6dfe42..876bb7f7b08f11b85c068a12edb37a38747750ab 100644 (file)
@@ -28,7 +28,7 @@ public class PortStatistics {
 
     // To satisfy JAXB
     @SuppressWarnings("unused")
-       private PortStatistics() {
+        private PortStatistics() {
     }
 
     public PortStatistics(Node node, List<NodeConnectorStatistics> portStats) {
index dee52932bda41ed77ca5b0be273bae94886b791e..197ebabf9133d43f7b81f5360f46b7d3138b1f9e 100644 (file)
@@ -40,7 +40,7 @@ import org.opendaylight.controller.switchmanager.ISwitchManager;
 /**
  * Northbound APIs that returns various Statistics exposed by the Southbound
  * plugins such as Openflow.
- * 
+ *
  * <br>
  * <br>
  * Authentication scheme : <b>HTTP Basic</b><br>
@@ -52,7 +52,7 @@ import org.opendaylight.controller.switchmanager.ISwitchManager;
  * trusted authority.<br>
  * More info :
  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
- * 
+ *
  */
 @Path("/")
 public class StatisticsNorthbound {
@@ -102,7 +102,7 @@ public class StatisticsNorthbound {
 
     /**
      * Returns a list of all Flow Statistics from all the Nodes.
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -154,7 +154,7 @@ public class StatisticsNorthbound {
 
     /**
      * Returns a list of Flow Statistics for a given Node.
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -204,7 +204,7 @@ public class StatisticsNorthbound {
     /**
      * Returns a list of all the Port Statistics across all the NodeConnectors
      * on all the Nodes.
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
@@ -255,7 +255,7 @@ public class StatisticsNorthbound {
     /**
      * Returns a list of all the Port Statistics across all the NodeConnectors
      * in a given Node.
-     * 
+     *
      * @param containerName
      *            Name of the Container. The Container name for the base
      *            controller is "default".
index 24242d3c4587833e6a1db737ec7b5439722a79ce..f152aa75a2b1af7321ccf33d9776563750e82967 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
   <servlet>
     <servlet-name>JAXRSStatistics</servlet-name>
     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
     <url-pattern>/*</url-pattern>
   </servlet-mapping>
 
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>NB api</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>NB api</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
-       <login-config>
-               <auth-method>BASIC</auth-method>
-               <realm-name>opendaylight</realm-name>
-       </login-config>
+        <login-config>
+                <auth-method>BASIC</auth-method>
+                <realm-name>opendaylight</realm-name>
+        </login-config>
 </web-app>
\ No newline at end of file
index 60062edd2914d5165484426bbdb42ac5f9d1a2f4..3361f1b3d29cfdf38527d0589774b9129cb278a3 100644 (file)
@@ -21,22 +21,22 @@ import org.opendaylight.controller.switchmanager.SubnetConfig;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class SubnetConfigs {
-       @XmlElement
-       List<SubnetConfig> subnetConfig;
-       //To satisfy JAXB
-       private SubnetConfigs() {
-               
-       }
-       
-       public SubnetConfigs(List<SubnetConfig> subnetConfig) {
-               this.subnetConfig = subnetConfig;
-       }
-
-       public List<SubnetConfig> getSubnetConfig() {
-               return subnetConfig;
-       }
-
-       public void setSubnetConfig(List<SubnetConfig> subnetConfig) {
-               this.subnetConfig = subnetConfig;
-       }
+        @XmlElement
+        List<SubnetConfig> subnetConfig;
+        //To satisfy JAXB
+        private SubnetConfigs() {
+
+        }
+
+        public SubnetConfigs(List<SubnetConfig> subnetConfig) {
+                this.subnetConfig = subnetConfig;
+        }
+
+        public List<SubnetConfig> getSubnetConfig() {
+                return subnetConfig;
+        }
+
+        public void setSubnetConfig(List<SubnetConfig> subnetConfig) {
+                this.subnetConfig = subnetConfig;
+        }
 }
index 05bb5b1dd938ff9208eb5fcda84c6d262e50be33..5c327c4f72243b0cd9af6ddb92b1b747630bdca2 100644 (file)
@@ -55,10 +55,10 @@ public class SubnetsNorthboundJAXRS {
 
     /**
      * List all the subnets in a given container
-     * 
+     *
      * @param containerName
      *            container in which we want to query the subnets
-     * 
+     *
      * @return a List of SubnetConfig
      */
     @Path("/{containerName}")
@@ -86,12 +86,12 @@ public class SubnetsNorthboundJAXRS {
 
     /**
      * List the configuration of a subnet in a given container
-     * 
+     *
      * @param containerName
      *            container in which we want to query the subnet
      * @param subnetName
      *            of the subnet being queried
-     * 
+     *
      * @return a SubnetConfig
      */
     @Path("/{containerName}/{subnetName}")
@@ -129,7 +129,7 @@ public class SubnetsNorthboundJAXRS {
 
     /**
      * Add/Update a subnet to a container
-     * 
+     *
      * @param containerName
      *            container in which we want to add/update the subnet
      * @param subnetName
@@ -137,7 +137,7 @@ public class SubnetsNorthboundJAXRS {
      * @param subnet
      *            pair default gateway IP/mask that identify the subnet being
      *            added modified
-     * 
+     *
      */
     @Path("/{containerName}/{subnetName}")
     @POST
@@ -183,12 +183,12 @@ public class SubnetsNorthboundJAXRS {
 
     /**
      * Delete a subnet from a container
-     * 
+     *
      * @param containerName
      *            container in which we want to delete the subnet by name
      * @param subnetName
      *            of the subnet to be remove.
-     * 
+     *
      */
     @Path("/{containerName}/{subnetName}")
     @DELETE
@@ -225,56 +225,56 @@ public class SubnetsNorthboundJAXRS {
     }
 
     /*
-     * 
+     *
      * Add or remove switch ports to a subnet POST subnets/green/sw
-     * 
+     *
      * @param model
-     * 
+     *
      * @param containerName
-     * 
+     *
      * @param name
-     * 
+     *
      * @param subnet: the subnet name name
-     * 
+     *
      * @param switchports: datapath ID/port list =>
      * xx:xx:xx:xx:xx:xx:xx:xx/a,b,c-m,r-t,y
-     * 
+     *
      * @return
-     * 
+     *
      * @RequestMapping(value = "/{containerName}/{name}", method =
      * RequestMethod.POST)
-     * 
+     *
      * public View addSwitchports(Map<String, Object> model,
-     * 
+     *
      * @PathVariable(value = "containerName") String containerName,
-     * 
+     *
      * @PathVariable(value = "name") String name,
-     * 
+     *
      * @RequestParam(value = "nodeports") String nodePorts,
-     * 
+     *
      * @RequestParam(value = "action") String action) {
-     * 
+     *
      * checkDefaultDisabled(containerName); ISwitchManager switchManager = null;
      * try { BundleContext bCtx = FrameworkUtil.getBundle(this.getClass())
      * .getBundleContext();
-     * 
+     *
      * ServiceReference[] services = bCtx.getServiceReferences(
      * ISwitchManager.class.getName(), "(containerName=" + containerName + ")");
-     * 
+     *
      * if (services != null) { switchManager = (ISwitchManager)
      * bCtx.getService(services[0]); logger.debug("Switch manager reference is:"
      * + switchManager); } } catch (Exception e) {
      * logger.error("Switch Manager reference is NULL"); }
-     * 
+     *
      * checkContainerExists(switchManager);
-     * 
+     *
      * String ret; if (action.equals("add")) { ret =
      * switchManager.addPortsToSubnet(name, nodePorts); } else if
      * (action.equals("remove")) { ret =
      * switchManager.removePortsFromSubnet(name, nodePorts); } else { throw new
      * UnsupportedMediaTypeException(RestMessages.UNKNOWNACTION .toString() +
      * ": " + action); }
-     * 
+     *
      * return returnViewOrThrowConflicEx(model, ret); }
      */
 }
index 1c201d3b33eb590ce57d70ac180c0abee48b6fba..f7eccef6666f7d2ec8f0dc2d8b36215e0c9801a1 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">  
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
   <servlet>
     <servlet-name>JAXRSSubnets</servlet-name>
     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
     <servlet-name>JAXRSSubnets</servlet-name>
     <url-pattern>/*</url-pattern>
   </servlet-mapping>
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>NB api</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>NB api</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
-       <login-config>
-               <auth-method>BASIC</auth-method>
-               <realm-name>opendaylight</realm-name>
-       </login-config>
+        <login-config>
+                <auth-method>BASIC</auth-method>
+                <realm-name>opendaylight</realm-name>
+        </login-config>
 </web-app>
index 9338b55826b81852f4c0c881fe7beaa49bdc0298..8a8bfdb02999941afa232187ea4c02a37bf030d7 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <enunciate label="full" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://enunciate.codehaus.org/schemas/enunciate-1.26.xsd">
-  
+
   <services>
     <rest defaultRestSubcontext="/controller/nb/v2/switch"/>
   </services>
index ac9be4d07591e6e463c6be05b00a7ba48e125823..4a31317d95b3b61926ec96ca751bc5205c5f59c5 100644 (file)
@@ -19,22 +19,22 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class NodeConnectors {
-       @XmlElement
-       List<NodeConnectorProperties> nodeConnectorProperties;
-       //To satisfy JAXB
-       private NodeConnectors() {
-               
-       }
-       
-       public NodeConnectors(List<NodeConnectorProperties> nodeConnectorProperties) {
-               this.nodeConnectorProperties = nodeConnectorProperties;
-       }
-
-       public List<NodeConnectorProperties> getNodeConnectorProperties() {
-               return nodeConnectorProperties;
-       }
-
-       public void setNodeConnectorProperties(List<NodeConnectorProperties> nodeConnectorProperties) {
-               this.nodeConnectorProperties = nodeConnectorProperties;
-       }
+        @XmlElement
+        List<NodeConnectorProperties> nodeConnectorProperties;
+        //To satisfy JAXB
+        private NodeConnectors() {
+
+        }
+
+        public NodeConnectors(List<NodeConnectorProperties> nodeConnectorProperties) {
+                this.nodeConnectorProperties = nodeConnectorProperties;
+        }
+
+        public List<NodeConnectorProperties> getNodeConnectorProperties() {
+                return nodeConnectorProperties;
+        }
+
+        public void setNodeConnectorProperties(List<NodeConnectorProperties> nodeConnectorProperties) {
+                this.nodeConnectorProperties = nodeConnectorProperties;
+        }
 }
index 07d7b7c33b7b87cdf716c2233529c45dca6d750c..b7f1c53ae850dec4c7d8bf258853bbec849e5801 100644 (file)
@@ -19,22 +19,22 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class Nodes {
-       @XmlElement
-       List<NodeProperties> nodeProperties;
-       //To satisfy JAXB
-       private Nodes() {
-               
-       }
-       
-       public Nodes(List<NodeProperties> nodeProperties) {
-               this.nodeProperties = nodeProperties;
-       }
-
-       public List<NodeProperties> getNodeProperties() {
-               return nodeProperties;
-       }
-
-       public void setNodeProperties(List<NodeProperties> nodeProperties) {
-               this.nodeProperties = nodeProperties;
-       }
+        @XmlElement
+        List<NodeProperties> nodeProperties;
+        //To satisfy JAXB
+        private Nodes() {
+
+        }
+
+        public Nodes(List<NodeProperties> nodeProperties) {
+                this.nodeProperties = nodeProperties;
+        }
+
+        public List<NodeProperties> getNodeProperties() {
+                return nodeProperties;
+        }
+
+        public void setNodeProperties(List<NodeProperties> nodeProperties) {
+                this.nodeProperties = nodeProperties;
+        }
 }
index e92583a33a9543c30c60b269ddc67a0c075c8561..d3b023512bebd5790559b7e047b813e0558395e9 100644 (file)
@@ -205,7 +205,7 @@ public class SwitchNorthbound {
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
-        Node node = Node.fromString(nodeId);
+        Node node = Node.fromString(nodeType, nodeId);
 
         Property prop = switchManager.createProperty(propName, propValue);
         if (prop == null) {
@@ -262,8 +262,7 @@ public class SwitchNorthbound {
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
-        Node node = Node.fromString(nodeId);
-
+        Node node = Node.fromString(nodeType, nodeId);
         Status ret = switchManager.removeNodeProp(node, propertyName);
         if (ret.isSuccess()) {
             return Response.ok().build();
@@ -316,8 +315,7 @@ public class SwitchNorthbound {
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
-        Node node = Node.fromString(nodeId);
-
+        Node node = Node.fromString(nodeType, nodeId);
         List<NodeConnectorProperties> res = new ArrayList<NodeConnectorProperties>();
         Set<NodeConnector> ncs = switchManager.getNodeConnectors(node);
         if (ncs == null) {
@@ -397,12 +395,12 @@ public class SwitchNorthbound {
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
-        Node node = Node.fromString(nodeId);
+        Node node = Node.fromString(nodeType, nodeId);
 
         handleNodeConnectorAvailability(containerName, node, nodeConnectorType,
                 nodeConnectorId);
         NodeConnector nc = NodeConnector
-                .fromStringNoNode(nodeConnectorId, node);
+                .fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
 
         Property prop = switchManager.createProperty(propName, propValue);
         if (prop == null) {
@@ -470,13 +468,12 @@ public class SwitchNorthbound {
         }
 
         handleNodeAvailability(containerName, nodeType, nodeId);
-        Node node = Node.fromString(nodeId);
+        Node node = Node.fromString(nodeType, nodeId);
 
         handleNodeConnectorAvailability(containerName, node, nodeConnectorType,
                 nodeConnectorId);
         NodeConnector nc = NodeConnector
-                .fromStringNoNode(nodeConnectorId, node);
-
+                .fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
         Status ret = switchManager.removeNodeConnectorProp(nc, propertyName);
         if (ret.isSuccess()) {
             return Response.ok().build();
index a16cdfab48b88f228ae69ca3856f2c95a954bcca..188b21b24d000014c1f498f6f4e101ed8dd25c21 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
   <servlet>
     <servlet-name>JAXRSSwitchManager</servlet-name>
     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
     <url-pattern>/*</url-pattern>
   </servlet-mapping>
 
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>NB api</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>NB api</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
-       <login-config>
-               <auth-method>BASIC</auth-method>
-               <realm-name>opendaylight</realm-name>
-       </login-config>
+        <login-config>
+                <auth-method>BASIC</auth-method>
+                <realm-name>opendaylight</realm-name>
+        </login-config>
 </web-app>
\ No newline at end of file
index a8b18d5637b5fb8394de825706e168b9cf06c230..5386d4142fd55f0d3c7c79a5254aaa4faa70710b 100644 (file)
@@ -18,58 +18,58 @@ import org.opendaylight.controller.sal.utils.NodeCreator;
 
 public class SwitchManagerNorthboundTest extends TestCase {
 
-       @Test
-       public void testNodes() {
-               List<NodeProperties> nodeProperties = new ArrayList<NodeProperties>();
-               Nodes nodes = new Nodes(nodeProperties);
-               Assert.assertTrue(nodes.getNodeProperties().equals(nodeProperties));
-               nodes.setNodeProperties(null);
-               Assert.assertTrue(nodes.getNodeProperties() == null);
-       }
-       
-       @Test
-       public void testNodeProperties() {
-               Node node = NodeCreator.createOFNode(1L);
-               NodeProperties np= new NodeProperties(node, null);
-               Assert.assertTrue(np.getNode().equals(node));
-               Assert.assertTrue(np.getProperties() == null);
-               
-               Node node2 = NodeCreator.createOFNode(2L);
-               np.setNode(node2);
-               Assert.assertTrue(np.getNode().equals(node2));
+        @Test
+        public void testNodes() {
+                List<NodeProperties> nodeProperties = new ArrayList<NodeProperties>();
+                Nodes nodes = new Nodes(nodeProperties);
+                Assert.assertTrue(nodes.getNodeProperties().equals(nodeProperties));
+                nodes.setNodeProperties(null);
+                Assert.assertTrue(nodes.getNodeProperties() == null);
+        }
 
-               Set<Property> props = new HashSet<Property>();
-               np.setProperties(props);
-               Assert.assertTrue(np.getProperties().equals(props));
-       }
+        @Test
+        public void testNodeProperties() {
+                Node node = NodeCreator.createOFNode(1L);
+                NodeProperties np= new NodeProperties(node, null);
+                Assert.assertTrue(np.getNode().equals(node));
+                Assert.assertTrue(np.getProperties() == null);
 
-       @Test
-       public void testNodeConnectors() {
-               List<NodeConnectorProperties> nodeConnectorProperties = new ArrayList<NodeConnectorProperties>();
-               NodeConnectors ncs = new NodeConnectors(nodeConnectorProperties);
-               Assert.assertTrue(ncs.getNodeConnectorProperties().equals(nodeConnectorProperties));
-               ncs.setNodeConnectorProperties(null);
-               Assert.assertTrue(ncs.getNodeConnectorProperties() == null);
-       }
-       
-       @Test
-       public void testNodeConnectorProperties() {
-               Node node = NodeCreator.createOFNode(1L);
+                Node node2 = NodeCreator.createOFNode(2L);
+                np.setNode(node2);
+                Assert.assertTrue(np.getNode().equals(node2));
+
+                Set<Property> props = new HashSet<Property>();
+                np.setProperties(props);
+                Assert.assertTrue(np.getProperties().equals(props));
+        }
+
+        @Test
+        public void testNodeConnectors() {
+                List<NodeConnectorProperties> nodeConnectorProperties = new ArrayList<NodeConnectorProperties>();
+                NodeConnectors ncs = new NodeConnectors(nodeConnectorProperties);
+                Assert.assertTrue(ncs.getNodeConnectorProperties().equals(nodeConnectorProperties));
+                ncs.setNodeConnectorProperties(null);
+                Assert.assertTrue(ncs.getNodeConnectorProperties() == null);
+        }
+
+        @Test
+        public void testNodeConnectorProperties() {
+                Node node = NodeCreator.createOFNode(1L);
         NodeConnector port = NodeConnectorCreator.createOFNodeConnector(
                 (short) 24, node);
-        
+
         NodeConnectorProperties ncp= new NodeConnectorProperties(port, null);
-               Assert.assertTrue(ncp.getProperties() == null);
-               Assert.assertTrue(ncp.getNodeConnector().equals(port));
-               
+                Assert.assertTrue(ncp.getProperties() == null);
+                Assert.assertTrue(ncp.getNodeConnector().equals(port));
+
         NodeConnector port2 = NodeConnectorCreator.createOFNodeConnector(
                 (short) 33, node);
-               ncp.setNodeConnector(port2);
-               Assert.assertTrue(ncp.getNodeConnector().equals(port2));
+                ncp.setNodeConnector(port2);
+                Assert.assertTrue(ncp.getNodeConnector().equals(port2));
+
+                Set<Property> props = new HashSet<Property>();
+                ncp.setProperties(props);
+                Assert.assertTrue(ncp.getProperties().equals(props));
+        }
 
-               Set<Property> props = new HashSet<Property>();
-               ncp.setProperties(props);
-               Assert.assertTrue(ncp.getProperties().equals(props));
-       }
-       
 }
index c955d8cc5c3ae549f7ff021db27d02ddaf9f8fd6..b7c451c8e6855e09c772b42e4f7f0e52948eec6d 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <enunciate label="full" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://enunciate.codehaus.org/schemas/enunciate-1.26.xsd">
-  
+
   <services>
     <rest defaultRestSubcontext="/controller/nb/v2/topology"/>
   </services>
index bfc86cf34b7fda45fb3ca1869c7d9a87680a62ae..15548d94286ceb0eb3058e0211cb5c3abcb29024 100644 (file)
@@ -19,22 +19,22 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class Topology {
-       @XmlElement
-       List<EdgeProperties> edgeProperties;
-       //To satisfy JAXB
-       private Topology() {
-               
-       }
-       
-       public Topology(List<EdgeProperties> edgeProperties) {
-               this.edgeProperties = edgeProperties;
-       }
-
-       public List<EdgeProperties> getEdgeProperties() {
-               return edgeProperties;
-       }
-
-       public void setEdgeProperties(List<EdgeProperties> edgeProperties) {
-               this.edgeProperties = edgeProperties;
-       }
+        @XmlElement
+        List<EdgeProperties> edgeProperties;
+        //To satisfy JAXB
+        private Topology() {
+
+        }
+
+        public Topology(List<EdgeProperties> edgeProperties) {
+                this.edgeProperties = edgeProperties;
+        }
+
+        public List<EdgeProperties> getEdgeProperties() {
+                return edgeProperties;
+        }
+
+        public void setEdgeProperties(List<EdgeProperties> edgeProperties) {
+                this.edgeProperties = edgeProperties;
+        }
 }
index 10480bc4ec3f153312b6d1f7cae0f0bf658772a1..323e2d2211deaa916ce5b81257bde2074592aa65 100644 (file)
@@ -45,7 +45,7 @@ import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig;
 
 /**
  * Topology Northbound REST API
- * 
+ *
  * <br>
  * <br>
  * Authentication scheme : <b>HTTP Basic</b><br>
@@ -74,12 +74,12 @@ public class TopologyNorthboundJAXRS {
     }
 
     /**
-     * 
+     *
      * Retrieve the Topology
-     * 
+     *
      * @param containerName
      *            The container for which we want to retrieve the topology
-     * 
+     *
      * @return A List of EdgeProps each EdgeProp represent an Edge of the grap
      *         with the corresponding properties attached to it.
      */
@@ -119,10 +119,10 @@ public class TopologyNorthboundJAXRS {
 
     /**
      * Retrieve the user configured links
-     * 
+     *
      * @param containerName
      *            The container for which we want to retrieve the user links
-     * 
+     *
      * @return A List of user configured links
      */
     @Path("/{containerName}/userLink")
@@ -159,7 +159,7 @@ public class TopologyNorthboundJAXRS {
 
     /**
      * Add an User Link
-     * 
+     *
      * @param containerName
      *            Name of the Container. The base Container is "default".
      * @param TopologyUserLinkConfig
@@ -202,7 +202,7 @@ public class TopologyNorthboundJAXRS {
 
     /**
      * Delete an User Link
-     * 
+     *
      * @param containerName
      *            Name of the Container. The base Container is "default".
      * @param name
index 1b19edc5f617bde3b5f66a6ffc2455055666ef38..db24755a2985e396f2128a5420ad819c425a7397 100644 (file)
@@ -22,23 +22,23 @@ import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class TopologyUserLinks {
-       @XmlElement
-       List<TopologyUserLinkConfig> userLinks;
-       
-       //To satisfy JAXB
-       private TopologyUserLinks() {
-               
-       }
-       
-       public List<TopologyUserLinkConfig> getUserLinks() {
-               return userLinks;
-       }
-
-       public void setUserLinks(List<TopologyUserLinkConfig> userLinks) {
-               this.userLinks = userLinks;
-       }
-
-       public TopologyUserLinks(List<TopologyUserLinkConfig> userLinks) {
-               this.userLinks = new ArrayList<TopologyUserLinkConfig>(userLinks);
-       }
+        @XmlElement
+        List<TopologyUserLinkConfig> userLinks;
+
+        //To satisfy JAXB
+        private TopologyUserLinks() {
+
+        }
+
+        public List<TopologyUserLinkConfig> getUserLinks() {
+                return userLinks;
+        }
+
+        public void setUserLinks(List<TopologyUserLinkConfig> userLinks) {
+                this.userLinks = userLinks;
+        }
+
+        public TopologyUserLinks(List<TopologyUserLinkConfig> userLinks) {
+                this.userLinks = new ArrayList<TopologyUserLinkConfig>(userLinks);
+        }
 }
index e40c5fbfbf63804c159f93505c7a6b9153af390d..a46e433054831408b9907b33f7d95443e1cf104e 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
   <servlet>
     <servlet-name>JAXRSTopology</servlet-name>
     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
     <url-pattern>/*</url-pattern>
   </servlet-mapping>
 
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>NB api</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>NB api</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
-       <login-config>
-               <auth-method>BASIC</auth-method>
-               <realm-name>opendaylight</realm-name>
-       </login-config>
+        <login-config>
+                <auth-method>BASIC</auth-method>
+                <realm-name>opendaylight</realm-name>
+        </login-config>
 </web-app>
index 0a22a573b75028c06fe77c77737af72e39aea8b7..ed4f3300bae2220e35416b6c7a76353a6472f3bc 100644 (file)
@@ -1,50 +1,50 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-       <modelVersion>4.0.0</modelVersion>
+        <modelVersion>4.0.0</modelVersion>
   <parent>
     <groupId>org.opendaylight.controller</groupId>
     <artifactId>commons.opendaylight</artifactId>
     <version>1.4.0-SNAPSHOT</version>
     <relativePath>../../../opendaylight/commons/opendaylight</relativePath>
   </parent>
-  
-       <groupId>org.opendaylight.controller</groupId>
-       <artifactId>northboundtest</artifactId>
-       <version>0.4.0-SNAPSHOT</version>
-       <packaging>bundle</packaging>
 
-       <build>
-               <plugins>
-                       <plugin>
-                               <groupId>org.apache.felix</groupId>
-                               <artifactId>maven-bundle-plugin</artifactId>
-                               <version>2.3.6</version>
-                               <extensions>true</extensions>
-                               <configuration>
-                                       <instructions>
-                                               <Import-Package>
-                                                       org.opendaylight.controller.sal.core,
-                                                       org.eclipse.osgi.framework.console,
-                                                       org.osgi.framework,
-                                       org.apache.felix.dm
-                                               </Import-Package>
-                                               <Export-Package>
-                                               </Export-Package>
-                                               <Bundle-Activator>
-                                         org.opendaylight.controller.northboundtest.unittestsuite.internal.Activator
-                                       </Bundle-Activator>
-                                               <Service-Component>
-                                               </Service-Component>
-                                       </instructions>
-                               </configuration>
-                       </plugin>
-               </plugins>
-       </build>
-       <dependencies>
-               <dependency>
-                       <groupId>org.opendaylight.controller</groupId>
-                       <artifactId>sal</artifactId>
-                       <version>0.4.0-SNAPSHOT</version>
-               </dependency>    
-       </dependencies>
+        <groupId>org.opendaylight.controller</groupId>
+        <artifactId>northboundtest</artifactId>
+        <version>0.4.0-SNAPSHOT</version>
+        <packaging>bundle</packaging>
+
+        <build>
+                <plugins>
+                        <plugin>
+                                <groupId>org.apache.felix</groupId>
+                                <artifactId>maven-bundle-plugin</artifactId>
+                                <version>2.3.6</version>
+                                <extensions>true</extensions>
+                                <configuration>
+                                        <instructions>
+                                                <Import-Package>
+                                                        org.opendaylight.controller.sal.core,
+                                                        org.eclipse.osgi.framework.console,
+                                                        org.osgi.framework,
+                                        org.apache.felix.dm
+                                                </Import-Package>
+                                                <Export-Package>
+                                                </Export-Package>
+                                                <Bundle-Activator>
+                                          org.opendaylight.controller.northboundtest.unittestsuite.internal.Activator
+                                        </Bundle-Activator>
+                                                <Service-Component>
+                                                </Service-Component>
+                                        </instructions>
+                                </configuration>
+                        </plugin>
+                </plugins>
+        </build>
+        <dependencies>
+                <dependency>
+                        <groupId>org.opendaylight.controller</groupId>
+                        <artifactId>sal</artifactId>
+                        <version>0.4.0-SNAPSHOT</version>
+                </dependency>
+        </dependencies>
 </project>
index 6b328961fc40d4936314a5880fb7f1c1139b84fe..9bcd7c0dc45229a4efa1cc845f20a51dc1bbb726 100644 (file)
@@ -24,22 +24,22 @@ public interface IInventoryShimInternalListener {
     /**
      * Updates node and its properties
      *
-     * @param node                     {@link org.opendaylight.controller.sal.core.Node} being updated
-     * @param type             {@link org.opendaylight.controller.sal.core.UpdateType}
-     * @param props            set of {@link org.opendaylight.controller.sal.core.Property} such as
-     *                                                 {@link org.opendaylight.controller.sal.core.Description} and/or
-     *                                                 {@link org.opendaylight.controller.sal.core.Tier} etc.
+     * @param node                      {@link org.opendaylight.controller.sal.core.Node} being updated
+     * @param type              {@link org.opendaylight.controller.sal.core.UpdateType}
+     * @param props             set of {@link org.opendaylight.controller.sal.core.Property} such as
+     *                                          {@link org.opendaylight.controller.sal.core.Description} and/or
+     *                                          {@link org.opendaylight.controller.sal.core.Tier} etc.
      */
     public void updateNode(Node node, UpdateType type, Set<Property> props);
 
     /**
      * Updates node connector and its properties
      *
-     * @param nodeConnector    {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
-     * @param type             {@link org.opendaylight.controller.sal.core.UpdateType}
-     * @param props            set of {@link org.opendaylight.controller.sal.core.Property} such as
-     *                                                 {@link org.opendaylight.controller.sal.core.Description} and/or
-     *                                                 {@link org.opendaylight.controller.sal.core.State} etc.
+     * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
+     * @param type              {@link org.opendaylight.controller.sal.core.UpdateType}
+     * @param props             set of {@link org.opendaylight.controller.sal.core.Property} such as
+     *                                          {@link org.opendaylight.controller.sal.core.Description} and/or
+     *                                          {@link org.opendaylight.controller.sal.core.State} etc.
      */
     public void updateNodeConnector(NodeConnector nodeConnector,
             UpdateType type, Set<Property> props);
index 74dc84aec9613671bb24a17bfd38f788b5c8f35d..d619b7377672616e538ecd161473fc8453a91015 100644 (file)
@@ -80,7 +80,7 @@ public interface IOFStatisticsManager {
      *                                  For port statistics, it is the port id. If null the query
      *                                  will be performed for all the targets for the specified
      *                                  statistics type.
-     * 
+     *
      * @param timeout the timeout in milliseconds the system will wait for a response
      *                  from the switch, before declaring failure
      * @return the list of openflow statistics
index fd762d4aa9376a24ceb6cd48105f4b0b8744280e..9fca60f1a039d1b9514469ad0410024b0b2147ce 100644 (file)
 package org.opendaylight.controller.protocol_plugin.openflow;
 
 /**
- * @file       IRefreshInternalProvider.java
+ * @file        IRefreshInternalProvider.java
  *
- * @brief      Topology refresh notifications requested by application
- *                     to be fetched from the plugin
+ * @brief       Topology refresh notifications requested by application
+ *                      to be fetched from the plugin
  *
  * For example, an application that has been started late, will want to
  * be up to date with the latest topology.  Hence, it requests for a
index 4f15a1055a324b74d11a6454ebe4ccb8292a979e..d837e01c01a5c89546fa10af9185521192c81cc7 100644 (file)
@@ -8,6 +8,6 @@ import org.openflow.protocol.statistics.OFDescriptionStatistics;
  * is updated with new one.
  */
 public interface IStatisticsListener {
-       public void descriptionRefreshed(Long switchId,
-                                       OFDescriptionStatistics description);
+        public void descriptionRefreshed(Long switchId,
+                                        OFDescriptionStatistics description);
 }
index e90823726c926d70304666055445b06df7ee4558..45c0025b54ea2eda642f3c82b79e85b0f58f733a 100644 (file)
@@ -22,7 +22,7 @@ import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
 public interface ITopologyServiceShimListener {
     /**
      * Called to update on Edge in the topology graph
-     * 
+     *
      * @param topoedgeupdateList
      *            List of topoedgeupdates Each topoedgeupdate includes edge, its
      *            Properties ( BandWidth and/or Latency etc) and update type.
@@ -32,7 +32,7 @@ public interface ITopologyServiceShimListener {
     /**
      * Called when an Edge utilization is above the safe threshold configured on
      * the controller
-     * 
+     *
      * @param {@link org.opendaylight.controller.sal.core.Edge}
      */
     public void edgeOverUtilized(Edge edge);
@@ -40,7 +40,7 @@ public interface ITopologyServiceShimListener {
     /**
      * Called when the Edge utilization is back to normal, below the safety
      * threshold level configured on the controller
-     * 
+     *
      * @param {@link org.opendaylight.controller.sal.core.Edge}
      */
     public void edgeUtilBackToNormal(Edge edge);
index 8fb9a6acb8a2c498533ce15db5161af7a28d6562..ce91e1f2750ce1343ecac5d39488b2b9993a9c31 100644 (file)
@@ -19,35 +19,35 @@ import org.openflow.protocol.OFMessage;
  * encryption and decryption of the network data.
  */
 public interface IMessageReadWrite {
-       /**
-        * Sends the OF message out over the socket channel. For secure
-        * communication, the data will be encrypted.
-        * 
-        * @param msg OF message to be sent
-        * @throws Exception
-        */
-       public void asyncSend(OFMessage msg) throws Exception;
-
-       /**
-        * Resumes sending the remaining messages in the outgoing buffer
-        * @throws Exception
-        */
-       public void resumeSend() throws Exception;
-
-       /**
-        * Reads the incoming network data from the socket and retrieves the OF
-        * messages. For secure communication, the data will be decrypted first.
-        * 
-        * @return list of OF messages
-        * @throws Exception
-        */
+        /**
+         * Sends the OF message out over the socket channel. For secure
+         * communication, the data will be encrypted.
+         *
+         * @param msg OF message to be sent
+         * @throws Exception
+         */
+        public void asyncSend(OFMessage msg) throws Exception;
+
+        /**
+         * Resumes sending the remaining messages in the outgoing buffer
+         * @throws Exception
+         */
+        public void resumeSend() throws Exception;
+
+        /**
+         * Reads the incoming network data from the socket and retrieves the OF
+         * messages. For secure communication, the data will be decrypted first.
+         *
+         * @return list of OF messages
+         * @throws Exception
+         */
     public List<OFMessage> readMessages() throws Exception;
-    
-       /**
-        * Proper clean up when the switch connection is closed
-        * 
-        * @return
-        * @throws Exception
-        */
+
+        /**
+         * Proper clean up when the switch connection is closed
+         *
+         * @return
+         * @throws Exception
+         */
     public void stop() throws Exception;
 }
index 196fbbfb4c454e0ff6f748cf2a11dc50d7186c16..41da311fd916dc8c1913b98f19976d9b319bf7d8 100644 (file)
@@ -19,54 +19,54 @@ import org.openflow.protocol.OFStatisticsRequest;
 
 /**
  * This interface defines an abstraction of an Open Flow Switch.
- * 
+ *
  */
 public interface ISwitch {
     /**
      * Gets a unique XID.
-     * 
+     *
      * @return XID
      */
     public int getNextXid();
 
     /**
      * Returns the Switch's ID.
-     * 
+     *
      * @return the Switch's ID
      */
     public Long getId();
 
     /**
      * Returns the Switch's table numbers supported by datapath
-     * 
+     *
      * @return the tables
      */
     public Byte getTables();
 
     /**
      * Returns the Switch's bitmap of supported ofp_action_type
-     * 
+     *
      * @return the actions
      */
     public Integer getActions();
 
     /**
      * Returns the Switch's bitmap of supported ofp_capabilities
-     * 
+     *
      * @return the capabilities
      */
     public Integer getCapabilities();
 
     /**
      * Returns the Switch's buffering capacity in Number of Pkts
-     * 
+     *
      * @return the buffers
      */
     public Integer getBuffers();
 
     /**
      * Returns the Date when the switch was connected.
-     * 
+     *
      * @return Date The date when the switch was connected
      */
     public Date getConnectedDate();
@@ -77,7 +77,7 @@ public interface ISwitch {
      * should be used for non-critical messages such as statistics request,
      * discovery packets, etc. An unique XID is generated automatically and
      * inserted into the message.
-     * 
+     *
      * @param msg
      *            The OF message to be sent
      * @return The XID used
@@ -89,7 +89,7 @@ public interface ISwitch {
      * priority. It will be served after high priority messages. The method
      * should be used for non-critical messages such as statistics request,
      * discovery packets, etc. The specified XID is inserted into the message.
-     * 
+     *
      * @param msg
      *            The OF message to be Sent
      * @param xid
@@ -104,7 +104,7 @@ public interface ISwitch {
      * method should be used for critical messages such as hello, echo reply
      * etc. An unique XID is generated automatically and inserted into the
      * message.
-     * 
+     *
      * @param msg
      *            The OF message to be sent
      * @return The XID used
@@ -116,7 +116,7 @@ public interface ISwitch {
      * priority. It will be served first before normal priority messages. The
      * method should be used for critical messages such as hello, echo reply
      * etc. The specified XID is inserted into the message.
-     * 
+     *
      * @param msg
      *            The OF message to be sent
      * @return The XID used
@@ -126,7 +126,7 @@ public interface ISwitch {
     /**
      * Sends the OF message followed by a Barrier Request with a unique XID
      * which is automatically generated, and waits for a result from the switch.
-     * 
+     *
      * @param msg
      *            The message to be sent
      * @return An Object which has one of the followings instances/values:
@@ -141,21 +141,21 @@ public interface ISwitch {
 
     /**
      * Returns a map containing all OFPhysicalPorts of this switch.
-     * 
+     *
      * @return The Map of OFPhysicalPort
      */
     public Map<Short, OFPhysicalPort> getPhysicalPorts();
 
     /**
      * Returns a Set containing all port IDs of this switch.
-     * 
+     *
      * @return The Set of port ID
      */
     public Set<Short> getPorts();
 
     /**
      * Returns OFPhysicalPort of the specified portNumber of this switch.
-     * 
+     *
      * @param portNumber
      *            The port ID
      * @return OFPhysicalPort for the specified PortNumber
@@ -164,7 +164,7 @@ public interface ISwitch {
 
     /**
      * Returns the bandwidth of the specified portNumber of this switch.
-     * 
+     *
      * @param portNumber
      *            the port ID
      * @return bandwidth
@@ -173,7 +173,7 @@ public interface ISwitch {
 
     /**
      * Returns True if the port is enabled,
-     * 
+     *
      * @param portNumber
      * @return True if the port is enabled
      */
@@ -181,7 +181,7 @@ public interface ISwitch {
 
     /**
      * Returns True if the port is enabled.
-     * 
+     *
      * @param port
      * @return True if the port is enabled
      */
@@ -189,7 +189,7 @@ public interface ISwitch {
 
     /**
      * Returns a list containing all enabled ports of this switch.
-     * 
+     *
      * @return: List containing all enabled ports of this switch
      */
     public List<OFPhysicalPort> getEnabledPorts();
@@ -197,7 +197,7 @@ public interface ISwitch {
     /**
      * Sends OFStatisticsRequest with a unique XID generated automatically and
      * waits for a result from the switch.
-     * 
+     *
      * @param req
      *            the OF Statistic Request to be sent
      * @return Object has one of the following instances/values::
@@ -211,7 +211,7 @@ public interface ISwitch {
     /**
      * Returns true if the switch has reached the operational state (has sent
      * FEATURE_REPLY to the controller).
-     * 
+     *
      * @return true if the switch is operational
      */
     public boolean isOperational();
index 2863070cc5a7a34ff0f2d95475cd5a9359a443f3..7fb5f9fcf134c2b83a4d6534dca9356af206103b 100644 (file)
@@ -107,7 +107,7 @@ public class Controller implements IController, CommandProvider {
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
-     * 
+     *
      */
     public void init() {
         logger.debug("Initializing!");
@@ -122,7 +122,7 @@ public class Controller implements IController, CommandProvider {
     /**
      * Function called by dependency manager after "init ()" is called and after
      * the services provided by the class are registered in the service registry
-     * 
+     *
      */
     public void start() {
         logger.debug("Starting!");
@@ -145,7 +145,7 @@ public class Controller implements IController, CommandProvider {
      * Function called by the dependency manager before the services exported by
      * the component are unregistered, this will be followed by a "destroy ()"
      * calls
-     * 
+     *
      */
     public void stop() {
         for (Iterator<Entry<Long, ISwitch>> it = switches.entrySet().iterator(); it
@@ -166,7 +166,7 @@ public class Controller implements IController, CommandProvider {
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     public void destroy() {
     }
@@ -224,7 +224,7 @@ public class Controller implements IController, CommandProvider {
                     instanceName);
             switchHandler.start();
             if (sc.isConnected()) {
-                logger.info("Switch:{} is connected to the Controller", 
+                logger.info("Switch:{} is connected to the Controller",
                         sc.socket().getRemoteSocketAddress()
                         .toString().split("/")[1]);
             }
index d2dab0fc94483b4827890d087c996e0c9ebe3a09..fc2e0ee324b2cc4934a1f4181988cf674d6bebc1 100644 (file)
@@ -52,7 +52,7 @@ public class MessageReadWriteService implements IMessageReadWrite {
 
     /**
      * Sends the OF message out over the socket channel.
-     * 
+     *
      * @param msg
      *            OF message to be sent
      * @throws Exception
@@ -90,7 +90,7 @@ public class MessageReadWriteService implements IMessageReadWrite {
 
     /**
      * Resumes sending the remaining messages in the outgoing buffer
-     * 
+     *
      * @throws Exception
      */
     @Override
@@ -116,7 +116,7 @@ public class MessageReadWriteService implements IMessageReadWrite {
     /**
      * Reads the incoming network data from the socket and retrieves the OF
      * messages.
-     * 
+     *
      * @return list of OF messages
      * @throws Exception
      */
index 6a2cb9e9c4f576949a79a1b63976605a3970d95f..7893ae0acca4f37e22a6fecee532b902652d2f0f 100644 (file)
@@ -10,7 +10,6 @@ package org.opendaylight.controller.protocol_plugin.openflow.core.internal;
 
 import java.util.concurrent.atomic.AtomicLong;
 
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
 import org.openflow.protocol.OFMessage;
 
 /**
@@ -22,7 +21,7 @@ class PriorityMessage {
     final static AtomicLong seq = new AtomicLong();
     final long seqNum;
     boolean syncReply; // set to true if we want to be blocked until the response arrives
-    
+
     public PriorityMessage(OFMessage msg, int priority) {
         this.msg = msg;
         this.priority = priority;
index 43a64814d8498a1842ae9f4e2ce4ee75a08aca2f..64031fd01212cceeaaed4ae95b65a0db3904f3da 100644 (file)
@@ -71,7 +71,7 @@ public class SecureMessageReadWriteService implements IMessageReadWrite {
 
     /**
      * Bring up secure channel using SSL Engine
-     * 
+     *
      * @param socket
      *            TCP socket channel
      * @throws Exception
@@ -143,7 +143,7 @@ public class SecureMessageReadWriteService implements IMessageReadWrite {
     /**
      * Sends the OF message out over the socket channel. The message is
      * encrypted by SSL Engine.
-     * 
+     *
      * @param msg
      *            OF message to be sent
      * @throws Exception
@@ -196,7 +196,7 @@ public class SecureMessageReadWriteService implements IMessageReadWrite {
 
     /**
      * Resumes sending the remaining messages in the outgoing buffer
-     * 
+     *
      * @throws Exception
      */
     @Override
@@ -234,7 +234,7 @@ public class SecureMessageReadWriteService implements IMessageReadWrite {
     /**
      * Reads the incoming network data from the socket, decryptes them and then
      * retrieves the OF messages.
-     * 
+     *
      * @return list of OF messages
      * @throws Exception
      */
index dc84304a047573307e62fa0205fc2ff6dce16a71..2d8cdd206a7e2c651151c6515e003ba8e862c8fa 100644 (file)
@@ -131,7 +131,7 @@ public class DataPacketMuxDemux implements IContainerListener,
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
-     * 
+     *
      */
     void init() {
         this.controller.addMessageListener(OFType.PACKET_IN, this);
@@ -141,7 +141,7 @@ public class DataPacketMuxDemux implements IContainerListener,
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
         this.controller.removeMessageListener(OFType.PACKET_IN, this);
index e2945628868d0b4e1b6477e2f4285353f0d3f941..ffd5fd4315747e40c7bf16b298c98f7c1bbd34eb 100644 (file)
@@ -28,7 +28,7 @@ public class DescStatisticsConverter {
 
     public DescStatisticsConverter(List<OFStatistics> statsList) {
         this.hwDesc = null;
-        this.ofDesc = (statsList == null || statsList.isEmpty())? 
+        this.ofDesc = (statsList == null || statsList.isEmpty())?
                 null : (OFDescriptionStatistics) statsList.get(0);
     }
 
index 3be6f22742432795a55f17540fa03b8792b1bac9..c3833d224626832b821dea92503f5b41b756faed 100644 (file)
@@ -933,20 +933,20 @@ public class DiscoveryService implements IInventoryShimExternalListener,
         help.append("\t pcc                             - Print CC info\n");
         help.append("\t psize                           - Print sizes of all the lists\n");
         help.append("\t ptm                             - Print timeout info\n");
-        help.append("\t ecc                            - Enable CC\n");
-        help.append("\t dcc                            - Disable CC\n");
+        help.append("\t ecc                             - Enable CC\n");
+        help.append("\t dcc                             - Disable CC\n");
         help.append("\t scc [multiple]                  - Set/show CC multiple and interval\n");
-        help.append("\t sports [ports]                         - Set/show max ports per batch\n");
+        help.append("\t sports [ports]                  - Set/show max ports per batch\n");
         help.append("\t spause [ticks]                  - Set/show pause period\n");
-        help.append("\t sdi [ticks]                            - Set/show discovery interval in ticks\n");
+        help.append("\t sdi [ticks]                     - Set/show discovery interval in ticks\n");
         help.append("\t stm [ticks]                     - Set/show per timeout ticks\n");
-        help.append("\t sretry [count]                         - Set/show num of retries\n");
-        help.append("\t addsw <swid>                   - Add a switch\n");
-        help.append("\t remsw <swid>                   - Remove a switch\n");
+        help.append("\t sretry [count]                  - Set/show num of retries\n");
+        help.append("\t addsw <swid>                    - Add a switch\n");
+        help.append("\t remsw <swid>                    - Remove a switch\n");
         help.append("\t page                            - Print aging info\n");
         help.append("\t sage                            - Set/Show aging time limit\n");
-        help.append("\t eage                           - Enable aging\n");
-        help.append("\t dage                           - Disable aging\n");
+        help.append("\t eage                            - Enable aging\n");
+        help.append("\t dage                            - Disable aging\n");
         help.append("\t pthrot                          - Print throttling\n");
         help.append("\t ethrot                          - Enable throttling\n");
         help.append("\t dthrot                          - Disable throttling\n");
@@ -1048,7 +1048,7 @@ public class DiscoveryService implements IInventoryShimExternalListener,
             }
         }
         ci.println("\n");
-        ci.println("              NodeConnector                                                Edge ");
+        ci.println("              NodeConnector                                                 Edge ");
         Set<NodeConnector> keySet = prodMap.keySet();
         if (keySet == null) {
             return;
index cad0dfa8078e0d642339d4f49d55ae4015290c75..2a62d6c34a08a19c4cccb898acdf90945ada255b 100644 (file)
@@ -37,7 +37,7 @@ public class FlowProgrammerNotifier implements IFlowProgrammerNotifier {
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
         logger.debug("DESTROY called!");
@@ -46,7 +46,7 @@ public class FlowProgrammerNotifier implements IFlowProgrammerNotifier {
     /**
      * Function called by dependency manager after "init ()" is called and after
      * the services provided by the class are registered in the service registry
-     * 
+     *
      */
     void start() {
         logger.debug("START called!");
@@ -56,7 +56,7 @@ public class FlowProgrammerNotifier implements IFlowProgrammerNotifier {
      * Function called by the dependency manager before the services exported by
      * the component are unregistered, this will be followed by a "destroy ()"
      * calls
-     * 
+     *
      */
     void stop() {
         logger.debug("STOP called!");
index 96ea6cd14f9612aa80a328faab5b1160277ec0e7..f58acf62edb0962703b9e4971e582bc412314c47 100644 (file)
@@ -110,7 +110,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
-     * 
+     *
      */
     void init() {
         this.controller.addMessageListener(OFType.FLOW_REMOVED, this);
@@ -122,7 +122,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
     }
@@ -130,7 +130,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
     /**
      * Function called by dependency manager after "init ()" is called and after
      * the services provided by the class are registered in the service registry
-     * 
+     *
      */
     void start() {
     }
@@ -139,7 +139,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
      * Function called by the dependency manager before the services exported by
      * the component are unregistered, this will be followed by a "destroy ()"
      * calls
-     * 
+     *
      */
     void stop() {
     }
@@ -201,7 +201,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
                      * will be inserted automatically to synchronize the
                      * progression.
                      */
-                    result = asyncMsgSend(node, sw, msg, rid);  
+                    result = asyncMsgSend(node, sw, msg, rid);
                 }
                 return getStatusInternal(result, action, rid);
             } else {
@@ -392,7 +392,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
         if ((rid == null) || (rid == 0)) {
             return;
         }
-        
+
         /*
          * Notifies the caller that error has been reported for a previous flow
          * programming request
@@ -466,7 +466,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
         return new Status(StatusCode.INTERNALERROR,
                 "Failed to send Barrier message.");
     }
-    
+
     @Override
     public Status asyncSendBarrierMessage(Node node) {
         if (!node.getType().equals(NodeIDType.OPENFLOW)) {
@@ -489,14 +489,14 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
         return new Status(StatusCode.INTERNALERROR,
                 "Failed to send Barrier message.");
     }
-    
+
     /**
      * This method sends the message asynchronously until the number of messages
      * sent reaches a threshold. Then a Barrier message is sent automatically
      * for sync purpose. An unique Request ID associated with the message is
      * passed down by the caller. The Request ID will be returned to the caller
      * when an error message is received from the switch.
-     * 
+     *
      * @param node
      *            The node
      * @param msg
@@ -514,25 +514,25 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
 
         xid = sw.asyncSend(msg);
         addXid2Rid(swid, xid, rid);
-        
+
         Map<Integer, Long> swxid2rid = this.xid2rid.get(swid);
         if (swxid2rid == null) {
             return result;
         }
-        
+
         int size = swxid2rid.size();
         if (size % barrierMessagePriorCount == 0) {
             result = asyncSendBarrierMessage(node);
         }
-        
+
         return result;
     }
-    
+
     /**
      * A number of async messages are sent followed by a synchronous Barrier
      * message. This method returns the maximum async messages that can be sent
      * before the Barrier message.
-     * 
+     *
      * @return The max count of async messages sent prior to Barrier message
      */
     private int getBarrierMessagePriorCount() {
@@ -548,11 +548,11 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
 
         return rv;
     }
-    
+
     /**
      * This method returns the message Request ID previously assigned by the
      * caller for a given OF message xid
-     * 
+     *
      * @param swid
      *            The switch id
      * @param xid
@@ -576,14 +576,14 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
     /**
      * This method returns a copy of outstanding xid to rid mappings.for a given
      * switch
-     * 
+     *
      * @param swid
      *            The switch id
      * @return a copy of xid2rid mappings
      */
     public Map<Integer, Long> getSwXid2Rid(long swid) {
         Map<Integer, Long> swxid2rid = this.xid2rid.get(swid);
-        
+
         if (swxid2rid != null) {
             return new HashMap<Integer, Long>(swxid2rid);
         } else {
@@ -593,7 +593,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
 
     /**
      * Adds xid to rid mapping to the local DB
-     * 
+     *
      * @param swid
      *            The switch id
      * @param xid
@@ -611,7 +611,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
     /**
      * When an Error message is received, this method will be invoked to remove
      * the offending xid from the local DB.
-     * 
+     *
      * @param swid
      *            The switch id
      * @param xid
@@ -626,7 +626,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
 
     /**
      * Convert various result into Status
-     * 
+     *
      * @param result
      *            The returned result from previous action
      * @param action
@@ -652,11 +652,11 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
                     "send", action, "Internal Error"));
         }
     }
-    
+
     /**
      * When a Barrier reply is received, this method will be invoked to clear
      * the local DB
-     * 
+     *
      * @param swid
      *            The switch id
      */
@@ -670,7 +670,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
     @Override
     public void updateNode(Node node, UpdateType type, Set<Property> props) {
         long swid = (Long)node.getID();
-        
+
         switch (type) {
         case ADDED:
             Map<Integer, Long> swxid2rid = new HashMap<Integer, Long>();
@@ -712,7 +712,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
             ci.println("Please enter a valid node id");
             return;
         }
-        
+
         long sid;
         try {
             sid = HexEncode.stringToLong(st);
@@ -720,7 +720,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
             ci.println("Please enter a valid node id");
             return;
         }
-        
+
         Map<Integer, Long> swxid2rid = this.xid2rid.get(sid);
         if (swxid2rid == null) {
             ci.println("The node id entered does not exist");
@@ -728,7 +728,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService,
         }
 
         ci.println("xid             rid");
-        
+
         Set<Integer> xidSet = swxid2rid.keySet();
         if (xidSet == null) {
             return;
index 7afe6ce5be9a863d49938aa80c1576ef68e4ecf4..82dbf670a9517ee1b998442f2d524f37628f5815 100644 (file)
@@ -23,9 +23,9 @@ import org.slf4j.LoggerFactory;
 /**
  * Converts an openflow list of flow statistics in a SAL list of FlowOnNode
  * objects
- * 
- * 
- * 
+ *
+ *
+ *
  */
 public class FlowStatisticsConverter {
     private static final Logger log = LoggerFactory
index ec6ea1223e71f6103fcfef6aecb655c1108e6179..4869a9500b489ca58c1eaf72359fb8aaeb72cd12 100644 (file)
@@ -53,6 +53,7 @@ public class InventoryService implements IInventoryShimInternalListener,
     private ConcurrentMap<Node, Map<String, Property>> nodeProps; // properties are maintained in global container only
     private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps; // properties are maintained in global container only
     private boolean isDefaultContainer = false;
+    private String containerName = null;
 
     void setController(IController s) {
         this.controller = s;
@@ -75,7 +76,7 @@ public class InventoryService implements IInventoryShimInternalListener,
 
         Dictionary props = c.getServiceProperties();
         if (props != null) {
-            String containerName = (String) props.get("containerName");
+            containerName = (String) props.get("containerName");
             isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT
                     .toString());
         }
@@ -146,6 +147,7 @@ public class InventoryService implements IInventoryShimInternalListener,
      */
     @Override
     public ConcurrentMap<Node, Map<String, Property>> getNodeProps() {
+        logger.debug("getNodePros for container {}", containerName);
         return nodeProps;
     }
 
@@ -212,15 +214,30 @@ public class InventoryService implements IInventoryShimInternalListener,
     }
 
     private void addNode(Node node, Set<Property> props) {
-        logger.trace("{} added, props: {}", node, props);
         if (nodeProps == null) {
             return;
         }
 
+        Set<Node> nodeSet = nodeProps.keySet();
+        if (((props == null) || props.isEmpty()) && (nodeSet != null)
+                && nodeSet.contains(node)) {
+            // node already added
+            return;
+        }
+
+        logger.trace("addNode: {} added, props: {} for container {}",
+                new Object[] { node, props, containerName });
+
         // update local cache
-        Map<String, Property> propMap = new HashMap<String, Property>();
-        for (Property prop : props) {
-            propMap.put(prop.getName(), prop);
+        Map<String, Property> propMap = nodeProps.get(node);
+        if (propMap == null) {
+            propMap = new HashMap<String, Property>();
+        }
+
+        if (props != null) {
+            for (Property prop : props) {
+                propMap.put(prop.getName(), prop);
+            }
         }
         nodeProps.put(node, propMap);
 
index 33afa9463338d7168458b1618edbac2acd6438b8..5e5f056c5aba0002a8cb1e3178ca9d1dddf842c3 100644 (file)
@@ -108,27 +108,27 @@ public class InventoryServiceHelper {
         if (bw != null) {
             props.add(bw);
         }
-        
+
         Bandwidth abw = InventoryServiceHelper.OFPortToBandWidth(port.getAdvertisedFeatures());
         if (abw != null) {
-               AdvertisedBandwidth a = new AdvertisedBandwidth(abw.getValue());
-               if (a != null) {
-                       props.add(a);
-               }
+                AdvertisedBandwidth a = new AdvertisedBandwidth(abw.getValue());
+                if (a != null) {
+                        props.add(a);
+                }
         }
         Bandwidth sbw = InventoryServiceHelper.OFPortToBandWidth(port.getSupportedFeatures());
         if (sbw != null) {
-               SupportedBandwidth s = new SupportedBandwidth(sbw.getValue());
-               if (s != null) {
-                       props.add(s);
-               }
+                SupportedBandwidth s = new SupportedBandwidth(sbw.getValue());
+                if (s != null) {
+                        props.add(s);
+                }
         }
         Bandwidth pbw = InventoryServiceHelper.OFPortToBandWidth(port.getPeerFeatures());
         if (pbw != null) {
-               PeerBandwidth p = new PeerBandwidth(pbw.getValue());
-               if (p != null) {
-                       props.add(p);
-               }
+                PeerBandwidth p = new PeerBandwidth(pbw.getValue());
+                if (p != null) {
+                        props.add(p);
+                }
         }
         props.add(new Name(port.getName()));
         props.add(InventoryServiceHelper.OFPortToConfig(port.getConfig()));
index f7210a333bd870d87216128b73cffb8a8402842f..e2d77b5b73f1b1c3c73da363b2f40949319c0a0a 100644 (file)
@@ -236,6 +236,8 @@ public class InventoryServiceShim implements IContainerListener,
     @Override
     public void tagUpdated(String containerName, Node n, short oldTag,
             short newTag, UpdateType t) {
+        logger.debug("tagUpdated: {} type {} for container {}", new Object[] {
+                n, t, containerName });
     }
 
     @Override
@@ -246,6 +248,8 @@ public class InventoryServiceShim implements IContainerListener,
     @Override
     public void nodeConnectorUpdated(String containerName, NodeConnector p,
             UpdateType t) {
+        logger.debug("nodeConnectorUpdated: {} type {} for container {}",
+                new Object[] { p, t, containerName });
         if (this.containerMap == null) {
             logger.error("containerMap is NULL");
             return;
@@ -283,6 +287,7 @@ public class InventoryServiceShim implements IContainerListener,
 
         // notify InventoryService
         notifyInventoryShimInternalListener(containerName, p, t, null);
+        notifyInventoryShimInternalListener(containerName, p.getNode(), t, null);
     }
 
     private void notifyInventoryShimExternalListener(Node node,
@@ -308,7 +313,7 @@ public class InventoryServiceShim implements IContainerListener,
                     type, props);
             logger.trace(
                     "notifyInventoryShimInternalListener {} type {} for container {}",
-                    nodeConnector, type, container);
+                    new Object[] { nodeConnector, type, container });
         }
     }
 
@@ -373,6 +378,18 @@ public class InventoryServiceShim implements IContainerListener,
         notifyInventoryShimExternalListener(node, type, props);
     }
 
+    private void notifyInventoryShimInternalListener(String container,
+            Node node, UpdateType type, Set<Property> props) {
+        IInventoryShimInternalListener inventoryShimInternalListener = inventoryShimInternalListeners
+                .get(container);
+        if (inventoryShimInternalListener != null) {
+            inventoryShimInternalListener.updateNode(node, type, props);
+            logger.trace(
+                    "notifyInventoryShimInternalListener {} type {} for container {}",
+                    new Object[] { node, type, container });
+        }
+    }
+
     private void addNode(ISwitch sw) {
         Node node;
         try {
index 78fddc773637c8aefb338b729d4e416e66e85441..21a632e1de0226dadfd035b432f2dec85f5a57f2 100644 (file)
@@ -129,7 +129,7 @@ IInventoryShimExternalListener, CommandProvider {
 
         /**
          * Returns the average transmit rate in bps
-         * 
+         *
          * @return the average transmit rate [bps]
          */
         public long getAverageTxRate() {
@@ -162,7 +162,7 @@ IInventoryShimExternalListener, CommandProvider {
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
-     * 
+     *
      */
     void init() {
         flowStatistics = new ConcurrentHashMap<Long, List<OFStatistics>>();
@@ -227,7 +227,7 @@ IInventoryShimExternalListener, CommandProvider {
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
     }
@@ -235,7 +235,7 @@ IInventoryShimExternalListener, CommandProvider {
     /**
      * Function called by dependency manager after "init ()" is called and after
      * the services provided by the class are registered in the service registry
-     * 
+     *
      */
     void start() {
         // Start managed timers
@@ -255,7 +255,7 @@ IInventoryShimExternalListener, CommandProvider {
      * Function called by the dependency manager before the services exported by
      * the component are unregistered, this will be followed by a "destroy ()"
      * calls
-     * 
+     *
      */
     void stop() {
         // Stop managed timers
@@ -896,7 +896,7 @@ IInventoryShimExternalListener, CommandProvider {
     /**
      * Update the cached port rates for this switch with the latest retrieved
      * port transmit byte count
-     * 
+     *
      * @param switchId
      */
     private synchronized void updatePortsTxRate(long switchId) {
index 410781683bdbd424f8fc2ffbb87118459890f40e..0b605ab875a145ff1935f56453d087b2e9115314 100644 (file)
@@ -20,9 +20,9 @@ import org.slf4j.LoggerFactory;
 /**
  * Abstract class which provides the utilities for converting the Openflow port
  * number to the equivalent NodeConnector and vice versa
- * 
- * 
- * 
+ *
+ *
+ *
  */
 public abstract class PortConverter {
     private static final Logger log = LoggerFactory
index 3fbf68fbc1746723f9c7119947e077ca2acfd5e0..b18eae971b9526fef38a927b798c0a1dccc8e9d9 100644 (file)
@@ -22,9 +22,9 @@ import org.slf4j.LoggerFactory;
 /**
  * Converts an openflow list of port statistics in a SAL list of
  * NodeConnectorStatistics objects
- * 
- * 
- * 
+ *
+ *
+ *
  */
 public class PortStatisticsConverter {
     private static final Logger log = LoggerFactory
index bcb01b1392ac8661f2ee6aeb3db5e34c47362a41..22e8a4dc74eb897847c0d2835f9060f3f506ea01 100644 (file)
@@ -284,9 +284,9 @@ public class ReadServiceFilter implements IPluginReadServiceFilter,
     /**
      * Returns whether the passed NodeConnector belongs to the container
      *
-     * @param container        container name
-     * @param p                node connector to test
-     * @return                 true if belongs false otherwise
+     * @param container container name
+     * @param p     node connector to test
+     * @return          true if belongs false otherwise
      */
     public boolean containerOwnsNodeConnector(String container, NodeConnector p) {
         // All node connectors belong to the default container
@@ -300,9 +300,9 @@ public class ReadServiceFilter implements IPluginReadServiceFilter,
     /**
      * Returns whether the passed NodeConnector belongs to the container
      *
-     * @param container        container name
-     * @param table            node table to test
-     * @return                 true if belongs false otherwise
+     * @param container container name
+     * @param table     node table to test
+     * @return          true if belongs false otherwise
      */
     public boolean containerOwnsNodeTable(String container, NodeTable table) {
         // All node table belong to the default container
index b23737c52037058d246d18bad2acd32caf52abc6..68572fb65086ef4c7901dc4179caf03e57c12233 100644 (file)
@@ -32,7 +32,7 @@ public class TopologyServices implements ITopologyServiceShimListener,
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
-     * 
+     *
      */
     @SuppressWarnings("unchecked")
     void init(Component c) {
@@ -46,7 +46,7 @@ public class TopologyServices implements ITopologyServiceShimListener,
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
         logger.trace("DESTROY called!");
@@ -55,7 +55,7 @@ public class TopologyServices implements ITopologyServiceShimListener,
     /**
      * Function called by dependency manager after "init ()" is called and after
      * the services provided by the class are registered in the service registry
-     * 
+     *
      */
     void start() {
         logger.trace("START called!");
@@ -65,7 +65,7 @@ public class TopologyServices implements ITopologyServiceShimListener,
      * Function called by the dependency manager before the services exported by
      * the component are unregistered, this will be followed by a "destroy ()"
      * calls
-     * 
+     *
      */
     void stop() {
         logger.trace("STOP called!");
@@ -73,7 +73,7 @@ public class TopologyServices implements ITopologyServiceShimListener,
 
     /**
      * Retrieve SAL service IPluginOutTopologyService
-     * 
+     *
      * @param s
      *            Called by Dependency Manager as soon as the SAL service is
      *            available
@@ -85,7 +85,7 @@ public class TopologyServices implements ITopologyServiceShimListener,
 
     /**
      * called when SAL service IPluginOutTopologyService is no longer available
-     * 
+     *
      * @param s
      *            Called by Dependency Manager as soon as the SAL service is
      *            unavailable
@@ -99,7 +99,7 @@ public class TopologyServices implements ITopologyServiceShimListener,
 
     /**
      * Retrieve OF protocol_plugin service IRefreshInternalProvider
-     * 
+     *
      * @param s
      *            Called by Dependency Manager as soon as the SAL service is
      *            available
@@ -112,7 +112,7 @@ public class TopologyServices implements ITopologyServiceShimListener,
     /**
      * called when OF protocol_plugin service IRefreshInternalProvider is no
      * longer available
-     * 
+     *
      * @param s
      *            Called by Dependency Manager as soon as the SAL service is
      *            unavailable
index f1ce03af281ffbfe51846173f6ebbc744e4d37d1..4f7bf4889fd6b6d1c59a07e9d06f384a3ae3f54b 100644 (file)
@@ -33,7 +33,7 @@ public abstract class Utils {
             er.readFrom(bb);
             return er.toString();
         }
-        
+
         // Handle OF1.0 errors here
         OFErrorType et = OFErrorType.values()[0xffff & error.getErrorType()];
         String errorStr = "Error : " + et.toString();
index c52c3f56b800a57ff247bc4a7246db2b3065c49d..9e44073e21a2f7376def5edd8f57458b1a7b3291 100644 (file)
@@ -6,21 +6,21 @@ import java.util.Arrays;
 import org.openflow.protocol.OFError;
 
 public class V6Error extends OFError {
-       private static final long serialVersionUID = 1L;
-       public static int MINIMUM_LENGTH = 20;//OfHdr(8) + NXET_VENDOR(2) + NXEC_VENDOR_ERROR(2) + struct nx_vendor_error(8)
-       public static final short NICIRA_VENDOR_ERRORTYPE = (short)0xb0c2;
-       protected int V6VendorId;
+        private static final long serialVersionUID = 1L;
+        public static int MINIMUM_LENGTH = 20;//OfHdr(8) + NXET_VENDOR(2) + NXEC_VENDOR_ERROR(2) + struct nx_vendor_error(8)
+        public static final short NICIRA_VENDOR_ERRORTYPE = (short)0xb0c2;
+        protected int V6VendorId;
     protected short V6VendorErrorType;
     protected short V6VendorErrorCode;
     protected byte[] V6ErrorData;
-    
+
     public V6Error(OFError e) {
         this.length = (short)e.getLengthU();
         this.errorType = e.getErrorType();
         this.errorCode = e.getErrorCode();
         this.xid = e.getXid();
     }
-    
+
     @Override
     public void readFrom(ByteBuffer data) {
         this.V6VendorId = data.getInt();
@@ -30,37 +30,37 @@ public class V6Error extends OFError {
         if (dataLength > 0) {
             this.V6ErrorData = new byte[dataLength];
             data.get(this.V6ErrorData);
-        }   
+        }
     }
-    
+
     /**
      * @return the V6VendorId
      */
     public int getVendorId() {
         return V6VendorId;
     }
-    
+
     /**
      * @return the V6VendorErrorType
      */
     public short getVendorErrorType() {
         return V6VendorErrorType;
     }
-    
+
     /**
      * @return the VendorErrorType
      */
     public short getVendorErrorCode() {
         return V6VendorErrorCode;
     }
-    
+
     /**
      * @return the Error Bytes
      */
     public byte[] getError() {
         return V6ErrorData;
     }
-    
+
     @Override
     public int hashCode() {
         final int prime = 31;
index 53f4e1d5ad0e73f61219483fc16344d34ed0ca95..f7edd30b01cd3424cda925cf29b05ff747020096 100644 (file)
@@ -13,7 +13,6 @@ import java.nio.ByteBuffer;
 import java.util.LinkedList;
 import java.util.List;
 
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
 import org.openflow.protocol.OFPacketOut;
 import org.openflow.protocol.OFPort;
 import org.openflow.protocol.OFVendor;
@@ -24,7 +23,7 @@ import org.slf4j.LoggerFactory;
 /**
  * This class is used to create IPv6 Vendor Extension messages. Specfically, It
  * defines the methods used in creation of Vendor specific IPv6 Flow Mod message.
- * 
+ *
  *
  */
 public class V6FlowMod extends OFVendor implements Cloneable {
@@ -49,7 +48,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
     private static int IPV6_EXT_MIN_HDR_LEN = 36;
 
     /**
-     * Constructor for the V6FlowMod class. Initializes OFVendor (parent class) 
+     * Constructor for the V6FlowMod class. Initializes OFVendor (parent class)
      * fields by calling the parent class' constructor.
      */
     public V6FlowMod() {
@@ -58,7 +57,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
 
     /**
      * This method sets the match fields of V6FlowMod object
-     * @param match            V6Match object for this V6FlowMod message
+     * @param match     V6Match object for this V6FlowMod message
      */
     public void setMatch(V6Match match) {
         this.match = match;
@@ -66,7 +65,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
 
     /**
      * Sets the list of actions V6FlowMod message
-     * @param actions  a list of ordered OFAction objects
+     * @param actions   a list of ordered OFAction objects
      */
     public void setActions(List<OFAction> actions) {
         this.actions = actions;
@@ -74,7 +73,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
 
     /**
      * Sets the priority field of V6FlowMod message
-     * @param priority         Priority of the message
+     * @param priority  Priority of the message
      */
     public void setPriority(short priority) {
         this.priority = priority;
@@ -82,7 +81,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
 
     /**
      * Sets the cookie field of V6FlowMod message
-     * @param cookie   Cookie of the message
+     * @param cookie    Cookie of the message
      */
     public void setCookie(long cookie) {
         this.cookie = cookie;
@@ -90,7 +89,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
 
     /**
      * Sets the command field of V6FlowMod message
-     * @param command  Command type of the message (ADD or DELETE)
+     * @param command   Command type of the message (ADD or DELETE)
      */
     public V6FlowMod setCommand(short command) {
         this.command = command;
@@ -99,7 +98,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
 
     /**
      * Sets the outPort field of V6FlowMod message
-     * @param outPort  outPort of the message
+     * @param outPort   outPort of the message
      */
     public V6FlowMod setOutPort(OFPort port) {
         this.outPort = port.getValue();
@@ -108,7 +107,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
 
     /**
      * Sets the idle_timeout of V6FlowMod message
-     * @param idleTimeout      idle timeout for this message
+     * @param idleTimeout   idle timeout for this message
      */
     public void setIdleTimeout(short idleTimeout) {
         this.idleTimeout = idleTimeout;
@@ -116,7 +115,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
 
     /**
      * Sets the hardTimeout field of V6FlowMod message
-     * @param hardTimeout      hard timeout of the message
+     * @param hardTimeout       hard timeout of the message
      */
     public void setHardTimeout(short hardTimeout) {
         this.hardTimeout = hardTimeout;
@@ -124,21 +123,21 @@ public class V6FlowMod extends OFVendor implements Cloneable {
 
     /**
      * Returns the Flow Mod message subtype for V6FlowMod message
-     * @return                 message subtype
+     * @return          message subtype
      */
     private int getIPv6ExtensionFlowModAddSubType() {
         return IPV6EXT_ADD_FLOW_MSG_TYPE;
     }
-    
+
     /**
      * Returns the minimum header size for V6Flow Message type
-     * @return         minimum header size
+     * @return      minimum header size
      */
 
     public int getV6FlowModMinHdrSize() {
         return IPV6_EXT_MIN_HDR_LEN;
     }
-    
+
     /**
      * Sets the Vendor type in OFVendor message
      */
@@ -146,7 +145,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
     public void setVendor() {
         super.setVendor(V6StatsRequest.NICIRA_VENDOR_ID);
     }
-    
+
     /**
      * Get flags
      * @return
@@ -162,12 +161,12 @@ public class V6FlowMod extends OFVendor implements Cloneable {
     public void setFlags(short flags) {
         this.flags = flags;
     }
-    
+
     /**
      * This method forms the Vendor extension IPv6 Flow Mod message.It uses the
-     * fields in V6FlowMod class, and writes the data according to vendor 
+     * fields in V6FlowMod class, and writes the data according to vendor
      * extension format. The fields include flow properties (cookie, timeout,
-     * priority, etc), flow match, and action list. It also takes care of 
+     * priority, etc), flow match, and action list. It also takes care of
      * required padding.
      */
 
@@ -209,7 +208,7 @@ public class V6FlowMod extends OFVendor implements Cloneable {
 
     /**
      * Forms the clone of V6FlowMod Object. If Object is returned
-     * successfully, then returns the cloned object. Throws an 
+     * successfully, then returns the cloned object. Throws an
      * exception if cloning is not supported.
      */
     @Override
@@ -229,12 +228,15 @@ public class V6FlowMod extends OFVendor implements Cloneable {
         }
     }
 
-    /**
-     * Prints the contents of V6FlowMod in a string format.
-     */
     @Override
     public String toString() {
-        return "V6FlowMod[" + ReflectionToStringBuilder.toString(this) + "]";
+        return "V6FlowMod [match=" + match + ", cookie=" + cookie
+                + ", command=" + command + ", idleTimeout=" + idleTimeout
+                + ", hardTimeout=" + hardTimeout + ", priority=" + priority
+                + ", bufferId=" + bufferId + ", outPort=" + outPort
+                + ", flags=" + flags + ", actions=" + actions + ", match_len="
+                + match_len + ", actions_len=" + actions_len + ", pad_size="
+                + pad_size + "]";
     }
 
 }
index 2da6b9b00891008850075e31920d02c01888ad16..f31e079bc7705e64bb7c5aa80bc8afdf9d53256f 100644 (file)
@@ -9,32 +9,30 @@
 
 package org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension;
 
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
-import org.openflow.protocol.OFMatch;
-import org.openflow.util.U16;
-import org.openflow.util.U8;
-
 import java.net.Inet6Address;
-import org.opendaylight.controller.sal.utils.HexEncode;
-
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.nio.ByteBuffer;
+import java.util.Arrays;
 
+import org.opendaylight.controller.sal.utils.HexEncode;
+import org.openflow.protocol.OFMatch;
+import org.openflow.util.U16;
+import org.openflow.util.U8;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
  * This Class forms the vendor specific IPv6 Flow Match messages as well as
  * processes the vendor specific IPv6 Stats Reply message.
- * 
- * For message creation, it parses the user entered IPv6 match fields, creates 
- * a sub-message for each field which are later used to form the complete 
- * message.  
- * 
+ *
+ * For message creation, it parses the user entered IPv6 match fields, creates
+ * a sub-message for each field which are later used to form the complete
+ * message.
+ *
  * For message processing, it parses the incoming message and reads each field
  * of the message and stores in appropriate field of V6Match object.
- *  
+ *
  *
  */
 public class V6Match extends OFMatch implements Cloneable {
@@ -472,7 +470,7 @@ public class V6Match extends OFMatch implements Cloneable {
 
     /**
      * Sets this (V6Match) object's member variables based on a comma-separated key=value pair similar to OFMatch's fromString.
-     * 
+     *
      * @param match a key=value comma separated string.
      */
     @Override
@@ -1013,7 +1011,31 @@ public class V6Match extends OFMatch implements Cloneable {
 
     @Override
     public String toString() {
-        return "V6Match[" + ReflectionToStringBuilder.toString(this) + "]";
+        return "V6Match [nwSrc=" + nwSrc + ", nwDst=" + nwDst
+                + ", inputPortMask=" + inputPortMask + ", dataLayerSourceMask="
+                + HexEncode.bytesToHexStringFormat(dataLayerSourceMask)
+                + ", dataLayerDestinationMask="
+                + HexEncode.bytesToHexStringFormat(dataLayerDestinationMask)
+                + ", dataLayerVirtualLanMask=" + dataLayerVirtualLanMask
+                + ", dataLayerVirtualLanPriorityCodePointMask="
+                + dataLayerVirtualLanPriorityCodePointMask
+                + ", dataLayerTypeMask=" + dataLayerTypeMask
+                + ", networkTypeOfServiceMask=" + networkTypeOfServiceMask
+                + ", networkProtocolMask=" + networkProtocolMask
+                + ", networkSourceMask=" + networkSourceMask
+                + ", networkDestinationMask=" + networkDestinationMask
+                + ", transportSourceMask=" + transportSourceMask
+                + ", transportDestinationMask=" + transportDestinationMask
+                + ", srcIPv6SubnetMaskbits=" + srcIPv6SubnetMaskbits
+                + ", dstIPv6SubnetMaskbits=" + dstIPv6SubnetMaskbits
+                + ", inputPortState=" + inputPortState + ", dlSourceState="
+                + dlSourceState + ", dlDestState=" + dlDestState
+                + ", dlVlanState=" + dlVlanState + ", ethTypeState="
+                + ethTypeState + ", nwTosState=" + nwTosState
+                + ", nwProtoState=" + nwProtoState + ", nwSrcState="
+                + nwSrcState + ", nwDstState=" + nwDstState + ", tpSrcState="
+                + tpSrcState + ", tpDstState=" + tpDstState + ", match_len="
+                + match_len + ", pad_size=" + pad_size + "]";
     }
 
     /**
index 6893fa78e279979bb3149038a3f87b3bc4234a49..bd3c2a2c04e95fb01ce31c1d595ba02069b8a04a 100644 (file)
@@ -19,9 +19,9 @@ import org.openflow.util.U16;
 /**
  * This Class processes the OpenFlow Vendor Extension Reply message of a Stats
  * Request. It parses the reply message and initializes fields of  V6StatsReply
- * object. Multiple instances of this class objects are created and used by 
+ * object. Multiple instances of this class objects are created and used by
  * OpenDaylight's Troubleshooting Application.
- * 
+ *
  */
 
 public class V6StatsReply extends OFVendorStatistics {
index 593b464d3c68cec4f3a753657c3085a9081b94bf..1644b1147b1f008b396c089191c83a40ec2324a2 100644 (file)
@@ -11,14 +11,13 @@ package org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6e
 
 import java.nio.ByteBuffer;
 
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
 import org.openflow.protocol.statistics.OFVendorStatistics;
 
 
 /**
- * This Class creates the OpenFlow Vendor Extension IPv6 Flow Stats Request 
+ * This Class creates the OpenFlow Vendor Extension IPv6 Flow Stats Request
  * messages and also reads the Reply of a stats request message.
- * 
+ *
  */
 
 public class V6StatsRequest extends OFVendorStatistics {
@@ -150,7 +149,8 @@ public class V6StatsRequest extends OFVendorStatistics {
 
     @Override
     public String toString() {
-        return "V6StatsRequest[" + ReflectionToStringBuilder.toString(this)
+        return "V6StatsRequest [msgsubtype=" + msgsubtype + ", outPort="
+                + outPort + ", match_len=" + match_len + ", tableId=" + tableId
                 + "]";
     }
 
index faefe4c629012771c238218dc3ec55c299bd668e..750c39503cd4b3aabfd1a3e9608debeae22d3005 100644 (file)
@@ -39,7 +39,7 @@
               org.opendaylight.controller.protocol_plugins.stub.internal
             </Export-Package>
             <Bundle-Activator>
-              org.opendaylight.controller.protocol_plugins.stub.internal.Activator 
+              org.opendaylight.controller.protocol_plugins.stub.internal.Activator
             </Bundle-Activator>
           </instructions>
           <manifestLocation>${project.basedir}/META-INF</manifestLocation>
@@ -60,4 +60,4 @@
       <scope>test</scope>
     </dependency>
   </dependencies>
-</project>
\ No newline at end of file
+</project>
index 8e4c985c06b76ea6055717ae7a5d46370335673e..614e70b1b859b0e23c7500549f776dd961558d53 100644 (file)
@@ -28,8 +28,8 @@ import org.slf4j.LoggerFactory;
 
 /**
  * stub protocol plugin Activator
- * 
- * 
+ *
+ *
  */
 public class Activator extends ComponentActivatorAbstractBase {
     protected static final Logger logger = LoggerFactory
@@ -38,7 +38,7 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function called when the activator starts just after some initializations
      * are done by the ComponentActivatorAbstractBase.
-     * 
+     *
      */
     public void init() {
         Node.NodeIDType.registerIDType("STUB", Integer.class);
@@ -48,7 +48,7 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function called when the activator stops just before the cleanup done by
      * ComponentActivatorAbstractBase
-     * 
+     *
      */
     public void destroy() {
         Node.NodeIDType.unRegisterIDType("STUB");
@@ -58,8 +58,8 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function that is used to communicate to dependency manager the list of
      * known implementations for services inside a container
-     * 
-     * 
+     *
+     *
      * @return An array containing all the CLASS objects that will be
      *         instantiated in order to get an fully working implementation
      *         Object
@@ -72,7 +72,7 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function that is called when configuration of the dependencies is
      * required.
-     * 
+     *
      * @param c
      *            dependency manager Component object, used for configuring the
      *            dependencies exported and imported
@@ -103,12 +103,12 @@ public class Activator extends ComponentActivatorAbstractBase {
             c.setInterface(IPluginInInventoryService.class.getName(), props);
         }
     }
-    
+
     public Object[] getGlobalImplementations() {
         Object[] res = { FlowProgrammerService.class, StubNodeFactory.class, StubNodeConnectorFactory.class };
         return res;
     }
-    
+
     public void configureGlobalInstance(Component c, Object imp){
         if (imp.equals(FlowProgrammerService.class)) {
             // export the service to be used by SAL
@@ -136,6 +136,6 @@ public class Activator extends ComponentActivatorAbstractBase {
             props.put("protocolName", "STUB");
             c.setInterface(INodeConnectorFactory.class.getName(), props);
         }
-        
+
     }
 }
index 834b3faceb2a95a3458bee693dc27069d24c9f88..305829705a88b32983c3eb7954a74eb3ca07e109 100644 (file)
@@ -29,7 +29,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
     }
@@ -37,7 +37,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
     /**
      * Function called by dependency manager after "init ()" is called and after
      * the services provided by the class are registered in the service registry
-     * 
+     *
      */
     void start() {
     }
@@ -46,15 +46,15 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
      * Function called by the dependency manager before the services exported by
      * the component are unregistered, this will be followed by a "destroy ()"
      * calls
-     * 
+     *
      */
     void stop() {
     }
-    
-    
+
+
     /**
      * Synchronously add a flow to the network node
-     * 
+     *
      * @param node
      * @param flow
      */
@@ -64,7 +64,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
 
     /**
      * Synchronously modify existing flow on the switch
-     * 
+     *
      * @param node
      * @param flow
      */
@@ -73,7 +73,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
     }
     /**
      * Synchronously remove the flow from the network node
-     * 
+     *
      * @param node
      * @param flow
      */
@@ -83,7 +83,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
 
     /**
      * Asynchronously add a flow to the network node
-     * 
+     *
      * @param node
      * @param flow
      * @param rid
@@ -94,7 +94,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
 
     /**
      * Asynchronously modify existing flow on the switch
-     * 
+     *
      * @param node
      * @param flow
      * @param rid
@@ -105,7 +105,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
 
     /**
      * Asynchronously remove the flow from the network node
-     * 
+     *
      * @param node
      * @param flow
      * @param rid
@@ -116,7 +116,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
 
     /**
      * Remove all flows present on the network node
-     * 
+     *
      * @param node
      */
     public Status removeAllFlows(Node node){
@@ -126,7 +126,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
     /**
      * Send Barrier message synchronously. The caller will be blocked until the
      * Barrier reply arrives.
-     * 
+     *
      * @param node
      */
     public Status syncSendBarrierMessage(Node node){
@@ -135,7 +135,7 @@ public class FlowProgrammerService implements IPluginInFlowProgrammerService
 
     /**
      * Send Barrier message asynchronously. The caller is not blocked.
-     * 
+     *
      * @param node
      */
     public Status asyncSendBarrierMessage(Node node){
index b4d6166d3636efa901aa490a8dd0d23dad0bbe4c..22a4343f332ed2e79e7f7ecc979d8535acc4ea26 100644 (file)
@@ -42,9 +42,19 @@ public class InventoryService implements IPluginInInventoryService {
     private static final Logger logger = LoggerFactory
             .getLogger(InventoryService.class);
 
-    private ConcurrentMap<Node, Map<String, Property>> nodeProps; // properties are maintained in global container only
-    private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps; // properties are maintained in global container only
-
+    private ConcurrentMap<Node, Map<String, Property>> nodeProps; // properties
+                                                                  // are
+                                                                  // maintained
+                                                                  // in global
+                                                                  // container
+                                                                  // only
+    private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps; // properties
+                                                                                    // are
+                                                                                    // maintained
+                                                                                    // in
+                                                                                    // global
+                                                                                    // container
+                                                                                    // only
 
     /**
      * Function called by the dependency manager when all the required
@@ -55,7 +65,95 @@ public class InventoryService implements IPluginInInventoryService {
         nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>();
         nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>();
         Node.NodeIDType.registerIDType("STUB", Integer.class);
-        NodeConnector.NodeConnectorIDType.registerIDType("STUB", Integer.class, "STUB");
+        NodeConnector.NodeConnectorIDType.registerIDType("STUB", Integer.class,
+                "STUB");
+
+        setupNodeProps();
+        setupNodeConnectorProps();
+    }
+
+    private void setupNodeConnectorProps() {
+        Map<String, Property> ncPropMap = new HashMap<String, Property>();
+        Capabilities cap = new Capabilities(
+                CapabilitiesType.FLOW_STATS_CAPABILITY.getValue());
+        ncPropMap.put(Capabilities.CapabilitiesPropName, cap);
+        Bandwidth bw = new Bandwidth(Bandwidth.BW1Gbps);
+        ncPropMap.put(Bandwidth.BandwidthPropName, bw);
+        State st = new State(State.EDGE_UP);
+        ncPropMap.put(State.StatePropName, st);
+
+        // setup property map for all node connectors
+        NodeConnector nc;
+        Node node;
+        try {
+            node = new Node("STUB", new Integer(0xCAFE));
+            nc = new NodeConnector("STUB", 0xCAFE, node);
+        } catch (ConstructionException e) {
+            nc = null;
+            node = null;
+        }
+        nodeConnectorProps.put(nc, ncPropMap);
+
+        try {
+            node = new Node("STUB", 3366);
+            nc = new NodeConnector("STUB", 12, node);
+        } catch (ConstructionException e) {
+            nc = null;
+            node = null;
+        }
+        nodeConnectorProps.put(nc, ncPropMap);
+
+        try {
+            node = new Node("STUB", 4477);
+            nc = new NodeConnector("STUB", 34, node);
+        } catch (ConstructionException e) {
+            nc = null;
+            node = null;
+        }
+        nodeConnectorProps.put(nc, ncPropMap);
+
+    }
+
+    private void setupNodeProps() {
+        Map<String, Property> propMap = new HashMap<String, Property>();
+
+        Tables t = new Tables((byte) 1);
+        propMap.put(Tables.TablesPropName, t);
+        Capabilities c = new Capabilities((int) 3);
+        propMap.put(Capabilities.CapabilitiesPropName, c);
+        Actions a = new Actions((int) 2);
+        propMap.put(Actions.ActionsPropName, a);
+        Buffers b = new Buffers((int) 1);
+        propMap.put(Buffers.BuffersPropName, b);
+        Long connectedSinceTime = 100000L;
+        TimeStamp timeStamp = new TimeStamp(connectedSinceTime,
+                "connectedSince");
+        propMap.put(TimeStamp.TimeStampPropName, timeStamp);
+
+        // setup property map for all nodes
+        Node node;
+        try {
+            node = new Node("STUB", new Integer(0xCAFE));
+        } catch (ConstructionException e) {
+            node = null;
+        }
+
+        nodeProps.put(node, propMap);
+
+        try {
+            node = new Node("STUB", 3366);
+        } catch (ConstructionException e) {
+            node = null;
+        }
+        nodeProps.put(node, propMap);
+
+        try {
+            node = new Node("STUB", 4477);
+        } catch (ConstructionException e) {
+            node = null;
+        }
+        nodeProps.put(node, propMap);
+
     }
 
     /**
@@ -89,47 +187,6 @@ public class InventoryService implements IPluginInInventoryService {
      */
     @Override
     public ConcurrentMap<Node, Map<String, Property>> getNodeProps() {
-
-        //  setup nodeProps
-        Map<String, Property> propMap = new HashMap<String, Property>();
-
-        Tables t = new Tables((byte)1);
-        propMap.put(Tables.TablesPropName, t);
-        Capabilities c = new Capabilities((int)3);
-        propMap.put(Capabilities.CapabilitiesPropName, c);
-        Actions a = new Actions((int)2);
-        propMap.put(Actions.ActionsPropName, a);
-        Buffers b = new Buffers((int)1);
-        propMap.put(Buffers.BuffersPropName, b);
-        Long connectedSinceTime = 100000L;
-        TimeStamp timeStamp = new TimeStamp(connectedSinceTime,
-                "connectedSince");
-        propMap.put(TimeStamp.TimeStampPropName, timeStamp);
-
-        // setup property map for all nodes
-        Node node;
-        try{
-            node = new Node("STUB", new Integer(0xCAFE));
-        }catch(ConstructionException e){
-            node = null;
-        }       
-     
-        nodeProps.put(node, propMap);
-        
-        try{
-            node = new Node("STUB", 3366);
-        }catch(ConstructionException e){
-            node = null;
-        }       
-        nodeProps.put(node, propMap);
-        
-        try{
-            node = new Node("STUB", 4477);
-        }catch(ConstructionException e){
-            node = null;
-        }       
-        nodeProps.put(node, propMap);
-        
         return nodeProps;
     }
 
@@ -139,49 +196,7 @@ public class InventoryService implements IPluginInInventoryService {
     @Override
     public ConcurrentMap<NodeConnector, Map<String, Property>> getNodeConnectorProps(
             Boolean refresh) {
-
-        //  setup nodeConnectorProps
-        Map<String, Property> ncPropMap = new HashMap<String, Property>();
-        Capabilities cap = new Capabilities
-                (CapabilitiesType.FLOW_STATS_CAPABILITY.getValue());
-        ncPropMap.put(Capabilities.CapabilitiesPropName, cap);
-        Bandwidth bw = new Bandwidth (Bandwidth.BW1Gbps);
-        ncPropMap.put(Bandwidth.BandwidthPropName, bw);
-        State st = new State (State.EDGE_UP);
-        ncPropMap.put(State.StatePropName, st);
-
-        // setup property map for all node connectors
-        NodeConnector nc;
-        Node node;
-        try{
-            node = new Node("STUB", new Integer(0xCAFE));
-            nc = new NodeConnector("STUB", 0xCAFE, node);
-        }catch(ConstructionException e){
-            nc = null;
-            node = null;
-        }
-        nodeConnectorProps.put(nc, ncPropMap);
-
-        try{
-            node = new Node("STUB", 3366);
-            nc = new NodeConnector("STUB", 12, node);
-         } catch(ConstructionException e){
-            nc = null;
-            node = null;
-         }
-         nodeConnectorProps.put(nc, ncPropMap);
-
-         try{
-            node = new Node("STUB", 4477);
-            nc = new NodeConnector("STUB", 34, node);
-         }catch(ConstructionException e){
-            nc = null;
-            node = null;
-         }
-         nodeConnectorProps.put(nc, ncPropMap);
-
-         return nodeConnectorProps;
+        return nodeConnectorProps;
     }
 
-
 }
index 27ba897fdfc57b44e0d2d4c2ae391ffeae9364c3..b580021b690f996a35b396423bc337aed8752752 100644 (file)
@@ -47,8 +47,8 @@ import org.opendaylight.controller.sal.reader.NodeDescription;
 import org.opendaylight.controller.sal.reader.NodeTableStatistics;
 /**
  * Stub Implementation for IPluginInReadService used by SAL
- * 
- * 
+ *
+ *
  */
 public class ReadService implements IPluginInReadService {
     private static final Logger logger = LoggerFactory
@@ -57,7 +57,7 @@ public class ReadService implements IPluginInReadService {
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
-     * 
+     *
      */
     void init() {
     }
@@ -66,7 +66,7 @@ public class ReadService implements IPluginInReadService {
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
     }
@@ -74,7 +74,7 @@ public class ReadService implements IPluginInReadService {
     /**
      * Function called by dependency manager after "init ()" is called and after
      * the services provided by the class are registered in the service registry
-     * 
+     *
      */
     void start() {
     }
@@ -83,7 +83,7 @@ public class ReadService implements IPluginInReadService {
      * Function called by the dependency manager before the services exported by
      * the component are unregistered, this will be followed by a "destroy ()"
      * calls
-     * 
+     *
      */
     void stop() {
     }
index 0c1963d93396aa9be2bea92600e55f58fde2ed6d..53adef24276ee017d0be495213cdc63cad542756 100644 (file)
@@ -13,7 +13,7 @@ public class StubNodeConnectorFactory implements INodeConnectorFactory
        * Function called by the dependency manager when at least one dependency
        * become unsatisfied or when the component is shutting down because for
        * example bundle is being stopped.
-       * 
+       *
        */
       void destroy() {
       }
@@ -21,7 +21,7 @@ public class StubNodeConnectorFactory implements INodeConnectorFactory
       /**
        * Function called by dependency manager after "init ()" is called and after
        * the services provided by the class are registered in the service registry
-       * 
+       *
        */
       void start() {
       }
@@ -30,11 +30,11 @@ public class StubNodeConnectorFactory implements INodeConnectorFactory
        * Function called by the dependency manager before the services exported by
        * the component are unregistered, this will be followed by a "destroy ()"
        * calls
-       * 
+       *
        */
       void stop() {
       }
-      
+
       public NodeConnector fromStringNoNode(String typeStr, String IDStr,
               Node n){
           if(typeStr.equals("STUB")){
index 5b8ee12e567791f963caee163415f1db41616edf..25382429fd7126c595d76a2702250be76a96e036 100644 (file)
@@ -13,7 +13,7 @@ public class StubNodeFactory implements INodeFactory
        * Function called by the dependency manager when at least one dependency
        * become unsatisfied or when the component is shutting down because for
        * example bundle is being stopped.
-       * 
+       *
        */
       void destroy() {
       }
@@ -21,7 +21,7 @@ public class StubNodeFactory implements INodeFactory
       /**
        * Function called by dependency manager after "init ()" is called and after
        * the services provided by the class are registered in the service registry
-       * 
+       *
        */
       void start() {
       }
@@ -30,11 +30,11 @@ public class StubNodeFactory implements INodeFactory
        * Function called by the dependency manager before the services exported by
        * the component are unregistered, this will be followed by a "destroy ()"
        * calls
-       * 
+       *
        */
       void stop() {
       }
-      
+
       public Node fromString(String nodeType, String nodeId){
           if(nodeType.equals("STUB"))
               try{
index 26ae86243b7b83279443b2a2a2b477aa85a4e179..3a0faa91d4bbca4018d18022ac2418b2e8fa8804 100644 (file)
@@ -381,7 +381,7 @@ public class DijkstraImplementation implements IRouting, ITopologyManagerAware {
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
-     * 
+     *
      */
     @SuppressWarnings({ "unchecked", "rawtypes" })
     public void init() {
@@ -401,7 +401,7 @@ public class DijkstraImplementation implements IRouting, ITopologyManagerAware {
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
         log.debug("Routing destroy() is called");
@@ -410,7 +410,7 @@ public class DijkstraImplementation implements IRouting, ITopologyManagerAware {
     /**
      * Function called by dependency manager after "init ()" is called and after
      * the services provided by the class are registered in the service registry
-     * 
+     *
      */
     void start() {
         log.debug("Routing start() is called");
@@ -437,7 +437,7 @@ public class DijkstraImplementation implements IRouting, ITopologyManagerAware {
      * Function called by the dependency manager before the services exported by
      * the component are unregistered, this will be followed by a "destroy ()"
      * calls
-     * 
+     *
      */
     public void stop() {
         log.debug("Routing stop() is called");
index d8144d7bb74eaaf7a043ce3cba623b58b53c041b..332e31f6bf5337e93f0516eafe03166680450e88 100644 (file)
@@ -24,8 +24,8 @@ import org.slf4j.LoggerFactory;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 @XmlSeeAlso({Controller.class, Drop.class, Flood.class, FloodAll.class, HwPath.class, Loopback.class, Output.class,
-                        PopVlan.class, PushVlan.class, SetDlDst.class, SetDlSrc.class, SetDlType.class, SetNwDst.class, SetNwSrc.class,
-                        SetNwTos.class, SetTpDst.class, SetTpSrc.class, SetVlanCfi.class, SetVlanId.class, SetVlanPcp.class, SwPath.class})
+                         PopVlan.class, PushVlan.class, SetDlDst.class, SetDlSrc.class, SetDlType.class, SetNwDst.class, SetNwSrc.class,
+                         SetNwTos.class, SetTpDst.class, SetTpSrc.class, SetVlanCfi.class, SetVlanId.class, SetVlanPcp.class, SwPath.class})
 public abstract class Action {
     private static final Logger logger = LoggerFactory.getLogger(Action.class);
     private static boolean debug = false; // Enable to find where in the code an invalid assignment is made
@@ -39,9 +39,9 @@ public abstract class Action {
 
     /*
     public Action (ActionType type, Object value) {
-       this.type = type;
-       this.value = value;
-       this.isValid = true;
+        this.type = type;
+        this.value = value;
+        this.isValid = true;
     } */
 
     /**
@@ -112,7 +112,7 @@ public abstract class Action {
     /**
      * Returns whether the Action is valid or not
      *
-     * @return boolean
+     * @return  boolean
      */
     public boolean isValid() {
         return isValid;
index e09968836ff1877cfb195974808aaceda1ef4680..774c79a543feacae6b59e052c04326311f31cd0c 100644 (file)
@@ -26,7 +26,7 @@ import org.opendaylight.controller.sal.core.NodeConnector;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class Output extends Action {
-       @XmlElement
+        @XmlElement
     private NodeConnector port;
 
     /* Dummy constructor for JAXB */
index f3b862fe7e2d2e16e5a5e07da4afa992d0478a6a..b5783d487a1c236948cbdc976e34e2334a51b37b 100644 (file)
@@ -21,7 +21,7 @@ import org.opendaylight.controller.sal.utils.EtherTypes;
  * Execute it multiple times to achieve QinQ
  *
  * 802.1q = [TPID(16) + TCI(16)]
- *                     TCI = [PCP(3) + CFI(1) + VID(12)]
+ *                      TCI = [PCP(3) + CFI(1) + VID(12)]
  *
  *
  *
index 2413c23314b5732c3e5d17cbbb44058835cb3d2d..c2c40bfcc8df8b70e9d007e992f16a463b95186e 100644 (file)
@@ -45,12 +45,12 @@ public class SetDlDst extends Action {
     public byte[] getDlAddress() {
         return address.clone();
     }
-    
+
     @XmlElement(name = "address")
     public String getDlAddressString() {
         return HexEncode.bytesToHexString(address);
     }
-    
+
     @Override
     public boolean equals(Object obj) {
         if (this == obj)
index 3cdd5b617038c9aadf5aad41115edfebc26ef768..91909993f3422d012003ff4e26c267033f463e49 100644 (file)
@@ -54,7 +54,7 @@ public class SetDlSrc extends Action {
     public String getDlAddressString() {
         return HexEncode.bytesToHexString(address);
     }
-    
+
     @Override
     public boolean equals(Object obj) {
         if (this == obj)
index f76000c64948d42849fd4e5c1cde568e373dcf4b..d15424ee15b9aabf9e0a493ce4a396a53c12fef1 100644 (file)
@@ -24,7 +24,7 @@ import org.opendaylight.controller.sal.utils.EtherTypes;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class SetDlType extends Action {
-       @XmlElement
+        @XmlElement
     private int dlType;
 
     /* Dummy constructor for JAXB */
index bccca3f1f236b99aafee3a77d8803aad9111a284..2fa71f5d7b86195d8ae1671e43f69acf8260ed7b 100644 (file)
@@ -38,15 +38,15 @@ public class SetNwDst extends Action {
     /**
      * Returns the network address this action will set
      *
-     * @return InetAddress
+     * @return  InetAddress
      */
     public InetAddress getAddress() {
         return address;
     }
-    
+
     @XmlElement (name="address")
     public String getAddressAsString() {
-       return address.getHostAddress();
+        return address.getHostAddress();
     }
 
     @Override
index 5595b610de6f153cd3fbea6b8e46039ceadfaaea..c57f1a53a96b4dde4ffcb9c638fb202fc20d3367 100644 (file)
@@ -38,7 +38,7 @@ public class SetNwSrc extends Action {
     /**
      * Returns the network address this action will set
      *
-     * @return InetAddress
+     * @return  InetAddress
      */
     public InetAddress getAddress() {
         return address;
@@ -46,7 +46,7 @@ public class SetNwSrc extends Action {
 
     @XmlElement (name="address")
     public String getAddressAsString() {
-       return address.getHostAddress();
+        return address.getHostAddress();
     }
 
     @Override
index 69fdd89ffb4cfb10f12ae899498c007454511edf..62dec0cd58198dfcbfa0b77e89a28ab9b97e1d88 100644 (file)
@@ -21,7 +21,7 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class SetNwTos extends Action {
-       @XmlElement
+        @XmlElement
     private int tos;
 
     /* Dummy constructor for JAXB */
index 825092c54fe355b520d0098771142b662c265930..c32c346307a8fb3d0ebb8aca9c9387ac24eac096 100644 (file)
@@ -21,7 +21,7 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class SetTpDst extends Action {
-       @XmlElement
+        @XmlElement
     private int port;
 
     /* Dummy constructor for JAXB */
index cdae5aad2ac7385c300f9c0f1f43f6456fd73f7d..d56f33d51ef0f9a55b0995de325e3caab3b1f5ed 100644 (file)
@@ -22,7 +22,7 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class SetTpSrc extends Action {
-       @XmlElement
+        @XmlElement
     private int port;
 
     /* Dummy constructor for JAXB */
index fc3d0a60ef2a742a3929f8d6f09490db2f3511ab..0385f63d561f43b21064036c920ff2734ebb8d71 100644 (file)
@@ -22,7 +22,7 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class SetVlanCfi extends Action {
-       @XmlElement
+        @XmlElement
     private int cfi;
 
     /* Dummy constructor for JAXB */
index b1e4748bc3b4f9dd1426cd4958af319eabda5e23..5370648227eb379c746f578e9d6476f4ef45b188 100644 (file)
@@ -22,13 +22,13 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class SetVlanId extends Action {
-       @XmlElement
+        @XmlElement
     private int vlanId;
 
-       private SetVlanId() {
-               
-       }
-       
+        private SetVlanId() {
+
+        }
+
     public SetVlanId(int vlanId) {
         type = ActionType.SET_VLAN_ID;
         this.vlanId = vlanId;
index c47723ebdf61021bde42532dfe45ac4e26584cee..1ee74fdf3f76b2d9d2a4fa5f75958d410653bbb4 100644 (file)
@@ -21,13 +21,13 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class SetVlanPcp extends Action {
-       @XmlElement
+        @XmlElement
     private int pcp;
 
-       private SetVlanPcp() {
-               
-       }
-       
+        private SetVlanPcp() {
+
+        }
+
     public SetVlanPcp(int pcp) {
         type = ActionType.SET_VLAN_PCP;
         this.pcp = pcp;
index f08fc84a2ca8a842c961eb92a99e7bf2e7f73631..7e73dd414f4e18dd927b3085b074bd02af56f762 100644 (file)
@@ -43,13 +43,13 @@ public enum AppRoleLevel implements Serializable {
     public String toStringPretty() {
         return this.prettyLevel;
     }
-    
+
     public static AppRoleLevel fromString(String levelString) {
-       for (AppRoleLevel level : AppRoleLevel.values()) {
-               if (level.toString().equals(levelString)) {
-                       return level;
-               }
-       }
-       return null;                    
+        for (AppRoleLevel level : AppRoleLevel.values()) {
+                if (level.toString().equals(levelString)) {
+                        return level;
+                }
+        }
+        return null;
     }
-} 
+}
index 8f6cfa42512642ba6e1115332c68898bb35ece75..453976bf680d1ee3af50fa7719aececff1cedc74 100644 (file)
@@ -25,20 +25,20 @@ public interface IResourceAuthorization {
     /**
      * Create a Role name for the application
      *
-     * @param role     the role name
-     * @param userLevel        the user level in the application context
-        * @return the status of the request
-        */
+     * @param role  the role name
+     * @param userLevel the user level in the application context
+         * @return the status of the request
+         */
     public Status createRole(String role, AppRoleLevel userLevel);
 
     /**
      * Remove a Role
-     * 
+     *
      * @param role the role name
      * @return the status of the request
      */
     public Status removeRole(String role);
-    
+
     /**
      * Return the list of roles configured for the application
      *
@@ -53,7 +53,7 @@ public interface IResourceAuthorization {
      *
      * @param roleName the role name to query
      * @return the application level of the given role in the application context as specified by {@link AppRoleLevel}
-     *                         if the role is not part of this application's roles, <code>NOUSER<code> is returned
+     *                  if the role is not part of this application's roles, <code>NOUSER<code> is returned
      */
     public AppRoleLevel getApplicationRoleLevel(String roleName);
 
@@ -61,7 +61,7 @@ public interface IResourceAuthorization {
      * Returns whether the specified role is part of this application's roles
      *
      * @param roleName the role name to test
-     * @return true if the role belongs to this application, false otherwise
+     * @return  true if the role belongs to this application, false otherwise
      */
     public boolean isApplicationRole(String roleName);
 
@@ -110,16 +110,16 @@ public interface IResourceAuthorization {
      * @return the status of the request
      */
     public Status assignResourceGroupToRole(String groupName, String role);
-    
+
     /**
      * Unassign the passed resource group from the specified role
-     * 
+     *
      * @param group
      * @param role
      * @return the status of the request
      */
     public Status unassignResourceGroupFromRole(String group, String role);
-    
+
     /**
      * Returns the list of resource groups the given Role is authorized to use
      * The returning object expresses the resource group name and the access
index a2e1d1c56d116672f0e7ea4a0c73ec473b73d677..70b41cdd8aa6b082b28a510d0768ca0fc057bed5 100644 (file)
@@ -15,11 +15,11 @@ import java.io.Serializable;
  * Describes the user role level in the controller space
  */
 public enum UserLevel implements Serializable {
-    SYSTEMADMIN(0, "System-Admin", "System Administrator"),    // can do everything
-    NETWORKADMIN(1, "Network-Admin", "Network Administrator"), // can do everything but setting a system admin user profile
-    NETWORKOPERATOR(2, "Network-Operator", "Network Operator"),        // can only see what is configured anywhere
-    CONTAINERUSER(4, "Container-User", "Container User"),              // container context user
-    APPUSER(5, "App-User", "Application User"),                                // application context user
+    SYSTEMADMIN(0, "System-Admin", "System Administrator"),     // can do everything
+    NETWORKADMIN(1, "Network-Admin", "Network Administrator"),  // can do everything but setting a system admin user profile
+    NETWORKOPERATOR(2, "Network-Operator", "Network Operator"), // can only see what is configured anywhere
+    CONTAINERUSER(4, "Container-User", "Container User"),       // container context user
+    APPUSER(5, "App-User", "Application User"),                                 // application context user
     NOUSER(255, "Not Authorized", "Not Authorized");
 
     private int userLevel;
index 3f81d0c4c5524150bf386158e8d22921f57249f6..135a67dcd1cbfdd83a00f5695ab2d18e4833fc9d 100644 (file)
@@ -22,33 +22,33 @@ import javax.xml.bind.annotation.XmlRootElement;
 
 @XmlRootElement
 public class Actions extends Property {
-       private static final long serialVersionUID = 1L;
+        private static final long serialVersionUID = 1L;
     @XmlElement
     private int actionsValue;
-    
-    public enum ActionType { 
-       OUTPUT_PORT_ACTION(1<<0),
-       VLAN_VID_ACTION(1<<1),
-       VLAN_PCP_ACTION(1<<2),
-       VLAN_STRIP_ACTION(1<<3),
-       DLSRC_ACTION(1<<4),
-       DLDST_ACTION(1<<5),
-       NWSRC_ACTION(1<<6),
-       NWDST_ACTION(1<<7),
-       NWTOS_ACTION(1<<8),
-       TPTSRC_ACTION(1<<9),
-       TPTDST_ACTION(1<<10),
-       ENQUEUE_ACTION(1<<11),
-       VENDOR_ACTION(0xffff);
-       private final int at;
-       ActionType(int val) {
-               this.at = val;
-       }
-       public int getValue() {
-               return at;
-       }
+
+    public enum ActionType {
+        OUTPUT_PORT_ACTION(1<<0),
+        VLAN_VID_ACTION(1<<1),
+        VLAN_PCP_ACTION(1<<2),
+        VLAN_STRIP_ACTION(1<<3),
+        DLSRC_ACTION(1<<4),
+        DLDST_ACTION(1<<5),
+        NWSRC_ACTION(1<<6),
+        NWDST_ACTION(1<<7),
+        NWTOS_ACTION(1<<8),
+        TPTSRC_ACTION(1<<9),
+        TPTDST_ACTION(1<<10),
+        ENQUEUE_ACTION(1<<11),
+        VENDOR_ACTION(0xffff);
+        private final int at;
+        ActionType(int val) {
+                this.at = val;
+        }
+        public int getValue() {
+                return at;
+        }
     }
-    
+
     public static final String ActionsPropName = "actions";
     /**
      * Construct a actions property
@@ -72,12 +72,12 @@ public class Actions extends Property {
     public Actions clone() {
         return new Actions(this.actionsValue);
     }
-    
+
     public int getValue() {
-       return this.actionsValue;
+        return this.actionsValue;
     }
-    
-    
+
+
     @Override
     public int hashCode() {
         final int prime = 31;
index 37aa60deef058e9f08ac3920cab4a3adb86815e0..ab546d73023c6c5fe45a03387969eba0beff58cb 100644 (file)
@@ -23,25 +23,25 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlRootElement
 @SuppressWarnings("serial")
 public class AdvertisedBandwidth extends Bandwidth {
-       public static final String AdvertisedBandwidthPropName = "advertisedBandwidth";
-       
-       public AdvertisedBandwidth(long value) {
-               super(AdvertisedBandwidthPropName);
-               this.bandwidthValue = value;
-       }
-       
-       /*
+        public static final String AdvertisedBandwidthPropName = "advertisedBandwidth";
+
+        public AdvertisedBandwidth(long value) {
+                super(AdvertisedBandwidthPropName);
+                this.bandwidthValue = value;
+        }
+
+        /*
      * Private constructor used for JAXB mapping
      */
     private AdvertisedBandwidth() {
-       super(AdvertisedBandwidthPropName);
-               this.bandwidthValue = 0;
+        super(AdvertisedBandwidthPropName);
+                this.bandwidthValue = 0;
     }
-       
-       public AdvertisedBandwidth clone() {
-               return new AdvertisedBandwidth(this.bandwidthValue);  
+
+        public AdvertisedBandwidth clone() {
+                return new AdvertisedBandwidth(this.bandwidthValue);
     }
-       
+
     @Override
     public String toString() {
         StringBuffer sb = new StringBuffer();
index fa5cc10827d5847140dd21ec72b24138b23b901f..8048cf882c6c9eec22883b9f3c823b23d8c72149 100644 (file)
@@ -66,7 +66,7 @@ public class Bandwidth extends Property {
         super(BandwidthPropName);
         this.bandwidthValue = (long) bandwidth;
     }
-    
+
     public Bandwidth(String name) {
         super(name);
     }
index 991ed688f2eda4d630d63f15b965983ca07acc97..99089d9096c9db1e0c37391e790322b093db5f47 100644 (file)
@@ -21,16 +21,16 @@ import javax.xml.bind.annotation.XmlRootElement;
  */
 @XmlRootElement
 public class Buffers extends Property {
-       private static final long serialVersionUID = 1L;
+        private static final long serialVersionUID = 1L;
     @XmlElement
     private int buffersValue;
-    
+
     public static final String BuffersPropName = "buffers";
-    
+
     /**
      * Construct a Buffers property
      *
-     * @param buffers the Buffers 
+     * @param buffers the Buffers
      * @return Constructed object
      */
     public Buffers(int buffers) {
@@ -53,7 +53,7 @@ public class Buffers extends Property {
     public int getValue() {
         return this.buffersValue;
     }
-    
+
     @Override
     public int hashCode() {
         final int prime = 31;
index a41a0e22904482050bbcfe95c4338c2acb0dc520..fb121d7b9a48aa4c4c21b626de4f6baf5d661444 100644 (file)
@@ -21,28 +21,28 @@ import javax.xml.bind.annotation.XmlRootElement;
  */
 @XmlRootElement
 public class Capabilities extends Property {
-       private static final long serialVersionUID = 1L;
+        private static final long serialVersionUID = 1L;
     @XmlElement
     private int capabilitiesValue;
-    
-    public enum CapabilitiesType { 
-       FLOW_STATS_CAPABILITY(1<<0),
-       TABLE_STATS_CAPABILITY(1<<1),
-       PORT_STATS_CAPABILITY(1<<2),
-       STP_CAPABILITY(1<<3),
-       RSVD_CAPABILITY(1<<4),
-       IP_REASSEM_CAPABILITY(1<<5),
-       QUEUE_STATS_CAPABILITY(1<<6),
-       ARP_MATCH_IP_CAPABILITY(1<<7);
-       private final int ct;
-       CapabilitiesType(int val) {
-               this.ct = val;
-       }
-       public int getValue() {
-               return ct;
-       }
+
+    public enum CapabilitiesType {
+        FLOW_STATS_CAPABILITY(1<<0),
+        TABLE_STATS_CAPABILITY(1<<1),
+        PORT_STATS_CAPABILITY(1<<2),
+        STP_CAPABILITY(1<<3),
+        RSVD_CAPABILITY(1<<4),
+        IP_REASSEM_CAPABILITY(1<<5),
+        QUEUE_STATS_CAPABILITY(1<<6),
+        ARP_MATCH_IP_CAPABILITY(1<<7);
+        private final int ct;
+        CapabilitiesType(int val) {
+                this.ct = val;
+        }
+        public int getValue() {
+                return ct;
+        }
     }
-   
+
     public static final String CapabilitiesPropName = "capabilities";
     /**
      * Construct a Capabilities property
@@ -68,9 +68,9 @@ public class Capabilities extends Property {
     }
 
     public int getValue() {
-       return this.capabilitiesValue;
+        return this.capabilitiesValue;
     }
-    
+
     @Override
     public int hashCode() {
         final int prime = 31;
index 039acf52e698945d6ec9275db7eb87dee1571d46..66882af5d3098d95b97fb7eee530ce57d834974c 100644 (file)
@@ -354,7 +354,7 @@ abstract public class ComponentActivatorAbstractBase implements
                     }
                 }
             }
-            
+
             // Register with OSGi the provider for the service IContainerAware
             context.registerService(
                     IContainerAware.class.getName(), this, null);
index c547c2bb455bd89f9d26b0c1483d9d6b3d8cc8d2..bae984eaec00f4f9524e4e0db719c8e2ec74e4e3 100644 (file)
@@ -13,8 +13,8 @@ import javax.xml.bind.annotation.XmlRootElement;
 
 /**
  * The class represents Admin Config status
- * 
- * 
+ *
+ *
  */
 @XmlRootElement
 @SuppressWarnings("serial")
index 2a80bd608823e2bf0a0ee329379a9578127af000..ebf623b7b00ff8bcf9dd784530b61de735bb0839 100644 (file)
@@ -127,7 +127,7 @@ public class ContainerFlow implements Serializable {
     /**
      * Returns whether the specified match is allowed
      *
-     * @param match    the match to test
+     * @param match the match to test
      * @return true if the match is allowed, false otherwise
      */
     public boolean allowsMatch(Match target) {
index d5fbdbc74371df64bbd204ed7965e156c21512da..edb3537c1273c9f6a02cc956b64e481161914b08 100644 (file)
@@ -15,8 +15,7 @@ import javax.xml.bind.annotation.XmlAccessorType;
 import javax.xml.bind.annotation.XmlElement;
 import javax.xml.bind.annotation.XmlRootElement;
 
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
-
+import org.opendaylight.controller.sal.utils.HexEncode;
 /**
  * The class contains MAC address property.
  */
@@ -92,6 +91,7 @@ public class MacAddress extends Property implements Cloneable {
 
     @Override
     public String toString() {
-        return "MacAddress[" + ReflectionToStringBuilder.toString(this) + "]";
+        return "MacAddress [address=" +
+            HexEncode.bytesToHexStringFormat(address) + "]";
     }
 }
index de2877597ff9171dd794ff62b73f9826c8cf866b..a1b436ef1a24b52b2a6d8f7578c91147ea80875d 100644 (file)
@@ -21,27 +21,27 @@ import javax.xml.bind.annotation.XmlRootElement;
  */
 @XmlRootElement
 public class PeerBandwidth extends Bandwidth {
-       private static final long serialVersionUID = 1L;
-       
-       public static final String PeerBandwidthPropName = "peerBandwidth";
-       
-       public PeerBandwidth(long value) {
-               super(PeerBandwidthPropName);
-               this.bandwidthValue = value;
-       }
-       
-       /*
+        private static final long serialVersionUID = 1L;
+
+        public static final String PeerBandwidthPropName = "peerBandwidth";
+
+        public PeerBandwidth(long value) {
+                super(PeerBandwidthPropName);
+                this.bandwidthValue = value;
+        }
+
+        /*
      * Private constructor used for JAXB mapping
      */
     private PeerBandwidth() {
-       super(PeerBandwidthPropName);
-               this.bandwidthValue = 0;
+        super(PeerBandwidthPropName);
+                this.bandwidthValue = 0;
     }
 
-       public PeerBandwidth clone() {
-               return new PeerBandwidth(this.bandwidthValue);  
+        public PeerBandwidth clone() {
+                return new PeerBandwidth(this.bandwidthValue);
     }
-       
+
 
     @Override
     public String toString() {
index 5cb7b33890b04e6f491a4dc0f1b39f69c77bde2e..cd6589ed6d3da0d492fa1217dff859dc3dd56d89 100644 (file)
@@ -22,24 +22,24 @@ import javax.xml.bind.annotation.XmlRootElement;
  */
 @XmlRootElement
 public class SupportedBandwidth extends Bandwidth {
-       private static final long serialVersionUID = 1L;
-       public static final String SupportedBandwidthPropName = "supportedBandwidth";
-       
-       public SupportedBandwidth(long value) {
-               super(SupportedBandwidthPropName);
-               this.bandwidthValue = value;
-       }
-       
-       /*
+        private static final long serialVersionUID = 1L;
+        public static final String SupportedBandwidthPropName = "supportedBandwidth";
+
+        public SupportedBandwidth(long value) {
+                super(SupportedBandwidthPropName);
+                this.bandwidthValue = value;
+        }
+
+        /*
      * Private constructor used for JAXB mapping
      */
     private SupportedBandwidth() {
-       super(SupportedBandwidthPropName);
-               this.bandwidthValue = 0;
+        super(SupportedBandwidthPropName);
+                this.bandwidthValue = 0;
     }
-       
-       public SupportedBandwidth clone() {
-               return new SupportedBandwidth(this.bandwidthValue);  
+
+        public SupportedBandwidth clone() {
+                return new SupportedBandwidth(this.bandwidthValue);
     }
 
     @Override
index 22cff90bb5dd3a9fc7f3852e7e100ab9b5fb65ff..156a0b8ee0225a3b719b7019976c6bc4556a55ba 100644 (file)
@@ -21,15 +21,15 @@ import javax.xml.bind.annotation.XmlRootElement;
  */
 @XmlRootElement
 public class Tables extends Property {
-       private static final long serialVersionUID = 1L;
+        private static final long serialVersionUID = 1L;
     @XmlElement
     private byte tablesValue;
-    
+
     public static final String TablesPropName = "tables";
     /**
      * Construct a Tables property
      *
-     * @param tables the Tables 
+     * @param tables the Tables
      * @return Constructed object
      */
     public Tables(byte tables) {
@@ -52,7 +52,7 @@ public class Tables extends Property {
     public byte getValue() {
         return this.tablesValue;
     }
-    
+
     @Override
     public int hashCode() {
         final int prime = 31;
index 29094d34f954c606f23a6c87ca35ca65c0d1b088..f640ac2a33f80db4ea24dfbed440c5bb69e7b1ed 100644 (file)
@@ -23,11 +23,11 @@ public interface IDiscoveryService {
     /**
      * The methods is called when an edge is added/deleted/changed
      *
-     * @param edge                     {@link org.opendaylight.controller.sal.core.Edge} being updated
-     * @param type             {@link org.opendaylight.controller.sal.core.UpdateType}
-     * @param props            set of {@link org.opendaylight.controller.sal.core.Property} like
-     *                                                 {@link org.opendaylight.controller.sal.core.Bandwidth} and/or
-     *                                                 {@link org.opendaylight.controller.sal.core.Latency} etc.
+     * @param edge                      {@link org.opendaylight.controller.sal.core.Edge} being updated
+     * @param type              {@link org.opendaylight.controller.sal.core.UpdateType}
+     * @param props             set of {@link org.opendaylight.controller.sal.core.Property} like
+     *                                          {@link org.opendaylight.controller.sal.core.Bandwidth} and/or
+     *                                          {@link org.opendaylight.controller.sal.core.Latency} etc.
      */
     public void notifyEdge(Edge edge, UpdateType type, Set<Property> props);
 }
index f56c13d34524efe0685047c005baeb71ed26130f..f70e254ff548e6b6b7b0e7e8b3ed283e45ea46b0 100644 (file)
@@ -39,8 +39,8 @@ import org.slf4j.LoggerFactory;
 public class Flow implements Cloneable, Serializable {
     protected static final Logger logger = LoggerFactory
     .getLogger(Flow.class);
-       private static final long serialVersionUID = 1L;
-       @XmlElement
+        private static final long serialVersionUID = 1L;
+        @XmlElement
     private Match match;
     @XmlElement
     private List<Action> actions;
index d2af1a8c7c5a4a026d8fd43e9168f8d65e83a81c..0b38dda8cb6c4e8f02ee97494fd8bd201a4efeb4 100644 (file)
@@ -18,7 +18,7 @@ import org.opendaylight.controller.sal.utils.Status;
 public interface IFlowProgrammerService {
     /**
      * Synchronously add a flow to the network node
-     * 
+     *
      * @param node
      *            The target network node
      * @param flow
@@ -29,7 +29,7 @@ public interface IFlowProgrammerService {
 
     /**
      * Synchronously modify existing flow on the switch
-     * 
+     *
      * @param node
      *            The target network node
      * @param oldFlow
@@ -42,7 +42,7 @@ public interface IFlowProgrammerService {
 
     /**
      * Synchronously remove the flow from the network node
-     * 
+     *
      * @param node
      *            The target network node
      * @param flow
@@ -53,7 +53,7 @@ public interface IFlowProgrammerService {
 
     /**
      * Asynchronously add a flow to the network node
-     * 
+     *
      * @param node
      *            The target network node
      * @param flow
@@ -64,7 +64,7 @@ public interface IFlowProgrammerService {
 
     /**
      * Asynchronously modify existing flow on the switch
-     * 
+     *
      * @param node
      *            The target network node
      * @param oldFlow
@@ -77,7 +77,7 @@ public interface IFlowProgrammerService {
 
     /**
      * Asynchronously remove the flow from the network node
-     * 
+     *
      * @param node
      *            The target network node
      * @param flow
@@ -88,7 +88,7 @@ public interface IFlowProgrammerService {
 
     /**
      * Remove all flows present on the network node
-     * 
+     *
      * @param node
      *            The target network node
      * @return The status of this request containing the unique request id
@@ -98,13 +98,13 @@ public interface IFlowProgrammerService {
     /**
      * Send Barrier message synchronously. The caller will be blocked until the
      * solicitation response arrives.
-     * 
+     *
      * Solicit the network node to report whether all the requests sent so far
      * are completed. When this call is done, caller knows that all past flow
      * operations requested to the node in asynchronous fashion were satisfied
      * by the network node and that in case of any failure, a message was sent
      * to the controller.
-     * 
+     *
      * @param node
      *            The network node to solicit
      * @return The status of this request containing the unique request id
@@ -113,13 +113,13 @@ public interface IFlowProgrammerService {
 
     /**
      * Send Barrier message asynchronously. The caller is not blocked.
-     * 
+     *
      * Solicit the network node to report whether all the requests sent so far
      * are completed. When this call is done, caller knows that all past flow
      * operations requested to the node in asynchronous fashion were satisfied
      * by the network node and that in case of any failure, a message was sent
      * to the controller.
-     * 
+     *
      * @param node
      *            The network node to solicit
      * @return The status of this request containing the unique request id
index 3c40b96cc74d240b116e3746a17820119e8b77b0..5157788ce7b58982414fdc91436d8cf24f5eb167 100644 (file)
@@ -13,13 +13,13 @@ import org.opendaylight.controller.sal.utils.Status;
 
 /**
  * @file IPluginOutFlowProgrammer.java
- * 
+ *
  * @brief Flow programmer interface to be implemented by protocol plugins
  */
 public interface IPluginInFlowProgrammerService {
     /**
      * Synchronously add a flow to the network node
-     * 
+     *
      * @param node
      * @param flow
      */
@@ -27,7 +27,7 @@ public interface IPluginInFlowProgrammerService {
 
     /**
      * Synchronously modify existing flow on the switch
-     * 
+     *
      * @param node
      * @param flow
      */
@@ -35,7 +35,7 @@ public interface IPluginInFlowProgrammerService {
 
     /**
      * Synchronously remove the flow from the network node
-     * 
+     *
      * @param node
      * @param flow
      */
@@ -43,7 +43,7 @@ public interface IPluginInFlowProgrammerService {
 
     /**
      * Asynchronously add a flow to the network node
-     * 
+     *
      * @param node
      * @param flow
      * @param rid
@@ -52,7 +52,7 @@ public interface IPluginInFlowProgrammerService {
 
     /**
      * Asynchronously modify existing flow on the switch
-     * 
+     *
      * @param node
      * @param flow
      * @param rid
@@ -61,7 +61,7 @@ public interface IPluginInFlowProgrammerService {
 
     /**
      * Asynchronously remove the flow from the network node
-     * 
+     *
      * @param node
      * @param flow
      * @param rid
@@ -70,7 +70,7 @@ public interface IPluginInFlowProgrammerService {
 
     /**
      * Remove all flows present on the network node
-     * 
+     *
      * @param node
      */
     Status removeAllFlows(Node node);
@@ -78,14 +78,14 @@ public interface IPluginInFlowProgrammerService {
     /**
      * Send Barrier message synchronously. The caller will be blocked until the
      * Barrier reply arrives.
-     * 
+     *
      * @param node
      */
     Status syncSendBarrierMessage(Node node);
 
     /**
      * Send Barrier message asynchronously. The caller is not blocked.
-     * 
+     *
      * @param node
      */
     Status asyncSendBarrierMessage(Node node);
index f1b80272d43083da329a4528679c2b7562a7b978..1fc6741611495b42eb2beb3ad89e39f1103db117 100644 (file)
@@ -20,7 +20,7 @@ public interface IPluginOutFlowProgrammerService {
      * Inform SAL that the flow on the specified node has been removed Consumer
      * has to expect this notification only for flows which were installed with
      * an idle or hard timeout specified.
-     * 
+     *
      * @param node
      *            the network node on which the flow got removed
      * @param flow
@@ -33,7 +33,7 @@ public interface IPluginOutFlowProgrammerService {
      * Inform SAL that an error message has been received from a switch
      * regarding a flow message previously sent to the switch. A Request ID
      * associated with the offending message is also returned.
-     * 
+     *
      * @param node
      *            the network node on which the error reported
      * @param rid
index ccfb3388494452088203732a2b322654b7d5fe2a..0438023165a18293fa522041d1bf9fd3d6eb7da6 100644 (file)
@@ -24,22 +24,22 @@ public interface IListenInventoryUpdates {
     /**
      * This method is called when some properties of a node are added/deleted/changed.
      *
-     * @param node                     {@link org.opendaylight.controller.sal.core.Node} being updated
-     * @param type             {@link org.opendaylight.controller.sal.core.UpdateType}
-     * @param props            set of {@link org.opendaylight.controller.sal.core.Property} such as
-     *                                                 {@link org.opendaylight.controller.sal.core.Description} and/or
-     *                                                 {@link org.opendaylight.controller.sal.core.Tier} etc.
+     * @param node                      {@link org.opendaylight.controller.sal.core.Node} being updated
+     * @param type              {@link org.opendaylight.controller.sal.core.UpdateType}
+     * @param props             set of {@link org.opendaylight.controller.sal.core.Property} such as
+     *                                          {@link org.opendaylight.controller.sal.core.Description} and/or
+     *                                          {@link org.opendaylight.controller.sal.core.Tier} etc.
      */
     public void updateNode(Node node, UpdateType type, Set<Property> props);
 
     /**
      * This method is called when some properties of a node connector are added/deleted/changed.
      *
-     * @param nodeConnector    {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
-     * @param type             {@link org.opendaylight.controller.sal.core.UpdateType}
-     * @param props            set of {@link org.opendaylight.controller.sal.core.Property} such as
-     *                                                 {@link org.opendaylight.controller.sal.core.Description} and/or
-     *                                                 {@link org.opendaylight.controller.sal.core.State} etc.
+     * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
+     * @param type              {@link org.opendaylight.controller.sal.core.UpdateType}
+     * @param props             set of {@link org.opendaylight.controller.sal.core.Property} such as
+     *                                          {@link org.opendaylight.controller.sal.core.Description} and/or
+     *                                          {@link org.opendaylight.controller.sal.core.State} etc.
      */
     public void updateNodeConnector(NodeConnector nodeConnector,
             UpdateType type, Set<Property> props);
index 42c9ab7475ef09f4e3289124f56a5a591df9f037..bda32b88fa8796583b32019fc3f057b9ceff5ad4 100644 (file)
@@ -24,22 +24,22 @@ public interface IPluginOutInventoryService {
     /**
      * This method is called when some properties of a node are added/deleted/changed.
      *
-     * @param node                     {@link org.opendaylight.controller.sal.core.Node} being updated
-     * @param type             {@link org.opendaylight.controller.sal.core.UpdateType}
-     * @param props            set of {@link org.opendaylight.controller.sal.core.Property} such as
-     *                                                 {@link org.opendaylight.controller.sal.core.Description} and/or
-     *                                                 {@link org.opendaylight.controller.sal.core.Tier} etc.
+     * @param node                      {@link org.opendaylight.controller.sal.core.Node} being updated
+     * @param type              {@link org.opendaylight.controller.sal.core.UpdateType}
+     * @param props             set of {@link org.opendaylight.controller.sal.core.Property} such as
+     *                                          {@link org.opendaylight.controller.sal.core.Description} and/or
+     *                                          {@link org.opendaylight.controller.sal.core.Tier} etc.
      */
     public void updateNode(Node node, UpdateType type, Set<Property> props);
 
     /**
      * This method is called when some properties of a node connector are added/deleted/changed.
      *
-     * @param nodeConnector    {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
-     * @param type             {@link org.opendaylight.controller.sal.core.UpdateType}
-     * @param props            set of {@link org.opendaylight.controller.sal.core.Property} such as
-     *                                                 {@link org.opendaylight.controller.sal.core.Description} and/or
-     *                                                 {@link org.opendaylight.controller.sal.core.State} etc.
+     * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
+     * @param type              {@link org.opendaylight.controller.sal.core.UpdateType}
+     * @param props             set of {@link org.opendaylight.controller.sal.core.Property} such as
+     *                                          {@link org.opendaylight.controller.sal.core.Description} and/or
+     *                                          {@link org.opendaylight.controller.sal.core.State} etc.
      */
     public void updateNodeConnector(NodeConnector nodeConnector,
             UpdateType type, Set<Property> props);
index 2ead8cdbc4b7e645b6d6a0a6d0ae8039c08923f2..00a2f57308d57e1d76c8f0e88aeb86d74a3f910a 100644 (file)
@@ -38,8 +38,8 @@ import org.opendaylight.controller.sal.utils.NetUtils;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 public class Match implements Cloneable, Serializable {
-       private static final long serialVersionUID = 1L;
-       private static final Map<MatchType, MatchType> reversableMatches;
+        private static final long serialVersionUID = 1L;
+        private static final Map<MatchType, MatchType> reversableMatches;
     static {
         Map<MatchType, MatchType> map = new HashMap<MatchType, MatchType>();
         map.put(MatchType.DL_SRC, MatchType.DL_DST);
@@ -67,9 +67,9 @@ public class Match implements Cloneable, Serializable {
      * Generic setter for frame/packet/message's header fields against which to match
      * Note: For MAC addresses, please pass the cloned value to this function
      *
-     * @param type             packet's header field type
-     * @param value    field's value to assign to the match
-     * @param mask             field's bitmask to apply to the match (has to be of the same class type of value)
+     * @param type      packet's header field type
+     * @param value     field's value to assign to the match
+     * @param mask      field's bitmask to apply to the match (has to be of the same class type of value)
      */
     public void setField(MatchType type, Object value, Object mask) {
         MatchField field = new MatchField(type, value, mask);
@@ -83,8 +83,8 @@ public class Match implements Cloneable, Serializable {
      * Generic setter for frame/packet/message's header fields against which to match
      * Note: For MAC addresses, please pass the cloned value to this function
      *
-     * @param type             packet's header field type
-     * @param value    field's value to assign to the match
+     * @param type      packet's header field type
+     * @param value     field's value to assign to the match
      */
     public void setField(MatchType type, Object value) {
         MatchField field = new MatchField(type, value);
@@ -117,7 +117,7 @@ public class Match implements Cloneable, Serializable {
     /**
      * Generic getter for fields against which the match is programmed
      *
-     * @param type     frame/packet/message's header field type
+     * @param type  frame/packet/message's header field type
      * @return
      */
     public MatchField getField(MatchType type) {
@@ -137,7 +137,7 @@ public class Match implements Cloneable, Serializable {
     /**
      * Returns the list of MatchType fields the match is set for
      *
-     * @return List of individual MatchType fields. 
+     * @return List of individual MatchType fields.
      */
     public List<MatchType> getMatchesList() {
         return new ArrayList<MatchType>(fields.keySet());
@@ -146,13 +146,13 @@ public class Match implements Cloneable, Serializable {
     /**
      * Returns the list of MatchFields the match is set for
      *
-     * @return List of individual MatchField values. 
+     * @return List of individual MatchField values.
      */
     @XmlElement(name="matchField")
     public List<MatchField> getMatchFields() {
-       return new ArrayList<MatchField>(fields.values());
+        return new ArrayList<MatchField>(fields.values());
     }
-    
+
     /**
      * Returns whether this match is for an IPv6 flow
      */
index 7d7b29c293aca87bdfcc35b48f8abda3fe4a1055..bd5ef2bafbd4134e74469824962b6e18f42edaeb 100644 (file)
@@ -20,7 +20,7 @@ import org.slf4j.LoggerFactory;
 
 /**
  * Represents the generic matching field
- * 
+ *
  */
 
 @XmlRootElement
@@ -42,7 +42,7 @@ public class MatchField implements Cloneable, Serializable {
 
     /**
      * Mask based match constructor
-     * 
+     *
      * @param type
      * @param value
      * @param mask
@@ -59,7 +59,7 @@ public class MatchField implements Cloneable, Serializable {
 
     /**
      * Full match constructor
-     * 
+     *
      * @param type
      * @param value
      */
@@ -73,7 +73,7 @@ public class MatchField implements Cloneable, Serializable {
 
     /**
      * Returns the value set for this match field
-     * 
+     *
      * @return
      */
     public Object getValue() {
@@ -87,7 +87,7 @@ public class MatchField implements Cloneable, Serializable {
 
     /**
      * Returns the type field this match field object is for
-     * 
+     *
      * @return
      */
     public MatchType getType() {
@@ -102,7 +102,7 @@ public class MatchField implements Cloneable, Serializable {
     /**
      * Returns the mask value set for this field match A null mask means this is
      * a full match
-     * 
+     *
      * @return
      */
     public Object getMask() {
@@ -116,7 +116,7 @@ public class MatchField implements Cloneable, Serializable {
 
     /**
      * Returns the bitmask set for this field match
-     * 
+     *
      * @return
      */
     public long getBitMask() {
@@ -125,7 +125,7 @@ public class MatchField implements Cloneable, Serializable {
 
     /**
      * Returns whether the field match configuration is valid or not
-     * 
+     *
      * @return
      */
     public boolean isValid() {
index 5ad4bd5b660dbc58e4041a5422205d61edf4a3d0..62c1b435dc1d0a37b377c9f1ebb79f79aa1ecc77 100644 (file)
@@ -19,9 +19,9 @@ import org.opendaylight.controller.sal.utils.NetUtils;
  * Represents the binding between the id, the value and mask type and the range
  * values of the elements type that can be matched on the network
  * frame/packet/message
- * 
- * 
- * 
+ *
+ *
+ *
  */
 public enum MatchType {
     IN_PORT("inPort", 1 << 0, NodeConnector.class, 1, 0),
@@ -73,7 +73,7 @@ public enum MatchType {
 
     /**
      * Perform the assignment type validation
-     * 
+     *
      * @param value
      * @param mask
      * @return
@@ -119,7 +119,7 @@ public enum MatchType {
 
     /**
      * Perform the value and mask range validation
-     * 
+     *
      * @param value
      * @param mask
      * @return
@@ -162,7 +162,7 @@ public enum MatchType {
 
     /**
      * Return the mask value in 64 bits bitmask form
-     * 
+     *
      * @param mask
      * @return
      */
index dd51e85f20ee4bd9b6ba2d9e64ac0965a1fc33b2..8fc0d625ebe0dd5b08bff4df864efe6a2e3068bd 100644 (file)
@@ -37,6 +37,8 @@ public class ARP extends Packet {
     public static short REQUEST = (short) 0x1;
     public static short REPLY = (short) 0x2;
 
+    public static short PROTO_TYPE_IP = 0x800;
+
     private static Map<String, Pair<Integer, Integer>> fieldCoordinates = new LinkedHashMap<String, Pair<Integer, Integer>>() {
         private static final long serialVersionUID = 1L;
         {
index 5c81a1830b58010bea88f7d5b238ccf58463a75d..c3982ae08e280dc1fd45b70896934791cfe7f092 100644 (file)
@@ -210,7 +210,7 @@ public abstract class BitBufferHelper {
      * @param int startOffset - offset to start fetching bits from data from
      * @param int numBits - number of bits to be fetched from data
      * @return byte [] - LSB aligned bits
-     * 
+     *
      * @throws BufferException
      *             when the startOffset and numBits parameters are not congruent
      *             with the data buffer size
@@ -291,7 +291,7 @@ public abstract class BitBufferHelper {
      * @param byte - input byte to be inserted
      * @param startOffset - offset of data[] to start inserting byte from
      * @param numBits - number of bits of input to be inserted into data[]
-     * 
+     *
      * @throws BufferException
      *             when the input, startOffset and numBits are not congruent
      *             with the data buffer size
@@ -322,7 +322,7 @@ public abstract class BitBufferHelper {
 
     /**
      * Returns numBits 1's in the MSB position
-     * 
+     *
      * @param numBits
      * @return
      */
@@ -336,7 +336,7 @@ public abstract class BitBufferHelper {
 
     /**
      * Returns numBits 1's in the LSB position
-     * 
+     *
      * @param numBits
      * @return
      */
@@ -350,7 +350,7 @@ public abstract class BitBufferHelper {
 
     /**
      * Returns the numerical value of the byte array passed
-     * 
+     *
      * @param byte[] - array
      * @return long - numerical value of byte array passed
      */
@@ -371,7 +371,7 @@ public abstract class BitBufferHelper {
     /**
      * Returns the numerical value of the last numBits (LSB bits) of the byte
      * array passed
-     * 
+     *
      * @param byte[] - array
      * @param int - numBits
      * @return long - numerical value of byte array passed
@@ -404,10 +404,10 @@ public abstract class BitBufferHelper {
      * Accepts a number as input and returns its value in byte form in LSB
      * aligned form example: input = 5000 [1001110001000] bytes = 19, -120
      * [00010011] [10001000]
-     * 
+     *
      * @param Number
      * @return byte[]
-     * 
+     *
      */
 
     public static byte[] toByteArray(Number input) {
@@ -443,12 +443,12 @@ public abstract class BitBufferHelper {
      * Accepts a number as input and returns its value in byte form in MSB
      * aligned form example: input = 5000 [1001110001000] bytes = -114, 64
      * [10011100] [01000000]
-     * 
+     *
      * @param Number
      *            input
      * @param int numBits - the number of bits to be returned
      * @return byte[]
-     * 
+     *
      */
     public static byte[] toByteArray(Number input, int numBits) {
         Class<? extends Number> dataType = input.getClass();
@@ -500,7 +500,7 @@ public abstract class BitBufferHelper {
     /**
      * Takes an LSB aligned byte array and returned the LSB numBits in a MSB
      * aligned byte array
-     * 
+     *
      * @param inputbytes
      * @param numBits
      * @return
@@ -508,10 +508,10 @@ public abstract class BitBufferHelper {
     /**
      * It aligns the last numBits bits to the head of the byte array following
      * them with numBits % 8 zero bits.
-     * 
+     *
      * Example: For inputbytes = [00000111][01110001] and numBits = 12 it
      * returns: shiftedBytes = [01110111][00010000]
-     * 
+     *
      * @param byte[] inputBytes
      * @param int numBits - number of bits to be left aligned
      * @return byte[]
@@ -566,10 +566,10 @@ public abstract class BitBufferHelper {
     /**
      * It aligns the first numBits bits to the right end of the byte array
      * preceding them with numBits % 8 zero bits.
-     * 
+     *
      * Example: For inputbytes = [01110111][00010000] and numBits = 12 it
      * returns: shiftedBytes = [00000111][01110001]
-     * 
+     *
      * @param byte[] inputBytes
      * @param int numBits - number of bits to be right aligned
      * @return byte[]
@@ -603,7 +603,7 @@ public abstract class BitBufferHelper {
      * Insert in the data buffer at position dictated by the offset the number
      * of bits specified from the input data byte array. The input byte array
      * has the bits stored starting from the LSB
-     * 
+     *
      * @param byte[] data
      * @param byte[] inputdata
      * @param int startOffset
@@ -623,8 +623,8 @@ public abstract class BitBufferHelper {
         int InputMSBbits = 0, InputLSBbits = 0;
         int i;
 
-        if (numBits == 0) { 
-            return; 
+        if (numBits == 0) {
+            return;
         }
 
         if (extraOffsetBits == 0) {
index 0429c0dd279e1231ace4a0bfd7c6b880163101ba..9bdb5d084c57b7fede9fe1557a4934ae31e981e4 100644 (file)
@@ -68,7 +68,7 @@ public class ICMP extends Packet {
 
     /**
      * Sets the type for the current ICMP message
-     * 
+     *
      * @param type
      *            The ICMP message type
      * @return This ICMP object
@@ -81,7 +81,7 @@ public class ICMP extends Packet {
 
     /**
      * Sets the ICMP code (type subtype) for the current ICMP object instance
-     * 
+     *
      * @param code
      *            The ICMP message type subtype
      * @return This ICMP object
@@ -136,7 +136,7 @@ public class ICMP extends Packet {
 
     /**
      * Computes the ICMP checksum on the serialized ICMP message
-     * 
+     *
      * @param serialized
      *            The data stream
      * @param start
index 44318aab8c5c1626eb787b960acfaa3ede7bea29..7a7a5a757fb4ab4ff7184da84a25662f42729e07 100644 (file)
@@ -378,9 +378,9 @@ public class IPv4 extends Packet {
      * @param checksum the checksum to set
      */
     /*public IPv4 setChecksum() {
-       short ipChecksum = computeChecksum();
+        short ipChecksum = computeChecksum();
         byte[] checksum = BitBufferHelper.toByteArray(ipChecksum);
-       fieldValues.put(CHECKSUM, checksum);
+        fieldValues.put(CHECKSUM, checksum);
         return this;
     }*/
 
@@ -444,7 +444,7 @@ public class IPv4 extends Packet {
     /**
      * Computes the IPv4 header checksum on the passed stream of bytes
      * representing the packet
-     * 
+     *
      * @param data
      *            The byte stream
      * @param offset
index 562d03b7abe503088664c28d5ecb04bb546b1258..6a896c6c712aee0e06d94b7be31bbf27529c7845 100644 (file)
@@ -223,7 +223,7 @@ public class LLDP extends Packet {
 
     /**
      * Returns the size of LLDP packet in bytes
-     * 
+     *
      * @return int - LLDP Packet size in bytes
      */
     private int getLLDPPacketLength() {
index ee5027335921b95c2b86b069cb05506d0126830a..5685b0a58af2e16300104e9ccd7f482b311ec0be 100644 (file)
@@ -11,7 +11,7 @@ package org.opendaylight.controller.sal.packet;
  * Describes an exception that is raised when the process of serializing or
  * deserializing a network packet/stream fails. This generally happens when the
  * packet/stream is malformed.
- * 
+ *
  */
 public class PacketException extends Exception {
     private static final long serialVersionUID = 1L;
index a7956d81b3d178ffa5b0a06052e000de1a389fa3..590f5d923e792f03f4abc8498bd405c64e770204 100644 (file)
@@ -24,10 +24,10 @@ import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.core.TimeStamp;
 
 /**
- * 
+ *
  * Describe a raw Data Packet, this is how a packet is received from the network
  * and how it will be transmitted. It essentially wraps the raw bytestream
- * 
+ *
  */
 public class RawPacket {
     private byte[] packetData;
@@ -41,8 +41,8 @@ public class RawPacket {
     /**
      * If the packet is being sent this parameter tells where the packet is sent
      * toward
-     * 
-     * 
+     *
+     *
      * @return the NodeConnector toward where the packet is being sent
      */
     public NodeConnector getOutgoingNodeConnector() {
@@ -51,7 +51,7 @@ public class RawPacket {
 
     /**
      * Setter method for OutGoing NodeConnector
-     * 
+     *
      * @param outgoingNodeConnector
      *            NodeConnector toward where the packet is travelling
      */
@@ -61,7 +61,7 @@ public class RawPacket {
 
     /**
      * Return the incoming NodeConnector if the packet was received
-     * 
+     *
      * @return NodeConnector where the packet was received from
      */
     public NodeConnector getIncomingNodeConnector() {
@@ -70,7 +70,7 @@ public class RawPacket {
 
     /**
      * Setter for Incoming NodeConnector
-     * 
+     *
      * @param incomingNodeConnector
      *            NodeConnector to be used and incoming one
      */
@@ -80,10 +80,10 @@ public class RawPacket {
 
     /**
      * Retrieve a given property attached to the packet, if exits of course
-     * 
+     *
      * @param key
      *            Key to retrieve the wanted property attached to the packet
-     * 
+     *
      * @return The property attached to the packet
      */
     public Object getProps(Object key) {
@@ -95,7 +95,7 @@ public class RawPacket {
 
     /**
      * Generic data associated to the data packet
-     * 
+     *
      * @param key
      *            key for the association
      * @param value
@@ -111,12 +111,12 @@ public class RawPacket {
 
     /**
      * Constructor for RawPacket
-     * 
+     *
      * @param data
      *            content of the packet as bytestream
      * @param e
      *            datalink encapsulation for the packet
-     * 
+     *
      */
     public RawPacket(byte[] data, LinkEncap e) throws ConstructionException {
         if (data == null) {
@@ -137,10 +137,10 @@ public class RawPacket {
      * Copy Constructor for RawPacket, it performs a copy of the packet so each
      * packet can be modified independently without worrying that source packet
      * content is touched
-     * 
+     *
      * @param src
      *            packet to copy data from
-     * 
+     *
      */
     public RawPacket(RawPacket src) throws ConstructionException {
         if (src == null) {
@@ -164,10 +164,10 @@ public class RawPacket {
 
     /**
      * Constructor for RawPacket with Ethernet encapsulation
-     * 
+     *
      * @param data
      *            content of the packet as bytestream
-     * 
+     *
      */
     public RawPacket(byte[] data) throws ConstructionException {
         this(data, LinkEncap.ETHERNET);
@@ -175,7 +175,7 @@ public class RawPacket {
 
     /**
      * Read the time stamp when the packet has entered the system
-     * 
+     *
      * @return The time stamp when the packet has entered the system
      */
     public TimeStamp getIncomingTime() {
@@ -184,7 +184,7 @@ public class RawPacket {
 
     /**
      * Read the packet encapsulation
-     * 
+     *
      * @return The encapsulation for the raw packet, necessary to start parsing
      *         the packet
      */
@@ -194,7 +194,7 @@ public class RawPacket {
 
     /**
      * Get bytestream of the packet body
-     * 
+     *
      * @return The raw bytestream composing the packet
      */
     public byte[] getPacketData() {
@@ -204,7 +204,7 @@ public class RawPacket {
     /**
      * Returns the time at which the current instance of RawPacket was created
      * as a copy of the original one.
-     * 
+     *
      * @return The time stamp at which this RawPacket instance was created. null
      *         if this is the original instance.
      */
index fba3f5c917ffc3b625c33c261c7e78b4a0245d01..b9bed9a67dd7aab46ed607f807ee7ed9787fe94b 100644 (file)
@@ -110,7 +110,7 @@ public class UDP extends Packet {
      */
     public void setHeaderField(String headerField, byte[] readValue) {
         /*if (headerField.equals("Protocol")) {
-               payloadClass = decodeMap.get(readValue);
+                payloadClass = decodeMap.get(readValue);
         }*/
         hdrFieldsMap.put(headerField, readValue);
     }
index 0c14517b192e36b7d579a417382675788af1ef2c..96a992b3c366c23d993197755d13c984298580c9 100644 (file)
@@ -14,8 +14,6 @@ import java.io.Serializable;
 import javax.xml.bind.annotation.XmlRootElement;
 import javax.xml.bind.annotation.XmlSeeAlso;
 
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
-
 /**
  * @file   DataLinkAddress.java
  *
@@ -94,7 +92,6 @@ abstract public class DataLinkAddress implements Serializable {
 
     @Override
     public String toString() {
-        return "DataLinkAddress[" + ReflectionToStringBuilder.toString(this)
-                + "]";
+        return "DataLinkAddress [name=" + name + "]";
     }
 }
index 2afaea8f42f91db209d9ed30d77bce17a53d0dfe..6cd14eadce78c48235412f907188ce86c8b50059 100644 (file)
@@ -17,7 +17,6 @@ import javax.xml.bind.annotation.XmlElement;
 import javax.xml.bind.annotation.XmlRootElement;
 import javax.xml.bind.annotation.XmlTransient;
 
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
 import org.opendaylight.controller.sal.core.ConstructionException;
 import org.opendaylight.controller.sal.utils.HexEncode;
 
@@ -117,7 +116,7 @@ public class EthernetAddress extends DataLinkAddress {
 
     @Override
     public String toString() {
-        return "EthernetAddress[" + ReflectionToStringBuilder.toString(this)
+        return "EthernetAddress [macAddress=" + HexEncode.bytesToHexStringFormat(macAddress)
                 + "]";
     }
 
index 431f5895638d52a1f14abcb515db65fb17d4b48e..fe93d1c985878dfad7f0c3d0d0e392530cbe8132 100644 (file)
@@ -40,7 +40,7 @@ public class FlowOnNode {
     /* Dummy constructor for JAXB */
     private FlowOnNode () {
     }
-    
+
     public FlowOnNode(Flow flow) {
         this.flow = flow;
     }
index a8c83e7913b25c227ed0f042d48d0a097ce75dae..49018d83edde915d6334fa39c5ad9a5e97ae872f 100644 (file)
@@ -25,37 +25,37 @@ import org.opendaylight.controller.sal.core.NodeConnector;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 public class NodeConnectorStatistics {
-       @XmlElement
+        @XmlElement
     private NodeConnector nodeConnector;
-       @XmlElement
+        @XmlElement
     private long receivePackets;
-       @XmlElement
+        @XmlElement
     private long transmitPackets;
-       @XmlElement
+        @XmlElement
     private long receiveBytes;
-       @XmlElement
+        @XmlElement
     private long transmitBytes;
-       @XmlElement
+        @XmlElement
     private long receiveDrops;
-       @XmlElement
+        @XmlElement
     private long transmitDrops;
-       @XmlElement
+        @XmlElement
     private long receiveErrors;
-       @XmlElement
+        @XmlElement
     private long transmitErrors;
-       @XmlElement
+        @XmlElement
     private long receiveFrameError;
-       @XmlElement
+        @XmlElement
     private long receiveOverRunError;
-       @XmlElement
+        @XmlElement
     private long receiveCrcError;
-       @XmlElement
+        @XmlElement
     private long collisionCount;
 
-       //To Satisfy JAXB
-       public NodeConnectorStatistics() {
-               
-       }
+        //To Satisfy JAXB
+        public NodeConnectorStatistics() {
+
+        }
     /**
      * Set the node connector
      * @param port
index 65efd3c29dc1dc944b6dbe52e2c629d0dd6e6ec8..26c8e1dec352673efff83fcc9350bb053567338e 100644 (file)
@@ -67,7 +67,7 @@ public class NodeDescription {
     @Override
     public String toString() {
         return "HwDescription[manufacturer=" + manufacturer + ", hardware="
-                       + hardware + ", software=" + software + ", serialNumber=" 
-                       + serialNumber + ", description=" + description + "]";
+                        + hardware + ", software=" + software + ", serialNumber="
+                        + serialNumber + ", description=" + description + "]";
     }
 }
index 3ccf8f59297701c0848bade6a9ef0a404a6ce6a0..46448bd09832d31493542b17aa9bc2f129820f1b 100644 (file)
@@ -17,7 +17,7 @@ import org.opendaylight.controller.sal.core.NodeTable;
 /**
  * @author Aditya Prakash Vaja <aditya.vaja@bigswitch.com>
  * Represents the Table statistics for the node
- * 
+ *
  */
 
 @XmlRootElement
index b4c44c00d94ba82fdb8b8ac1190321a575e697b7..11cdc990131a1ab6bbadc9cb142fcc7fb4476205 100644 (file)
@@ -25,12 +25,12 @@ import org.opendaylight.controller.sal.core.Edge;
 
 /**
  * Topology notifications provided by SAL toward the application
- * 
+ *
  */
 public interface IListenTopoUpdates {
     /**
      * Called to update on Edge in the topology graph
-     * 
+     *
      * @param topoedgeupdateList
      *            List of topoedgeupdates Each topoedgeupdate includes edge, its
      *            Properties ( BandWidth and/or Latency etc) and update type.
@@ -40,7 +40,7 @@ public interface IListenTopoUpdates {
     /**
      * Called when an Edge utilization is above the safety threshold configured
      * on the controller
-     * 
+     *
      * @param edge
      *            The edge which bandwidth usage is above the safety level
      */
@@ -49,7 +49,7 @@ public interface IListenTopoUpdates {
     /**
      * Called when the Edge utilization is back to normal, below the safety
      * threshold level configured on the controller
-     * 
+     *
      * @param edge
      */
     public void edgeUtilBackToNormal(Edge edge);
index b85eec84283ab4c37918bf9916b8c0618a0a2a2b..6667628b0dcfc201a2d6e80aad1c49ad03cd97ce 100644 (file)
@@ -27,13 +27,13 @@ import org.opendaylight.controller.sal.core.UpdateType;
 
 /**
  * Methods that are invoked from Protocol Plugin toward SAL
- * 
+ *
  */
 public interface IPluginOutTopologyService {
 
     /**
      * Called to update on Edge in the topology graph
-     * 
+     *
      * @param topoedgeupdateList
      *            List of topoedgeupdates Each topoedgeupdate includes edge, its
      *            Properties ( BandWidth and/or Latency etc) and update type.
@@ -43,7 +43,7 @@ public interface IPluginOutTopologyService {
     /**
      * Called when an Edge utilization is above the safety threshold configured
      * on the controller
-     * 
+     *
      * @param edge
      */
     public void edgeOverUtilized(Edge edge);
@@ -51,7 +51,7 @@ public interface IPluginOutTopologyService {
     /**
      * Called when the Edge utilization is back to normal, below the safety
      * threshold level configured on the controller
-     * 
+     *
      * @param edge
      */
     public void edgeUtilBackToNormal(Edge edge);
index fff46eafaf99ba48b96d5d5093ad4102daa5bb23..58bf350c40e015878cad1ae01f9de3ca9e7f7596 100644 (file)
@@ -10,7 +10,6 @@ package org.opendaylight.controller.sal.topology;
 
 import java.util.Set;
 
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
 import org.opendaylight.controller.sal.core.Edge;
 import org.opendaylight.controller.sal.core.Property;
 import org.opendaylight.controller.sal.core.UpdateType;
@@ -54,8 +53,8 @@ public class TopoEdgeUpdate {
 
     @Override
     public String toString() {
-        return "TopoEdgeUpdate[" + ReflectionToStringBuilder.toString(this)
-                + "]";
+        return "TopoEdgeUpdate [edge=" + edge + ", props=" + props + ", type="
+                + type + "]";
     }
 
     @Override
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/FilterIterator.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/FilterIterator.java
new file mode 100644 (file)
index 0000000..cdd8607
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.sal.utils;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+/**
+ * An iterator that will filter values from an iterator and return only those
+ * values that match the predicate.
+ */
+public abstract class FilterIterator<T> implements Iterator<T> {
+    protected Iterator<T> subIterator;
+    protected T next;
+
+    /**
+     * Construct a filter iterator from the given sub iterator
+     *
+     * @param subIterator
+     *            the sub iterator over which we'll filter
+     */
+    public FilterIterator(Iterator<T> subIterator) {
+        super();
+        this.subIterator = subIterator;
+    }
+
+    /**
+     * Check whether the given value should be returned by the filter
+     *
+     * @param value
+     *            the value to check
+     * @return true if the value should be included
+     */
+    protected abstract boolean matches(T value);
+
+    // ***********
+    // Iterator<T>
+    // ***********
+
+    @Override
+    public boolean hasNext() {
+        if (next != null)
+            return true;
+
+        while (subIterator.hasNext()) {
+            next = subIterator.next();
+            if (matches(next))
+                return true;
+        }
+        next = null;
+        return false;
+    }
+
+    @Override
+    public T next() {
+        if (hasNext()) {
+            T cur = next;
+            next = null;
+            return cur;
+        }
+        throw new NoSuchElementException();
+    }
+
+    @Override
+    public void remove() {
+        throw new UnsupportedOperationException();
+    }
+
+}
index 6f60a522fdb5ba5780dc5034c9be45efee931528..0ebf633c55c123b742f8ba5365905f372f328b02 100644 (file)
@@ -14,11 +14,11 @@ package org.opendaylight.controller.sal.utils;
  *
  */
 public enum GlobalConstants {
-    DEFAULT("default"), 
-    CONTAINERMANAGER("containermanager"), 
-    CONTAINERNAME("name"), 
-    STATICVLAN("staticvlan"), 
-    CLUSTERINGSERVICES("clusteringservices"), 
+    DEFAULT("default"),
+    CONTAINERMANAGER("containermanager"),
+    CONTAINERNAME("name"),
+    STATICVLAN("staticvlan"),
+    CLUSTERINGSERVICES("clusteringservices"),
     STARTUPHOME("configuration/startup/");
 
     private GlobalConstants(String name) {
index 41b4b7a57ddc8deae989f3eb98605a10ca7a8bcd..37661358cd18a4eb0439db820efa5f42e3d8f8d4 100644 (file)
@@ -19,7 +19,7 @@ import java.math.BigInteger;
 public class HexEncode {
     /**
      * This method converts byte array into String format without ":" inserted.
-     * 
+     *
      * @param bytes
      *            The byte array to convert to string
      * @return The hexadecimal representation of the byte array. If bytes is
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IListener.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IListener.java
new file mode 100644 (file)
index 0000000..4196025
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2011 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.sal.utils;
+
+public interface IListener<T> {
+    public enum Command {
+        CONTINUE, STOP
+    }
+
+    /**
+     * The name assigned to this listener
+     *
+     * @return
+     */
+    public String getName();
+
+    /**
+     * Check if the module called name is a callback ordering prerequisite for
+     * this module. In other words, if this function returns true for the given
+     * name, then this listener will be called after that message listener.
+     *
+     * @param type
+     *            the object type to which this applies
+     * @param name
+     *            the name of the module
+     * @return whether name is a prerequisite.
+     */
+    public boolean isCallbackOrderingPrereq(T type, String name);
+
+    /**
+     * Check if the module called name is a callback ordering post-requisite for
+     * this module. In other words, if this function returns true for the given
+     * name, then this listener will be called before that message listener.
+     *
+     * @param type
+     *            the object type to which this applies
+     * @param name
+     *            the name of the module
+     * @return whether name is a post-requisite.
+     */
+    public boolean isCallbackOrderingPostreq(T type, String name);
+}
index 416018d98ed80d915d5e470c1db871436fc53e96..cdb4463c02acb2636a0991053f9e64951e3f3ba5 100644 (file)
@@ -23,14 +23,14 @@ import java.util.List;
 // Openflow 1.0 supports the IP Proto match only for ICMP, TCP and UDP
 public enum IPProtocols {
     ANY("any", 0),
-    /* HOPOPT("HOPOPT",0),
+    /*  HOPOPT("HOPOPT",0),
      */ICMP("ICMP", 1),
-    /* IGMP("IGMP",2),
+    /*  IGMP("IGMP",2),
      GGP("GGP",3),
      IPV4("IPv4",4),
      ST("ST",5),
      */TCP("TCP", 6),
-    /* CBT("CBT",7),
+    /*  CBT("CBT",7),
      EGP("EGP",8),
      IGP("IGP",9),
      BBNRCCMON("BBN-RCC-MON",10),
@@ -41,7 +41,7 @@ public enum IPProtocols {
      XNET("XNET",15),
      CHAOS("CHAOS",16),
      */UDP("UDP", 17),
-    /* MUX("MUX",18),
+    /*  MUX("MUX",18),
      DCNMEAS("DCN-MEAS",19),
      HMP("HMP",20),
      PRM("PRM",21),
@@ -82,7 +82,7 @@ public enum IPProtocols {
      TLSP("TLSP",56),
      SKIP("SKIP",57),
      */IPV6ICMP("IPv6-ICMP", 58);
-    /* IPV6NoNxt("IPv6-NoNxt",59),
+    /*  IPV6NoNxt("IPv6-NoNxt",59),
      IPV6Opts("IPv6-Opts",60),
      ANYHOST("ANY-HOST",61),
      CFTP("CFTP",62),
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IterableIterator.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IterableIterator.java
new file mode 100644 (file)
index 0000000..6d68f42
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.sal.utils;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+/**
+ * Iterator over all values in an iterator of iterators
+ *
+ * @param <T>
+ *            the type of elements returned by this iterator
+ */
+public class IterableIterator<T> implements Iterator<T> {
+    Iterator<? extends Iterable<T>> subIterator;
+    Iterator<T> current = null;
+
+    public IterableIterator(Iterator<? extends Iterable<T>> subIterator) {
+        super();
+        this.subIterator = subIterator;
+    }
+
+    @Override
+    public boolean hasNext() {
+        if (current == null) {
+            if (subIterator.hasNext()) {
+                current = subIterator.next().iterator();
+            } else {
+                return false;
+            }
+        }
+        while (!current.hasNext() && subIterator.hasNext()) {
+            current = subIterator.next().iterator();
+        }
+
+        return current.hasNext();
+    }
+
+    @Override
+    public T next() {
+        if (hasNext())
+            return current.next();
+        throw new NoSuchElementException();
+    }
+
+    @Override
+    public void remove() {
+        if (hasNext())
+            current.remove();
+        throw new NoSuchElementException();
+    }
+}
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ListenerDispatcher.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ListenerDispatcher.java
new file mode 100644 (file)
index 0000000..282bac6
--- /dev/null
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2011 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.sal.utils;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Maintain lists of listeners ordered by dependency.
+ *
+ * @author readams
+ *
+ */
+public class ListenerDispatcher<U, T extends IListener<U>> {
+    protected static Logger logger = LoggerFactory
+            .getLogger(ListenerDispatcher.class);
+    volatile List<T> listeners = new ArrayList<T>();
+
+    private void visit(List<T> newlisteners, U type, HashSet<T> visited,
+            List<T> ordering, T listener) {
+        if (!visited.contains(listener)) {
+            visited.add(listener);
+
+            for (T i : newlisteners) {
+                if (ispre(type, i, listener)) {
+                    visit(newlisteners, type, visited, ordering, i);
+                }
+            }
+            ordering.add(listener);
+        }
+    }
+
+    private boolean ispre(U type, T l1, T l2) {
+        return (l2.isCallbackOrderingPrereq(type, l1.getName()) || l1
+                .isCallbackOrderingPostreq(type, l2.getName()));
+    }
+
+    /**
+     * Add a listener to the list of listeners
+     *
+     * @param listener
+     */
+    public void addListener(U type, T listener) {
+        List<T> newlisteners = new ArrayList<T>();
+        if (listeners != null)
+            newlisteners.addAll(listeners);
+
+        newlisteners.add(listener);
+        // Find nodes without outgoing edges
+        List<T> terminals = new ArrayList<T>();
+        for (T i : newlisteners) {
+            boolean isterm = true;
+            for (T j : newlisteners) {
+                if (ispre(type, i, j)) {
+                    isterm = false;
+                    break;
+                }
+            }
+            if (isterm) {
+                terminals.add(i);
+            }
+        }
+
+        if (terminals.size() == 0) {
+            logger.error("No listener dependency solution: "
+                    + "No listeners without incoming dependencies");
+            listeners = newlisteners;
+            return;
+        }
+
+        // visit depth-first traversing in the opposite order from
+        // the dependencies. Note we will not generally detect cycles
+        HashSet<T> visited = new HashSet<T>();
+        List<T> ordering = new ArrayList<T>();
+        for (T term : terminals) {
+            visit(newlisteners, type, visited, ordering, term);
+        }
+        listeners = ordering;
+    }
+
+    /**
+     * Remove the given listener
+     *
+     * @param listener
+     *            the listener to remove
+     */
+    public void removeListener(T listener) {
+        if (listeners != null) {
+            List<T> newlisteners = new ArrayList<T>();
+            newlisteners.addAll(listeners);
+            newlisteners.remove(listener);
+            listeners = newlisteners;
+        }
+    }
+
+    /**
+     * Clear all listeners
+     */
+    public void clearListeners() {
+        listeners = new ArrayList<T>();
+    }
+
+    /**
+     * Get the ordered list of listeners ordered by dependencies
+     *
+     * @return
+     */
+    public List<T> getOrderedListeners() {
+        return listeners;
+    }
+}
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/MultiIterator.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/MultiIterator.java
new file mode 100644 (file)
index 0000000..42d080d
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2012 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.sal.utils;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+/**
+ * Iterator over all values in an iterator of iterators
+ *
+ * @param <T>
+ *            the type of elements returned by this iterator
+ */
+public class MultiIterator<T> implements Iterator<T> {
+    Iterator<Iterator<T>> subIterator;
+    Iterator<T> current = null;
+
+    public MultiIterator(Iterator<Iterator<T>> subIterator) {
+        super();
+        this.subIterator = subIterator;
+    }
+
+    @Override
+    public boolean hasNext() {
+        if (current == null) {
+            if (subIterator.hasNext()) {
+                current = subIterator.next();
+            } else {
+                return false;
+            }
+        }
+        while (!current.hasNext() && subIterator.hasNext()) {
+            current = subIterator.next();
+        }
+
+        return current.hasNext();
+    }
+
+    @Override
+    public T next() {
+        if (hasNext())
+            return current.next();
+        throw new NoSuchElementException();
+    }
+
+    @Override
+    public void remove() {
+        if (hasNext())
+            current.remove();
+        throw new NoSuchElementException();
+    }
+}
index 2591d931e1d70e5084531c464f8c2b8c5209317f..74da40449646059b640e96465b9b01bbf93ac2d5 100644 (file)
@@ -36,8 +36,8 @@ public abstract class NetUtils {
     /**
      * Converts a 4 bytes array into an integer number
      *
-     * @param ba       the 4 bytes long byte array
-     * @return     the integer number
+     * @param ba    the 4 bytes long byte array
+     * @return      the integer number
      */
     public static int byteArray4ToInt(byte[] ba) {
         if (ba == null || ba.length != 4) {
@@ -63,8 +63,8 @@ public abstract class NetUtils {
      * Converts an IP address passed as integer value into the
      * respective InetAddress object
      *
-     * @param address  the IP address in integer form
-     * @return                 the IP address in InetAddress form
+     * @param address   the IP address in integer form
+     * @return          the IP address in InetAddress form
      */
     public static InetAddress getInetAddress(int address) {
         InetAddress ip = null;
@@ -81,8 +81,8 @@ public abstract class NetUtils {
      * The prefix bit mask indicates the contiguous leading bits that are NOT masked out.
      * Example: A prefix bit mask length of 8 will give an InetAddress Network Mask of 255.0.0.0
      *
-     * @param prefixMaskLength integer representing the length of the prefix network mask
-     * @param isV6                             boolean representing the IP version of the returned address
+     * @param prefixMaskLength  integer representing the length of the prefix network mask
+     * @param isV6              boolean representing the IP version of the returned address
      * @return
      */
     public static InetAddress getInetNetworkMask(int prefixMaskLength,
@@ -122,8 +122,8 @@ public abstract class NetUtils {
      * while ff.00.00.00 will return a subnet mask length of 24.
      * If the passed prefixMask object is null, 0 is returned
      *
-     * @param prefixMask       the prefix mask as byte array
-     * @return                         the length of the prefix network mask
+     * @param prefixMask    the prefix mask as byte array
+     * @return              the length of the prefix network mask
      */
     public static int getSubnetMaskLength(byte[] prefixMask) {
         int maskLength = 0;
@@ -150,8 +150,8 @@ public abstract class NetUtils {
      * while ff.00.00.00 will return a subnet mask length of 24
      * If the passed prefixMask object is null, 0 is returned
      *
-     * @param prefixMask       the prefix mask as InetAddress
-     * @return                         the length of the prefix network mask
+     * @param prefixMask    the prefix mask as InetAddress
+     * @return              the length of the prefix network mask
      */
     public static int getSubnetMaskLength(InetAddress prefixMask) {
         return (prefixMask == null) ? 0 : NetUtils
@@ -163,9 +163,9 @@ public abstract class NetUtils {
      * the equivalent subnet prefix IP address
      * Example: for ip = "172.28.30.254" and maskLen = 25 it will return "172.28.30.128"
      *
-     * @param ip               the IP address in InetAddress form
-     * @param maskLen  the length of the prefix network mask
-     * @return                 the subnet prefix IP address in InetAddress form
+     * @param ip        the IP address in InetAddress form
+     * @param maskLen   the length of the prefix network mask
+     * @return          the subnet prefix IP address in InetAddress form
      */
     public static InetAddress getSubnetPrefix(InetAddress ip, int maskLen) {
         int bytes = maskLen / 8;
@@ -241,8 +241,8 @@ public abstract class NetUtils {
     /**
      * Returns true if the passed MAC address is all zero
      *
-     * @param mac      the byte array representing the MAC address
-     * @return         true if all MAC bytes are zero
+     * @param mac   the byte array representing the MAC address
+     * @return      true if all MAC bytes are zero
      */
     public static boolean isZeroMAC(byte[] mac) {
         for (short i = 0; i < 6; i++) {
@@ -256,8 +256,8 @@ public abstract class NetUtils {
     /**
      * Returns true if the passed InetAddress contains all zero
      *
-     * @param ip       the IP address to test
-     * @return         true if the address is all zero
+     * @param ip    the IP address to test
+     * @return      true if the address is all zero
      */
     public static boolean isAny(InetAddress ip) {
         for (byte b : ip.getAddress()) {
@@ -366,12 +366,12 @@ public abstract class NetUtils {
     /**
      * Returns the unsigned value of the passed byte variable
      *
-     * @param b        the byte value
+     * @param b the byte value
      * @return the int variable containing the unsigned byte value
      */
     public static int getUnsignedByte(byte b) {
-               return (b > 0)? (int)b : (b & 0x7F | 0x80);
-       }
+        return (b > 0)? (int)b : (b & 0x7F | 0x80);
+    }
 
     /**
      * Return the unsigned value of the passed short variable
@@ -379,7 +379,7 @@ public abstract class NetUtils {
      * @param s the short value
      * @return the int variable containing the unsigned short value
      */
-       public static int getUnsignedShort(short s) {
-               return (s > 0)? (int)s : (s & 0x7FFF | 0x8000);
-       }
+    public static int getUnsignedShort(short s) {
+        return (s > 0)? (int)s : (s & 0x7FFF | 0x8000);
+    }
 }
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/SingletonTask.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/SingletonTask.java
new file mode 100644 (file)
index 0000000..634caac
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2011,2013 Big Switch Networks, Inc.
+ *
+ * Licensed under the Eclipse Public License, Version 1.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ *      http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ *    Originally created by David Erickson, Stanford University
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the
+ *    License. You may obtain a copy of the License at
+ *
+ *         http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing,
+ *    software distributed under the License is distributed on an "AS
+ *    IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ *    express or implied. See the License for the specific language
+ *    governing permissions and limitations under the License.
+ */
+
+package org.opendaylight.controller.sal.utils;
+
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This allows you to represent a task that should be queued for future
+ * execution but where you only want the task to complete once in response to
+ * some sequence of events. For example, if you get a change notification and
+ * want to reload state, you only want to reload the state once, at the end, and
+ * don't want to queue an update for every notification that might come in.
+ *
+ * The semantics are as follows: * If the task hasn't begun yet, do not queue a
+ * new task * If the task has begun, set a bit to restart it after the current
+ * task finishes
+ */
+public class SingletonTask {
+    protected static Logger logger = LoggerFactory
+            .getLogger(SingletonTask.class);
+
+    protected static class SingletonTaskContext {
+        protected boolean taskShouldRun = false;
+        protected boolean taskRunning = false;
+
+        protected SingletonTaskWorker waitingTask = null;
+    }
+
+    protected static class SingletonTaskWorker implements Runnable {
+        SingletonTask parent;
+        boolean canceled = false;
+        long nextschedule = 0;
+
+        public SingletonTaskWorker(SingletonTask parent) {
+            super();
+            this.parent = parent;
+        }
+
+        @Override
+        public void run() {
+            synchronized (parent.context) {
+                if (canceled || !parent.context.taskShouldRun)
+                    return;
+
+                parent.context.taskRunning = true;
+                parent.context.taskShouldRun = false;
+            }
+
+            try {
+                parent.task.run();
+            } catch (Exception e) {
+                logger.error("Exception while executing task", e);
+            }
+
+            synchronized (parent.context) {
+                parent.context.taskRunning = false;
+
+                if (parent.context.taskShouldRun) {
+                    long now = System.nanoTime();
+                    if ((nextschedule <= 0 || (nextschedule - now) <= 0)) {
+                        parent.ses.execute(this);
+                    } else {
+                        parent.ses.schedule(this, nextschedule - now,
+                                TimeUnit.NANOSECONDS);
+                    }
+                }
+            }
+        }
+    }
+
+    protected SingletonTaskContext context = new SingletonTaskContext();
+    protected Runnable task;
+    protected ScheduledExecutorService ses;
+
+    /**
+     * Construct a new SingletonTask for the given runnable. The context is used
+     * to manage the state of the task execution and can be shared by more than
+     * one instance of the runnable.
+     *
+     * @param context
+     * @param Task
+     */
+    public SingletonTask(ScheduledExecutorService ses, Runnable task) {
+        super();
+        this.task = task;
+        this.ses = ses;
+    }
+
+    /**
+     * Schedule the task to run if there's not already a task scheduled If there
+     * is such a task waiting that has not already started, it cancel that task
+     * and reschedule it to run at the given time. If the task is already
+     * started, it will cause the task to be rescheduled once it completes to
+     * run after delay from the time of reschedule.
+     *
+     * @param delay
+     *            the delay in scheduling
+     * @param unit
+     *            the timeunit of the delay
+     */
+    public void reschedule(long delay, TimeUnit unit) {
+        boolean needQueue = true;
+        SingletonTaskWorker stw = null;
+
+        synchronized (context) {
+            if (context.taskRunning || context.taskShouldRun) {
+                if (context.taskRunning) {
+                    // schedule to restart at the right time
+                    if (delay > 0) {
+                        long now = System.nanoTime();
+                        long then = now
+                                + TimeUnit.NANOSECONDS.convert(delay, unit);
+                        context.waitingTask.nextschedule = then;
+                    } else {
+                        context.waitingTask.nextschedule = 0;
+                    }
+                    needQueue = false;
+                } else {
+                    // cancel and requeue
+                    context.waitingTask.canceled = true;
+                    context.waitingTask = null;
+                }
+            }
+
+            context.taskShouldRun = true;
+
+            if (needQueue) {
+                stw = context.waitingTask = new SingletonTaskWorker(this);
+            }
+        }
+
+        if (needQueue) {
+            if (delay <= 0)
+                ses.execute(stw);
+            else
+                ses.schedule(stw, delay, unit);
+        }
+    }
+}
\ No newline at end of file
index 2fbb3e55f841eb80db4f5397b3913683cd77c5cc..1d7ce224b5620f438947eeb29139309cd865b7f2 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved. 
+ * 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,
@@ -23,7 +23,7 @@ public class Status {
      * for internal API2 function calls. This constructor allows to specify,
      * beside the Status Code, a custom human readable description to add more
      * information about the status.
-     * 
+     *
      * @param errorCode
      *            The status code. If passed as null, code will be stored as
      *            {@code StatusCode.UNDEFINED}
@@ -42,7 +42,7 @@ public class Status {
      * Generates an instance of the Status class based on the passed StatusCode
      * only. The description field of the Status object will be inferred by the
      * status code.
-     * 
+     *
      * @param errorCode
      *            The status code. If passed as null, code will be stored as
      *            {@code StatusCode.UNDEFINED}
@@ -59,7 +59,7 @@ public class Status {
      * asynchronous call. It is supposed to be created by the underlying
      * infrastructure only when it was successful in allocating the asynchronous
      * request id, hence caller should expect StatusCode to be successful.
-     * 
+     *
      * @param errorCode
      *            The status code. If passed as null, code will be stored as
      *            {@code StatusCode.UNDEFINED}
@@ -76,7 +76,7 @@ public class Status {
 
     /**
      * Returns the status code
-     * 
+     *
      * @return the {@code StatusCode} representing the status code
      */
     public StatusCode getCode() {
@@ -85,7 +85,7 @@ public class Status {
 
     /**
      * Returns a human readable description of the failure if any
-     * 
+     *
      * @return a string representing the reason of failure
      */
     public String getDescription() {
@@ -94,7 +94,7 @@ public class Status {
 
     /**
      * Tells whether the status is successful
-     * 
+     *
      * @return true if the Status code is {@code StatusCode.SUCCESS}
      */
     public boolean isSuccess() {
@@ -105,7 +105,7 @@ public class Status {
      * Return the request id assigned by underlying infrastructure in case of
      * asynchronous request. In case of synchronous requests, the returned id
      * is expected to be 0
-     * 
+     *
      * @return The request id assigned for this asynchronous request
      */
     public long getRequestId() {
index 8500d6398de4f2b39f91c912dacc1ce2a4d8bbe2..ce91ff440d1f70f4dba814700e7d65c34c1873af 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved. 
+ * 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,
@@ -10,39 +10,39 @@ package org.opendaylight.controller.sal.utils;
 
 /**
  * The enum which describes the generic error conditions.
- * Each enum value is associated with a minimal description string. 
+ * Each enum value is associated with a minimal description string.
  *
  */
 public enum StatusCode {
-       SUCCESS("Success"),
-
-       BADREQUEST("Bad Request"),
-       UNAUTHORIZED("UnAuthorized"),
-       FORBIDDEN("Forbidden"),
-       NOTFOUND("Not Found"),
-       NOTALLOWED("Method Not Allowed"),
-       NOTACCEPTABLE("Request Not Acceptable"),
-       TIMEOUT("Request Timeout"),
-       CONFLICT("Resource Conflict"),
-       GONE("Resource Gone"),
-       UNSUPPORTED("Unsupported"),
-
-       INTERNALERROR("Internal Error"), 
-       NOTIMPLEMENTED("Not Implemented"),
-       NOSERVICE("Service Not Available"),
-       
-       UNDEFINED("Undefined Error");
-       
-       private String description;
-       private StatusCode(String description) {
-               this.description = description; 
-       }
-       
-       /**
-        * Prints the description associated to the code value
-        */
-       public String toString() {
-               return description;
-       }
+        SUCCESS("Success"),
+
+        BADREQUEST("Bad Request"),
+        UNAUTHORIZED("UnAuthorized"),
+        FORBIDDEN("Forbidden"),
+        NOTFOUND("Not Found"),
+        NOTALLOWED("Method Not Allowed"),
+        NOTACCEPTABLE("Request Not Acceptable"),
+        TIMEOUT("Request Timeout"),
+        CONFLICT("Resource Conflict"),
+        GONE("Resource Gone"),
+        UNSUPPORTED("Unsupported"),
+
+        INTERNALERROR("Internal Error"),
+        NOTIMPLEMENTED("Not Implemented"),
+        NOSERVICE("Service Not Available"),
+
+        UNDEFINED("Undefined Error");
+
+        private String description;
+        private StatusCode(String description) {
+                this.description = description;
+        }
+
+        /**
+         * Prints the description associated to the code value
+         */
+        public String toString() {
+                return description;
+        }
 
 }
index 55adfdac5173022579e65e96a272418dbfa3f299..869d7ff5203d53043d548e79dd04dca0110c1ef4 100644 (file)
@@ -8,7 +8,7 @@
  */
 
 package org.opendaylight.controller.sal.authorization;
-               
+
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Map;
@@ -19,59 +19,59 @@ import org.junit.Test;
 
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.utils.NodeCreator;
-       
-       public class AuthorizationTest {
-       
-       @Test
-       public void testResources () {
-       Privilege p = Privilege.WRITE;
-       ResourceGroup resourceGroup = new ResourceGroup("NodeGroup", p);
-       Map<ResourceGroup, ArrayList<Resource>> resourceMap = new HashMap<ResourceGroup, ArrayList<Resource>>();
-       ArrayList<Resource> resourceList = new ArrayList<Resource>();
-       
-               for (int i = 0; i < 5; i++) {
-                       Node node = NodeCreator.createOFNode((long)i);
-                       Resource resource = new Resource (node, p);     
-                       resourceList.add(resource);
-               }
-               
-               resourceMap.put(resourceGroup, resourceList);
-               
-               ArrayList<Resource> retrievedResourceList = resourceMap.get(resourceGroup);
-               for (Entry<ResourceGroup, ArrayList<Resource>> entry : resourceMap.entrySet()) {
-                       ResourceGroup rGroup = entry.getKey();
-                       Assert.assertTrue(rGroup.getGroupName().equals(resourceGroup.getGroupName()));
-                       for (int i = 0; i < 5; i++) {
-                               Resource resource = retrievedResourceList.get(i);
-                               Assert.assertTrue(resource.getPrivilege().equals(Privilege.WRITE));
-                               Assert.assertTrue(((Long)((Node)resource.getResource()).getID()).equals((long)i));
-                       }
-               }
-       }
-       
-       @Test
-       public void testAppRoleLevel() {
-               AppRoleLevel appRoleLevel = AppRoleLevel.APPOPERATOR;
-               Assert.assertTrue(appRoleLevel.toString().equals("App-Operator"));
-               Assert.assertTrue(appRoleLevel.toNumber() == 2);
-               Assert.assertTrue(appRoleLevel.toStringPretty().equals("Application Operator"));
-       }
-       
-       @Test
-       public void testUserLevel() {
-               UserLevel userLevel = UserLevel.SYSTEMADMIN;
-               Assert.assertTrue(userLevel.toString().equals("System-Admin"));
-               Assert.assertTrue(userLevel.toNumber() == 0);
-               Assert.assertTrue(userLevel.toStringPretty().equals("System Administrator"));
-       }
-       
-       @Test
-       public void testAppRoleLevelFromString() {
-               Assert.assertTrue(AppRoleLevel.fromString("App-Admin") == AppRoleLevel.APPADMIN);
-               Assert.assertTrue(AppRoleLevel.fromString("App-User") == AppRoleLevel.APPUSER);
-               Assert.assertTrue(AppRoleLevel.fromString("App-Operator") == AppRoleLevel.APPOPERATOR);
-               Assert.assertTrue(AppRoleLevel.fromString(" ") == null);
-               Assert.assertTrue(AppRoleLevel.fromString("") == null);
-               Assert.assertTrue(AppRoleLevel.fromString("App-Admini") == null);               
-       }
+
+        public class AuthorizationTest {
+
+        @Test
+        public void testResources () {
+        Privilege p = Privilege.WRITE;
+        ResourceGroup resourceGroup = new ResourceGroup("NodeGroup", p);
+        Map<ResourceGroup, ArrayList<Resource>> resourceMap = new HashMap<ResourceGroup, ArrayList<Resource>>();
+        ArrayList<Resource> resourceList = new ArrayList<Resource>();
+
+                for (int i = 0; i < 5; i++) {
+                        Node node = NodeCreator.createOFNode((long)i);
+                        Resource resource = new Resource (node, p);
+                        resourceList.add(resource);
+                }
+
+                resourceMap.put(resourceGroup, resourceList);
+
+                ArrayList<Resource> retrievedResourceList = resourceMap.get(resourceGroup);
+                for (Entry<ResourceGroup, ArrayList<Resource>> entry : resourceMap.entrySet()) {
+                        ResourceGroup rGroup = entry.getKey();
+                        Assert.assertTrue(rGroup.getGroupName().equals(resourceGroup.getGroupName()));
+                        for (int i = 0; i < 5; i++) {
+                                Resource resource = retrievedResourceList.get(i);
+                                Assert.assertTrue(resource.getPrivilege().equals(Privilege.WRITE));
+                                Assert.assertTrue(((Long)((Node)resource.getResource()).getID()).equals((long)i));
+                        }
+                }
+        }
+
+        @Test
+        public void testAppRoleLevel() {
+                AppRoleLevel appRoleLevel = AppRoleLevel.APPOPERATOR;
+                Assert.assertTrue(appRoleLevel.toString().equals("App-Operator"));
+                Assert.assertTrue(appRoleLevel.toNumber() == 2);
+                Assert.assertTrue(appRoleLevel.toStringPretty().equals("Application Operator"));
+        }
+
+        @Test
+        public void testUserLevel() {
+                UserLevel userLevel = UserLevel.SYSTEMADMIN;
+                Assert.assertTrue(userLevel.toString().equals("System-Admin"));
+                Assert.assertTrue(userLevel.toNumber() == 0);
+                Assert.assertTrue(userLevel.toStringPretty().equals("System Administrator"));
+        }
+
+        @Test
+        public void testAppRoleLevelFromString() {
+                Assert.assertTrue(AppRoleLevel.fromString("App-Admin") == AppRoleLevel.APPADMIN);
+                Assert.assertTrue(AppRoleLevel.fromString("App-User") == AppRoleLevel.APPUSER);
+                Assert.assertTrue(AppRoleLevel.fromString("App-Operator") == AppRoleLevel.APPOPERATOR);
+                Assert.assertTrue(AppRoleLevel.fromString(" ") == null);
+                Assert.assertTrue(AppRoleLevel.fromString("") == null);
+                Assert.assertTrue(AppRoleLevel.fromString("App-Admini") == null);
+        }
 }
index c081e10645b6a1d2ff1f55dc942b47d932310344..c6697196d479f0764309c7906d3c5a97f0ccf8a8 100644 (file)
@@ -396,7 +396,7 @@ public class NodeTest {
     public void testExtensibleNode() {
         // Add a new ID type
         Assert.assertTrue(Node.NodeIDType.registerIDType("FOO", Integer.class));
-        
+
         // Trying to re-register the node must fail
         Assert.assertFalse(Node.NodeIDType.registerIDType("FOO",
                                                           Integer.class));
@@ -408,7 +408,7 @@ public class NodeTest {
             // Got an unexpected exception
             Assert.assertTrue(false);
         }
-        
+
         // Now unregister the type and make sure the node doesn't get
         // created
         Node.NodeIDType.unRegisterIDType("FOO");
index f257befd3c3d64ed15f8dcc76cd87b501135f49d..5ec7d089b68dc6a257df8a4cd6bd08edc27d44c0 100644 (file)
@@ -313,13 +313,13 @@ public class MatchTest {
         InetAddress ipMask2 = null;
         short ethertype = EtherTypes.IPv4.shortValue();
         short ethertype2 = EtherTypes.IPv4.shortValue();
-       
+
         /*
          * Create a SAL Flow aFlow
          */
         Match match1 = new Match();
         Match match2 = new Match();
-        
+
         match1.setField(MatchType.DL_TYPE, ethertype);
         match1.setField(MatchType.NW_SRC, srcIP, ipMask);
 
@@ -327,7 +327,7 @@ public class MatchTest {
         match2.setField(MatchType.NW_SRC, srcIP2, ipMask2);
 
         Assert.assertTrue(match1.equals(match2));
-        
+
         ipMask2 = InetAddress.getByName("255.255.255.255");
         match2.setField(MatchType.NW_SRC, srcIP2, ipMask2);
 
@@ -337,7 +337,7 @@ public class MatchTest {
         ipMask2 = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
         ethertype = EtherTypes.IPv6.shortValue();
         ethertype2 = EtherTypes.IPv6.shortValue();
+
         match1.setField(MatchType.DL_TYPE, ethertype);
         match1.setField(MatchType.NW_SRC, srcIP, ipMask);
 
@@ -346,7 +346,7 @@ public class MatchTest {
 
         Assert.assertTrue(match1.equals(match2));
     }
-    
+
     @Test
     public void testCloning() throws Exception {
         Node node = NodeCreator.createOFNode(7l);
index b1c5e945d69aa8c76e53f2de9f936eac1967bf5c..9f74fcab9e40b93601dd72ee8b0ed2f10a57e6e5 100644 (file)
@@ -374,7 +374,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data2[3] == 80);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               // OUTPUT: [01001011] [01101000] = {75, 104}
+        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        // OUTPUT: [01001011] [01101000] = {75, 104}
         byte data10[] = new byte[2];
         startOffset = 0;
         numBits = 13;
@@ -383,7 +383,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data10[1] == 104);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               // OUTPUT: [01001000] = {72}
+        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        // OUTPUT: [01001000] = {72}
         byte data11[] = new byte[4];
         startOffset = 8;
         numBits = 6;
@@ -391,7 +391,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data11[1] == 72);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [01001011] [01101110] [01101000] = {75, 110, 105}
+        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [01001011] [01101110] [01101000] = {75, 110, 105}
         byte data12[] = new byte[4];
         startOffset = 0;
         numBits = 23;
@@ -401,7 +401,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data12[2] == 106);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [01001011] [01101110] [01100000] = {75, 110, 96}
+        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [01001011] [01101110] [01100000] = {75, 110, 96}
         byte data13[] = new byte[4];
         startOffset = 8;
         numBits = 20;
@@ -411,7 +411,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data13[3] == 96);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [01001011] [01101110] [01101011] [10100000]= {75, 110, 107, 80}
+        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [01001011] [01101110] [01101011] [10100000]= {75, 110, 107, 80}
         byte data14[] = new byte[4];
         startOffset = 0;
         numBits = 30;
@@ -423,7 +423,7 @@ public class BitBufferHelperTest {
 
         //CASE 3: startOffset%8 != 0, numBits%8 = 0
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00001001] [11000000] = {72, 96}
+        // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00001001] [11000000] = {72, 96}
         byte data16[] = new byte[5];
         startOffset = 3;
         numBits = 8;
@@ -433,7 +433,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data16[2] == 0);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: [00000100] [1011 0110] [1110 0000] = {4, -54, -96}
 
         startOffset = 3;
@@ -458,7 +458,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data18[2] == -64);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: [0000 1001] [0110 1101] [1100 1101] [0110 1010] [0000 0001] = {9, 109, -51, 106, 0}
 
         startOffset = 3;
@@ -472,7 +472,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data19[4] == 0);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: data[4, 5, 6] = [0 010 0101] [1 011 0111] [0 000 0000] = {37, -73, 0}
         startOffset = 33;
         numBits = 16;
@@ -484,7 +484,7 @@ public class BitBufferHelperTest {
 
         //CASE 4: extranumBits != 0 AND extraOffsetBits != 0
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: [0000 1001] [0100 0000]  = {9, 96}
         startOffset = 3;
         numBits = 7;
@@ -495,7 +495,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data21[2] == 0);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: data = [00000 010] [01011 011] [01110 000] = {37, -73, 0}
         startOffset = 5;
         numBits = 17;
@@ -506,7 +506,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data22[2] == 112);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: [0000 1001] [0110 1101] [110 01101] [01 00000] = {9, 109, -51, 64}
         startOffset = 3;
         numBits = 23;
@@ -518,7 +518,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data23[3] == 64);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: [0000 1001] [0110 1101]  = {9, 109}
         startOffset = 3;
         numBits = 13;
@@ -529,7 +529,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data24[2] == 0);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: [0000 0100] [1011 0110] [1110 0110]  = {4, -74, -26}
         startOffset = 4;
         numBits = 20;
@@ -541,7 +541,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data25[3] == -0);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: [0000 0010] [0101 1011]   = {0, 2, 91, 0}
         startOffset = 13;
         numBits = 11;
@@ -553,7 +553,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data26[3] == 0);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: [000 01001] [011 01101] [110 0 0000]   = {9, 109, -64, 0}
         startOffset = 3;
         numBits = 17;
@@ -565,7 +565,7 @@ public class BitBufferHelperTest {
         Assert.assertTrue(data27[3] == 0);
 
         // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} =
-        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]               //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
+        // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]        //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96}
         // OUTPUT: [00 000000] [00 000000] [00 010010] [11 011011] [10 011010] [11 010100] [0000 0000] = {0, 0, 18, -37,-102,-44,0}
         startOffset = 18;
         numBits = 34;
index 8d856b08cdcafda4f9e89f2c78b0c87b33a7f8ce..8049000fa7d866d6b98abbaff5f4a7958952b642 100644 (file)
@@ -59,29 +59,29 @@ public class PacketTest {
         Assert.assertTrue(sMAC[5] == -97);
 
         Assert.assertTrue(etherType == 0x806);
-        
+
         ARP arpPacket = (ARP) eth.getPayload();
-        
+
         Assert.assertTrue(arpPacket.getHardwareType() == (byte)0x1);
         Assert.assertTrue(arpPacket.getProtocolType() == 2048);
         Assert.assertTrue(arpPacket.getHardwareAddressLength() == (byte)0x6);
         Assert.assertTrue(arpPacket.getProtocolAddressLength() == (byte)0x4);
         Assert.assertTrue(arpPacket.getOpCode() == 1);
-        
+
         byte[] senderHwAddress = arpPacket.getSenderHardwareAddress();
-        byte[] senderProtocolAddress = arpPacket.getSenderProtocolAddress(); 
-        
+        byte[] senderProtocolAddress = arpPacket.getSenderProtocolAddress();
+
         byte[] targetHwAddress = arpPacket.getTargetHardwareAddress();
-        byte[] targetProtocolAddress = arpPacket.getTargetProtocolAddress(); 
+        byte[] targetProtocolAddress = arpPacket.getTargetProtocolAddress();
+
 
-        
         Assert.assertTrue(senderHwAddress[0] == (byte)0xA6);
         Assert.assertTrue(senderHwAddress[1] == (byte)0xEC);
         Assert.assertTrue(senderHwAddress[2] == (byte)0x9C);
         Assert.assertTrue(senderHwAddress[3] == (byte)0xAE);
         Assert.assertTrue(senderHwAddress[4] == (byte)0xB2);
         Assert.assertTrue(senderHwAddress[5] == (byte)0x9F);
-        
+
         Assert.assertTrue(senderProtocolAddress[0] == (byte)0x9);
         Assert.assertTrue(senderProtocolAddress[1] == (byte)0x9);
         Assert.assertTrue(senderProtocolAddress[2] == (byte)0x9);
@@ -102,7 +102,7 @@ public class PacketTest {
         Assert.assertTrue(targetProtocolAddress[0] == (byte)0x9);
         Assert.assertTrue(targetProtocolAddress[1] == (byte)0x9);
         Assert.assertTrue(targetProtocolAddress[2] == (byte)0x9);
-        Assert.assertTrue(targetProtocolAddress[3] == (byte)0xFE);      
+        Assert.assertTrue(targetProtocolAddress[3] == (byte)0xFE);
     }
 
     @Test
index 61f34aa63a479b0f6ac5d9b2457c1ae226efb21a..21377be8538ffe2e0594438df2c8e0afdb1418a3 100644 (file)
@@ -22,38 +22,38 @@ import org.opendaylight.controller.sal.reader.FlowOnNode;
 import org.opendaylight.controller.sal.utils.EtherTypes;
 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
 import org.opendaylight.controller.sal.utils.NodeCreator;
-       
+
 public class FlowOnNodeTest {
 
-               @Test
-               public void testFlowOnNodeMethods () {
-               Match match = new Match();
-               NodeConnector inNC = NodeConnectorCreator.createNodeConnector((short)10, NodeCreator.createOFNode((long)10));
-               NodeConnector outNC = NodeConnectorCreator.createNodeConnector((short)20, NodeCreator.createOFNode((long)20));
-                       
-               match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
-               match.setField(MatchType.IN_PORT, inNC);
-                       
-               Output output = new Output(outNC);
-               ArrayList<Action> action = new ArrayList<Action>();
-               action.add(output);
-                       
-               Flow flow = new Flow (match, action);
-               
-               FlowOnNode flowOnNode = new FlowOnNode (flow);
-       
-               Assert.assertTrue(flowOnNode.getFlow().equals(flow));
-               
-               flowOnNode.setPacketCount((long)100);
-               flowOnNode.setByteCount((long)800);
-               flowOnNode.setTableId((byte)0x55);
-               flowOnNode.setDurationNanoseconds(40);
-               flowOnNode.setDurationSeconds(45);
-                       
-               Assert.assertTrue(flowOnNode.getPacketCount() == 100);
-               Assert.assertTrue(flowOnNode.getByteCount() == 800);
-               Assert.assertTrue(flowOnNode.getDurationNanoseconds() == 40);
-               Assert.assertTrue(flowOnNode.getDurationSeconds() == 45);
-               Assert.assertTrue(flowOnNode.getTableId() == (byte)0x55);               
-       }
+                @Test
+                public void testFlowOnNodeMethods () {
+                Match match = new Match();
+                NodeConnector inNC = NodeConnectorCreator.createNodeConnector((short)10, NodeCreator.createOFNode((long)10));
+                NodeConnector outNC = NodeConnectorCreator.createNodeConnector((short)20, NodeCreator.createOFNode((long)20));
+
+                match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
+                match.setField(MatchType.IN_PORT, inNC);
+
+                Output output = new Output(outNC);
+                ArrayList<Action> action = new ArrayList<Action>();
+                action.add(output);
+
+                Flow flow = new Flow (match, action);
+
+                FlowOnNode flowOnNode = new FlowOnNode (flow);
+
+                Assert.assertTrue(flowOnNode.getFlow().equals(flow));
+
+                flowOnNode.setPacketCount((long)100);
+                flowOnNode.setByteCount((long)800);
+                flowOnNode.setTableId((byte)0x55);
+                flowOnNode.setDurationNanoseconds(40);
+                flowOnNode.setDurationSeconds(45);
+
+                Assert.assertTrue(flowOnNode.getPacketCount() == 100);
+                Assert.assertTrue(flowOnNode.getByteCount() == 800);
+                Assert.assertTrue(flowOnNode.getDurationNanoseconds() == 40);
+                Assert.assertTrue(flowOnNode.getDurationSeconds() == 45);
+                Assert.assertTrue(flowOnNode.getTableId() == (byte)0x55);
+        }
 }
\ No newline at end of file
index 8c2d2e6e34cfa755ca1d6e91e15fce705c3784d2..c123e4e7c7f444e1e0e7cabfeef862a442b6d71c 100644 (file)
@@ -18,35 +18,34 @@ import org.junit.Assert;
 
 public class NodeConnectorStatisticsTest {
 
-       @Test
-       public void testNodeConnectorStatisticsMethods() {
-               NodeConnector nc = NodeConnectorCreator.createNodeConnector((short)20, NodeCreator.createOFNode((long)20));
-               NodeConnectorStatistics ncStats = new NodeConnectorStatistics();
-               ncStats.setNodeConnector(nc);
-               ncStats.setReceiveByteCount(800);
-               ncStats.setReceiveCRCErrorCount(10);
-               ncStats.setReceiveDropCount(5);
-               ncStats.setReceiveErrorCount(20);
-               ncStats.setReceiveFrameErrorCount(25);
-               ncStats.setReceiveOverRunErrorCount(30);
-               ncStats.setReceivePacketCount(100);
-               ncStats.setTransmitByteCount(400);
-               ncStats.setTransmitDropCount(15);
-               ncStats.setTransmitErrorCount(18);
-               ncStats.setTransmitPacketCount(50);
-               ncStats.setCollisionCount(2);
-               
-               Assert.assertTrue(ncStats.getCollisionCount() == 2);
-               Assert.assertTrue(ncStats.getTransmitPacketCount() == 50);
-               Assert.assertTrue(ncStats.getTransmitErrorCount() == 18);
-               Assert.assertTrue(ncStats.getTransmitDropCount() == 15);
-               Assert.assertTrue(ncStats.getReceivePacketCount() == 100);
-               Assert.assertTrue(ncStats.getReceiveOverRunErrorCount() == 30);
-               Assert.assertTrue(ncStats.getReceiveFrameErrorCount() == 25);
-               Assert.assertTrue(ncStats.getReceiveDropCount() == 5);
-               Assert.assertTrue(ncStats.getReceiveCRCErrorCount() == 10);
-               Assert.assertTrue(ncStats.getReceiveByteCount() == 800);
-               Assert.assertTrue(ncStats.getNodeConnector().equals(nc));
-       }
-}
+        @Test
+        public void testNodeConnectorStatisticsMethods() {
+                NodeConnector nc = NodeConnectorCreator.createNodeConnector((short)20, NodeCreator.createOFNode((long)20));
+                NodeConnectorStatistics ncStats = new NodeConnectorStatistics();
+                ncStats.setNodeConnector(nc);
+                ncStats.setReceiveByteCount(800);
+                ncStats.setReceiveCRCErrorCount(10);
+                ncStats.setReceiveDropCount(5);
+                ncStats.setReceiveErrorCount(20);
+                ncStats.setReceiveFrameErrorCount(25);
+                ncStats.setReceiveOverRunErrorCount(30);
+                ncStats.setReceivePacketCount(100);
+                ncStats.setTransmitByteCount(400);
+                ncStats.setTransmitDropCount(15);
+                ncStats.setTransmitErrorCount(18);
+                ncStats.setTransmitPacketCount(50);
+                ncStats.setCollisionCount(2);
 
+                Assert.assertTrue(ncStats.getCollisionCount() == 2);
+                Assert.assertTrue(ncStats.getTransmitPacketCount() == 50);
+                Assert.assertTrue(ncStats.getTransmitErrorCount() == 18);
+                Assert.assertTrue(ncStats.getTransmitDropCount() == 15);
+                Assert.assertTrue(ncStats.getReceivePacketCount() == 100);
+                Assert.assertTrue(ncStats.getReceiveOverRunErrorCount() == 30);
+                Assert.assertTrue(ncStats.getReceiveFrameErrorCount() == 25);
+                Assert.assertTrue(ncStats.getReceiveDropCount() == 5);
+                Assert.assertTrue(ncStats.getReceiveCRCErrorCount() == 10);
+                Assert.assertTrue(ncStats.getReceiveByteCount() == 800);
+                Assert.assertTrue(ncStats.getNodeConnector().equals(nc));
+        }
+}
index a720bdf680d16672e55b9269fa9fdb4ccacbdc5d..d4b1f8c25d2477d1fd5d9e741b376e744cec956c 100644 (file)
@@ -14,30 +14,27 @@ import org.junit.Test;
 import org.opendaylight.controller.sal.reader.NodeDescription;
 
 public class NodeDescriptionTest {
-       
-       @Test
-       public void testNodeDescriptionMethods() {
-               NodeDescription ncDesc = new NodeDescription();
-               ncDesc.setHardware("Hardware1");
-               ncDesc.setManufacturer("Manufacturer1");
-               ncDesc.setDescription("SDNProtocol1");
-               ncDesc.setSerialNumber("serialNumber1");
-               ncDesc.setSoftware("Software1");
-               
-               Assert.assertTrue(ncDesc.getHardware().equals("Hardware1"));
-               Assert.assertTrue(ncDesc.getManufacturer().equals("Manufacturer1"));
-               Assert.assertTrue(ncDesc.getDescription().equals("SDNProtocol1"));
-               Assert.assertTrue(ncDesc.getSerialNumber().equals("serialNumber1"));
-               Assert.assertTrue(ncDesc.getSoftware().equals("Software1"));
-               
-               Assert.assertFalse(ncDesc.getHardware().equals("Hardware2"));
-               Assert.assertFalse(ncDesc.getManufacturer().equals("Manufacturer2"));
-               Assert.assertFalse(ncDesc.getDescription().equals("SDNProtocol2"));
-               Assert.assertFalse(ncDesc.getSerialNumber().equals("serialNumber2"));
-               Assert.assertFalse(ncDesc.getSoftware().equals("Software2"));
-
-       }
-}
-
-
 
+        @Test
+        public void testNodeDescriptionMethods() {
+                NodeDescription ncDesc = new NodeDescription();
+                ncDesc.setHardware("Hardware1");
+                ncDesc.setManufacturer("Manufacturer1");
+                ncDesc.setDescription("SDNProtocol1");
+                ncDesc.setSerialNumber("serialNumber1");
+                ncDesc.setSoftware("Software1");
+
+                Assert.assertTrue(ncDesc.getHardware().equals("Hardware1"));
+                Assert.assertTrue(ncDesc.getManufacturer().equals("Manufacturer1"));
+                Assert.assertTrue(ncDesc.getDescription().equals("SDNProtocol1"));
+                Assert.assertTrue(ncDesc.getSerialNumber().equals("serialNumber1"));
+                Assert.assertTrue(ncDesc.getSoftware().equals("Software1"));
+
+                Assert.assertFalse(ncDesc.getHardware().equals("Hardware2"));
+                Assert.assertFalse(ncDesc.getManufacturer().equals("Manufacturer2"));
+                Assert.assertFalse(ncDesc.getDescription().equals("SDNProtocol2"));
+                Assert.assertFalse(ncDesc.getSerialNumber().equals("serialNumber2"));
+                Assert.assertFalse(ncDesc.getSoftware().equals("Software2"));
+
+        }
+}
index 117da55de89c4d74844a8ed7d80e17e61276eff6..5beb8713f9e91eb400e75ec7fa685ec51be870f8 100644 (file)
@@ -12,63 +12,60 @@ package org.opendaylight.controller.sal.utils;
 import java.util.ArrayList;
 import org.junit.Assert;
 import org.junit.Test;
-       
+
 public class EtherTypesTest {
-               
-       @Test
-       public void testEthertypesCreation() {
-               
-               EtherTypes arp = EtherTypes.ARP;
-               
-               Assert.assertTrue(arp.toString().equals("ARP"));
-               Assert.assertTrue(arp.intValue() == 2054);
-               Assert.assertTrue(arp.shortValue() == (short)2054);
-       }
-       
-       @Test
-       public void testGetEtherTypesString() {
-               
-               Assert.assertTrue(EtherTypes.getEtherTypeName(34984).equals("QINQ"));
-               Assert.assertTrue(EtherTypes.getEtherTypeName((short)2048).equals("IPv4"));
-               Assert.assertTrue(EtherTypes.getEtherTypeName(0x010B).equals("PVSTP"));
-               
-               Assert.assertFalse(EtherTypes.getEtherTypeName(0x800).equals("ARP"));
-       }
-       
-       @Test
-       public void testGetEtherTypesNumber() {
-               Assert.assertTrue(EtherTypes.getEtherTypeNumberInt("VLAN Tagged") == 33024);
-               Assert.assertTrue(EtherTypes.getEtherTypeNumberShort("ARP") == 2054);
-               
-               Assert.assertFalse(EtherTypes.getEtherTypeNumberInt("CDP") == 1000);
-       }
-       
-       @Test
-       public void testGetEtherTypesList() {
-               ArrayList<String> etherTypeNames = (ArrayList<String>) EtherTypes.getEtherTypesNameList();
-               Assert.assertTrue(etherTypeNames.get(0).equals("PVSTP"));
-               Assert.assertTrue(etherTypeNames.get(1).equals("CDP"));
-               Assert.assertTrue(etherTypeNames.get(2).equals("VTP"));
-               Assert.assertTrue(etherTypeNames.get(3).equals("IPv4"));
-               Assert.assertTrue(etherTypeNames.get(4).equals("ARP"));
-               Assert.assertTrue(etherTypeNames.get(5).equals("Reverse ARP"));
-               Assert.assertTrue(etherTypeNames.get(6).equals("VLAN Tagged"));
-               Assert.assertTrue(etherTypeNames.get(7).equals("IPv6"));
-               Assert.assertTrue(etherTypeNames.get(8).equals("MPLS Unicast"));
-               Assert.assertTrue(etherTypeNames.get(9).equals("MPLS Multicast"));
-               Assert.assertTrue(etherTypeNames.get(10).equals("QINQ"));
-               Assert.assertTrue(etherTypeNames.get(11).equals("LLDP"));
-               Assert.assertTrue(etherTypeNames.get(12).equals("Old QINQ"));
-               Assert.assertTrue(etherTypeNames.get(13).equals("Cisco QINQ"));         
-       }
-       
-       @Test
-       public void testGetEtherTypesloadFromString() {
-               Assert.assertTrue(EtherTypes.loadFromString("37376").equals(EtherTypes.CISCOQINQ));
-               Assert.assertTrue(EtherTypes.loadFromString("100") == null);
-       }
 
-}
+        @Test
+        public void testEthertypesCreation() {
+
+                EtherTypes arp = EtherTypes.ARP;
+
+                Assert.assertTrue(arp.toString().equals("ARP"));
+                Assert.assertTrue(arp.intValue() == 2054);
+                Assert.assertTrue(arp.shortValue() == (short)2054);
+        }
+
+        @Test
+        public void testGetEtherTypesString() {
 
+                Assert.assertTrue(EtherTypes.getEtherTypeName(34984).equals("QINQ"));
+                Assert.assertTrue(EtherTypes.getEtherTypeName((short)2048).equals("IPv4"));
+                Assert.assertTrue(EtherTypes.getEtherTypeName(0x010B).equals("PVSTP"));
 
+                Assert.assertFalse(EtherTypes.getEtherTypeName(0x800).equals("ARP"));
+        }
 
+        @Test
+        public void testGetEtherTypesNumber() {
+                Assert.assertTrue(EtherTypes.getEtherTypeNumberInt("VLAN Tagged") == 33024);
+                Assert.assertTrue(EtherTypes.getEtherTypeNumberShort("ARP") == 2054);
+
+                Assert.assertFalse(EtherTypes.getEtherTypeNumberInt("CDP") == 1000);
+        }
+
+        @Test
+        public void testGetEtherTypesList() {
+                ArrayList<String> etherTypeNames = (ArrayList<String>) EtherTypes.getEtherTypesNameList();
+                Assert.assertTrue(etherTypeNames.get(0).equals("PVSTP"));
+                Assert.assertTrue(etherTypeNames.get(1).equals("CDP"));
+                Assert.assertTrue(etherTypeNames.get(2).equals("VTP"));
+                Assert.assertTrue(etherTypeNames.get(3).equals("IPv4"));
+                Assert.assertTrue(etherTypeNames.get(4).equals("ARP"));
+                Assert.assertTrue(etherTypeNames.get(5).equals("Reverse ARP"));
+                Assert.assertTrue(etherTypeNames.get(6).equals("VLAN Tagged"));
+                Assert.assertTrue(etherTypeNames.get(7).equals("IPv6"));
+                Assert.assertTrue(etherTypeNames.get(8).equals("MPLS Unicast"));
+                Assert.assertTrue(etherTypeNames.get(9).equals("MPLS Multicast"));
+                Assert.assertTrue(etherTypeNames.get(10).equals("QINQ"));
+                Assert.assertTrue(etherTypeNames.get(11).equals("LLDP"));
+                Assert.assertTrue(etherTypeNames.get(12).equals("Old QINQ"));
+                Assert.assertTrue(etherTypeNames.get(13).equals("Cisco QINQ"));
+        }
+
+        @Test
+        public void testGetEtherTypesloadFromString() {
+                Assert.assertTrue(EtherTypes.loadFromString("37376").equals(EtherTypes.CISCOQINQ));
+                Assert.assertTrue(EtherTypes.loadFromString("100") == null);
+        }
+
+}
index b9b5f459274bd63c8ed804237a97749f36a7cf39..3cfa747be5c5288b5008d7e5a32419d7af08ce08 100644 (file)
@@ -8,63 +8,60 @@
  */
 
 package org.opendaylight.controller.sal.utils;
-               
+
 import org.junit.Assert;
 import org.junit.Test;
-       
+
 public class HexEncodeTest {
-               
-       @Test
-       public void testbytesToHexString() {
-               byte[] bytes1 = {(byte)0x01, (byte)0x02, (byte)0x03};           
-               String str1 = HexEncode.bytesToHexString(bytes1);
-               Assert.assertTrue(str1.equals("010203"));
-       
-               byte[] bytes2 = {(byte)0x11, (byte)0x22, (byte)0x33};           
-               String str2 = HexEncode.bytesToHexString(bytes2);
-               Assert.assertFalse(str2.equals("010203"));
-
-       }
-
-       @Test
-       public void testLongToHexString() {
-               long value1 = 12345678L;
-               String str1 = HexEncode.longToHexString(value1);
-               Assert.assertTrue(str1.equals("00:00:00:00:00:bc:61:4e"));
-               
-               long value2 = 98765432L;
-               String str2 = HexEncode.longToHexString(value2);
-               Assert.assertFalse(str2.equals("00:44:33:22:11:bc:61:4e"));
-
-       }
-       
-       @Test
-       public void testBytesFromHexString() {
-               String byteStr1 = "00:11:22:33:44:55";
-               byte byteArray1[] = new byte[(byteStr1.length() + 1)/3];
-               byteArray1 = HexEncode.bytesFromHexString(byteStr1);
-               
-               Assert.assertTrue(byteArray1[0] == (byte)0x0);
-               Assert.assertTrue(byteArray1[1] == (byte)0x11);
-               Assert.assertTrue(byteArray1[2] == (byte)0x22);
-               Assert.assertTrue(byteArray1[3] == (byte)0x33);
-               Assert.assertTrue(byteArray1[4] == (byte)0x44);
-               Assert.assertTrue(byteArray1[5] == (byte)0x55);
-               
-               String byteStr2 = "00:11:22:33:44:55";
-               byte byteArray2[] = new byte[(byteStr2.length() + 1)/3];
-               byteArray2 = HexEncode.bytesFromHexString(byteStr2);
-               
-               Assert.assertFalse(byteArray2[0] == (byte)0x55);
-               Assert.assertFalse(byteArray2[1] == (byte)0x44);
-               Assert.assertFalse(byteArray2[2] == (byte)0x33);
-               Assert.assertFalse(byteArray2[3] == (byte)0x22);
-               Assert.assertFalse(byteArray2[4] == (byte)0x11);
-               Assert.assertFalse(byteArray2[5] == (byte)0x0);
-
-       }
-                       
-}
 
+        @Test
+        public void testbytesToHexString() {
+                byte[] bytes1 = {(byte)0x01, (byte)0x02, (byte)0x03};
+                String str1 = HexEncode.bytesToHexString(bytes1);
+                Assert.assertTrue(str1.equals("010203"));
+
+                byte[] bytes2 = {(byte)0x11, (byte)0x22, (byte)0x33};
+                String str2 = HexEncode.bytesToHexString(bytes2);
+                Assert.assertFalse(str2.equals("010203"));
+
+        }
+
+        @Test
+        public void testLongToHexString() {
+                long value1 = 12345678L;
+                String str1 = HexEncode.longToHexString(value1);
+                Assert.assertTrue(str1.equals("00:00:00:00:00:bc:61:4e"));
+
+                long value2 = 98765432L;
+                String str2 = HexEncode.longToHexString(value2);
+                Assert.assertFalse(str2.equals("00:44:33:22:11:bc:61:4e"));
 
+        }
 
+        @Test
+        public void testBytesFromHexString() {
+                String byteStr1 = "00:11:22:33:44:55";
+                byte byteArray1[] = new byte[(byteStr1.length() + 1)/3];
+                byteArray1 = HexEncode.bytesFromHexString(byteStr1);
+
+                Assert.assertTrue(byteArray1[0] == (byte)0x0);
+                Assert.assertTrue(byteArray1[1] == (byte)0x11);
+                Assert.assertTrue(byteArray1[2] == (byte)0x22);
+                Assert.assertTrue(byteArray1[3] == (byte)0x33);
+                Assert.assertTrue(byteArray1[4] == (byte)0x44);
+                Assert.assertTrue(byteArray1[5] == (byte)0x55);
+
+                String byteStr2 = "00:11:22:33:44:55";
+                byte byteArray2[] = new byte[(byteStr2.length() + 1)/3];
+                byteArray2 = HexEncode.bytesFromHexString(byteStr2);
+
+                Assert.assertFalse(byteArray2[0] == (byte)0x55);
+                Assert.assertFalse(byteArray2[1] == (byte)0x44);
+                Assert.assertFalse(byteArray2[2] == (byte)0x33);
+                Assert.assertFalse(byteArray2[3] == (byte)0x22);
+                Assert.assertFalse(byteArray2[4] == (byte)0x11);
+                Assert.assertFalse(byteArray2[5] == (byte)0x0);
+
+        }
+
+}
index 99690802e3cdd5e9539c8e0a5c33a18ccec7b3d6..41e4d2a7fcb30247bdb9a95c5f8c014bfd69389a 100644 (file)
@@ -38,7 +38,7 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function called when the activator starts just after some initializations
      * are done by the ComponentActivatorAbstractBase.
-     * 
+     *
      */
     public void init() {
 
@@ -47,7 +47,7 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function called when the activator stops just before the cleanup done by
      * ComponentActivatorAbstractBase
-     * 
+     *
      */
     public void destroy() {
 
@@ -56,8 +56,8 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function that is used to communicate to dependency manager the list of
      * known implementations for services inside a container
-     * 
-     * 
+     *
+     *
      * @return An array containing all the CLASS objects that will be
      *         instantiated in order to get an fully working implementation
      *         Object
@@ -72,7 +72,7 @@ public class Activator extends ComponentActivatorAbstractBase {
     /**
      * Function that is called when configuration of the dependencies is
      * required.
-     * 
+     *
      * @param c
      *            dependency manager Component object, used for configuring the
      *            dependencies exported and imported
index 29d1c71204a68bde4edb0d66936b121590551ac2..a9eefd3a8a689d8b4d92bd76fc4ec0edf1198193 100644 (file)
@@ -46,7 +46,6 @@ import org.slf4j.LoggerFactory;
 
 public class DataPacketService implements IPluginOutDataPacketService,
         IDataPacketService {
-    private int RXMAXQUEUESIZE = 1000;
     private int TXMAXQUEUESIZE = 1000;
     protected static final Logger logger = LoggerFactory
             .getLogger(DataPacketService.class);
@@ -63,31 +62,21 @@ public class DataPacketService implements IPluginOutDataPacketService,
         pluginInDataService =
         new ConcurrentHashMap<String, IPluginInDataPacketService>();
     private Map<String, AtomicInteger> statistics = new HashMap<String, AtomicInteger>();
-    /**
-     * Queue for packets received from Data Path
-     */
-    private LinkedBlockingQueue<RawPacket> rxQueue = new LinkedBlockingQueue<RawPacket>(
-            RXMAXQUEUESIZE);
+
     /**
      * Queue for packets that need to be transmitted to Data Path
      */
     private LinkedBlockingQueue<RawPacket> txQueue = new LinkedBlockingQueue<RawPacket>(
-            RXMAXQUEUESIZE);
+            TXMAXQUEUESIZE);
     /**
      * Transmission thread
      */
     private Thread txThread = new Thread(new TxLoop(),
             "DataPacketService TX thread");
-    /**
-     * Receiving thread
-     */
-    private Thread rxThread = new Thread(new RxLoop(),
-            "DataPacketService RX thread");
 
     /**
      * Representation of a Data Packet Listener including of its
      * properties
-     *
      */
     private class DataPacketListener {
         // Key fields
@@ -152,49 +141,30 @@ public class DataPacketService implements IPluginOutDataPacketService,
 
     /**
      * Loop for processing Received packets
-     *
      */
-    private class RxLoop implements Runnable {
-        public void run() {
-            RawPacket pkt;
-            try {
-                for (pkt = rxQueue.take(); pkt != null; pkt = rxQueue.take()) {
-                    for (List<DataPacketListener> serialListeners : listenDataPacket) {
-                        int i = 0;
-                        for (i = 0; i < serialListeners.size(); i++) {
-                            RawPacket copyPkt = null;
-                            try {
-                                copyPkt = new RawPacket(pkt);
-                            } catch (ConstructionException cex) {
-                                logger.debug("Error while cloning the packet");
-                            }
-                            if (copyPkt == null) {
-                                increaseStat("RXPacketCopyFailed");
-                                continue;
-                            }
-                            DataPacketListener l = serialListeners.get(i);
-                            IListenDataPacket s = (l == null ? null
-                                    : l.listener);
-                            if (s != null) {
-                                try {
-                                    // TODO Make sure to filter based
-                                    // on the match too, later on
-                                    PacketResult res = s
-                                            .receiveDataPacket(copyPkt);
-                                    increaseStat("RXPacketSuccess");
-                                    if (res.equals(PacketResult.CONSUME)) {
-                                        increaseStat("RXPacketSerialExit");
-                                        break;
-                                    }
-                                } catch (Exception e) {
-                                    increaseStat("RXPacketFailedForException");
-                                }
-                            }
+    private void dispatchPacket(RawPacket pkt) {
+
+        // for now we treat all listeners as serial listeners
+        for (List<DataPacketListener> serialListeners : listenDataPacket) {
+            for (DataPacketListener l : serialListeners) {
+
+                // TODO: possibly deal with read-only and read-write packet
+                // copies
+                IListenDataPacket s = (l == null ? null : l.listener);
+                if (s != null) {
+                    try {
+                        // TODO Make sure to filter based on the match too,
+                        // later on
+                        PacketResult res = s.receiveDataPacket(pkt);
+                        increaseStat("RXPacketSuccess");
+                        if (res.equals(PacketResult.CONSUME)) {
+                            increaseStat("RXPacketSerialExit");
+                            break;
                         }
+                    } catch (Exception e) {
+                        increaseStat("RXPacketFailedForException");
                     }
                 }
-            } catch (InterruptedException e) {
-                // Not a big deal
             }
         }
     }
@@ -431,7 +401,6 @@ public class DataPacketService implements IPluginOutDataPacketService,
      */
     void init() {
         this.txThread.start();
-        this.rxThread.start();
     }
 
     /**
@@ -447,14 +416,11 @@ public class DataPacketService implements IPluginOutDataPacketService,
         this.indexDataPacket.clear();
         this.pluginInDataService.clear();
         this.statistics.clear();
-        this.rxQueue.clear();
         this.txQueue.clear();
         this.txThread.interrupt();
-        this.rxThread.interrupt();
         // Wait for them to be done
         try {
             this.txThread.join();
-            this.rxThread.join();
         } catch (InterruptedException ex) {
             // Not a big deal
         }
@@ -484,12 +450,8 @@ public class DataPacketService implements IPluginOutDataPacketService,
             return PacketResult.IGNORED;
         }
 
-        // If the queue was full don't wait, rather increase a counter
-        // for it
-        if (!this.rxQueue.offer(inPkt)) {
-            increaseStat("fullRXQueue");
-            return PacketResult.IGNORED;
-        }
+        // send the packet off to be processed by listeners
+        this.dispatchPacket(inPkt);
 
         // Walk the chain of listener going first throw all the
         // parallel ones and for each parallel in serial
index 6bea30666925ddaf4991f819597fde625766026f..d6feebd4a3067a057af0a7991dcf82613f2f5995 100644 (file)
@@ -75,7 +75,7 @@ public class FlowProgrammerService implements IFlowProgrammerService,
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
-     * 
+     *
      */
     void init() {
         logger.debug("INIT called!");
@@ -85,7 +85,7 @@ public class FlowProgrammerService implements IFlowProgrammerService,
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
         // Clear previous registration to avoid they are left hanging
@@ -96,7 +96,7 @@ public class FlowProgrammerService implements IFlowProgrammerService,
     /**
      * Function called by dependency manager after "init ()" is called and after
      * the services provided by the class are registered in the service registry
-     * 
+     *
      */
     void start() {
         logger.debug("START called!");
@@ -108,7 +108,7 @@ public class FlowProgrammerService implements IFlowProgrammerService,
      * Function called by the dependency manager before the services exported by
      * the component are unregistered, this will be followed by a "destroy ()"
      * calls
-     * 
+     *
      */
     void stop() {
         logger.debug("STOP called!");
@@ -305,7 +305,7 @@ public class FlowProgrammerService implements IFlowProgrammerService,
         }
         ci.println(this.addFlow(node, getSampleFlow(node)));
     }
-    
+
     public void _modifyflow(CommandInterpreter ci) throws UnknownHostException {
         Node node = null;
         String nodeId = ci.nextArgument();
@@ -494,7 +494,7 @@ public class FlowProgrammerService implements IFlowProgrammerService,
     /**
      * This Request ID generator starts with 1. Each aysnc message is
      * associated with an unique Request ID (!= 0).
-     * 
+     *
      * @return Request ID
      */
     private long getNextRid() {
index f965d7f2c402e21d6cf920f15ad0413ef7bd6785..2f517488a955ccbd7af16f05249114d9aa8e19fb 100644 (file)
@@ -60,7 +60,7 @@ public class Topology implements IPluginOutTopologyService, ITopologyService {
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
-     * 
+     *
      */
     void init() {
     }
@@ -69,7 +69,7 @@ public class Topology implements IPluginOutTopologyService, ITopologyService {
      * Function called by the dependency manager when at least one dependency
      * become unsatisfied or when the component is shutting down because for
      * example bundle is being stopped.
-     * 
+     *
      */
     void destroy() {
         // Make sure to clear all the data structure we use to track
index 730764a24e5bfc688008d980c02b3038c5b951e4..3a07288a9f9d9473c4dc8bba02410e4c81dd2238 100644 (file)
@@ -20,14 +20,14 @@ import org.opendaylight.controller.sal.packet.RawPacket;
 
 public class DataPacketServiceTest {
 
-       @Test
-       public void DataPacketServiceDecodeTest() throws ConstructionException, InstantiationException, IllegalAccessException {
-               
-               DataPacketService dService = new DataPacketService();
-               RawPacket rawPkt = null;
-               
-               Assert.assertTrue(dService.decodeDataPacket(rawPkt) == null);
-               
+        @Test
+        public void DataPacketServiceDecodeTest() throws ConstructionException, InstantiationException, IllegalAccessException {
+
+                DataPacketService dService = new DataPacketService();
+                RawPacket rawPkt = null;
+
+                Assert.assertTrue(dService.decodeDataPacket(rawPkt) == null);
+
         byte[] data = { 10, 12, 14, 20, 55, 69, //DMAC
                 -90, -20, -100, -82, -78, -97, //SMAC
                 8, 6, //ethype
@@ -40,35 +40,35 @@ public class DataPacketServiceTest {
                 9, 9, 9, 1, // src proto
                 0, 0, 0, 0, 0, 0, // target hw addr
                 9, 9, 9, -2 }; // target proto
-        
+
         rawPkt = new RawPacket(data);
-        
+
         Packet decodedPkt = dService.decodeDataPacket(rawPkt);
         Class<? extends Packet> payloadClass = ARP.class;
         Assert.assertTrue(payloadClass == decodedPkt.getPayload().getClass());
-                
+
         ARP arpPacket = (ARP) decodedPkt.getPayload();
-        
+
         Assert.assertTrue(arpPacket.getHardwareType() == (byte)0x1);
         Assert.assertTrue(arpPacket.getProtocolType() == 2048);
         Assert.assertTrue(arpPacket.getHardwareAddressLength() == (byte)0x6);
         Assert.assertTrue(arpPacket.getProtocolAddressLength() == (byte)0x4);
         Assert.assertTrue(arpPacket.getOpCode() == 1);
-        
+
         byte[] senderHwAddress = arpPacket.getSenderHardwareAddress();
-        byte[] senderProtocolAddress = arpPacket.getSenderProtocolAddress(); 
-        
+        byte[] senderProtocolAddress = arpPacket.getSenderProtocolAddress();
+
         byte[] targetHwAddress = arpPacket.getTargetHardwareAddress();
-        byte[] targetProtocolAddress = arpPacket.getTargetProtocolAddress(); 
+        byte[] targetProtocolAddress = arpPacket.getTargetProtocolAddress();
+
 
-        
         Assert.assertTrue(senderHwAddress[0] == (byte)0xA6);
         Assert.assertTrue(senderHwAddress[1] == (byte)0xEC);
         Assert.assertTrue(senderHwAddress[2] == (byte)0x9C);
         Assert.assertTrue(senderHwAddress[3] == (byte)0xAE);
         Assert.assertTrue(senderHwAddress[4] == (byte)0xB2);
         Assert.assertTrue(senderHwAddress[5] == (byte)0x9F);
-        
+
         Assert.assertTrue(senderProtocolAddress[0] == (byte)0x9);
         Assert.assertTrue(senderProtocolAddress[1] == (byte)0x9);
         Assert.assertTrue(senderProtocolAddress[2] == (byte)0x9);
@@ -89,36 +89,36 @@ public class DataPacketServiceTest {
         Assert.assertTrue(targetProtocolAddress[0] == (byte)0x9);
         Assert.assertTrue(targetProtocolAddress[1] == (byte)0x9);
         Assert.assertTrue(targetProtocolAddress[2] == (byte)0x9);
-        Assert.assertTrue(targetProtocolAddress[3] == (byte)0xFE);      
-       }
-       
-       @Test
-       public void DataPacketServiceEncodeTest() throws ConstructionException, InstantiationException, IllegalAccessException {
-               
-               DataPacketService dService = new DataPacketService();
-               Ethernet eth = new Ethernet();
+        Assert.assertTrue(targetProtocolAddress[3] == (byte)0xFE);
+        }
+
+        @Test
+        public void DataPacketServiceEncodeTest() throws ConstructionException, InstantiationException, IllegalAccessException {
+
+                DataPacketService dService = new DataPacketService();
+                Ethernet eth = new Ethernet();
         ARP arp = new ARP();
 
-               byte[] data = null;
-               RawPacket rawPkt;
+                byte[] data = null;
+                RawPacket rawPkt;
 
 
         byte[] dMAC = { 10, 12, 14, 20, 55, 69 };
         byte[] sMAC = { 82, 97, 109, 117, 127, -50 };
         short etherType = 2054;
-        
+
         eth.setDestinationMACAddress(dMAC);
         eth.setSourceMACAddress(sMAC);
         eth.setEtherType(etherType);
-               
+
         arp.setHardwareType((short)1);
         arp.setProtocolType((short)2048);
         arp.setHardwareAddressLength((byte)0x6);
         arp.setProtocolAddressLength((byte)0x4);
         arp.setOpCode((byte)0x1);
-        
+
         byte[] senderHardwareAddress = {(byte)0xA6, (byte)0xEC, (byte)0x9C, (byte)0xAE,
-                                                                       (byte)0xB2, (byte)0x9F};
+                                                                        (byte)0xB2, (byte)0x9F};
         byte[] senderProtocolAddress = {(byte)0x09, (byte)0x09, (byte)0x09, (byte)0x01};
         byte[] targetProtocolAddress = {(byte)0x09, (byte)0x09, (byte)0x09, (byte)0xFE};
         byte[] targetHardwareAddress = {(byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0};
@@ -126,13 +126,13 @@ public class DataPacketServiceTest {
         arp.setSenderProtocolAddress(senderProtocolAddress);
         arp.setTargetHardwareAddress(targetHardwareAddress);
         arp.setTargetProtocolAddress(targetProtocolAddress);
-                
+
         arp.setParent(eth);
         eth.setPayload(arp);
-        
+
         rawPkt = dService.encodeDataPacket(eth);
         data = rawPkt.getPacketData();
-        
+
         Assert.assertTrue(data[0] == (byte)0x0A);//Destination MAC
         Assert.assertTrue(data[1] == (byte)0x0C);
         Assert.assertTrue(data[2] == (byte)0x0E);
@@ -174,7 +174,7 @@ public class DataPacketServiceTest {
         Assert.assertTrue(data[38] == (byte)0x09);//Target Protocol Address
         Assert.assertTrue(data[39] == (byte)0x09);
         Assert.assertTrue(data[40] == (byte)0x09);
-        Assert.assertTrue(data[41] == (byte)0xFE);    
-       }
+        Assert.assertTrue(data[41] == (byte)0xFE);
+        }
 
 }
index bed7989074c7da7cff666b55d4afbb54f620e910..a9859f76304a6c4953bf7e17adb4619f5164ece8 100644 (file)
@@ -7,13 +7,47 @@
  */\r
 package org.opendaylight.controller.sal.binding.generator.api;\r
 \r
-import java.util.List;\r
-\r
 import org.opendaylight.controller.sal.binding.model.api.Type;\r
+import org.opendaylight.controller.yang.model.api.Module;\r
 import org.opendaylight.controller.yang.model.api.SchemaContext;\r
 \r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+/**\r
+ *\r
+ *\r
+ */\r
 public interface BindingGenerator {\r
 \r
+    /**\r
+     * Generate Types from whole Schema Context.\r
+     * <br>\r
+     * The method will return List of All Generated Types that could be\r
+     * Generated from Schema Context.\r
+     *\r
+     *\r
+     * @param context Schema Context\r
+     * @return List of Generated Types\r
+     *\r
+     * @see SchemaContext\r
+     */\r
     public List<Type> generateTypes(final SchemaContext context);\r
 \r
+    /**\r
+     * Generate Types from Schema Context restricted by sub set of specified\r
+     * Modules. The Schema Context MUST contain all of the sub modules\r
+     * otherwise the there is no guarantee that result List of Generated\r
+     * Types will contain correct Generated Types.\r
+     *\r
+     * @param context Schema Context\r
+     * @param modules Sub Set of Modules\r
+     * @return List of Generated Types restricted by sub set of Modules\r
+     *\r
+     * @see Module\r
+     * @see SchemaContext\r
+     *\r
+     */\r
+    public List<Type> generateTypes(final SchemaContext context,\r
+                                    final Set<Module> modules);\r
 }\r
index a903ef15811daeb7197c4ef7a80ca612c30520e4..b89dbb44ac786756b60d866c02459097bbe615b4 100644 (file)
@@ -9,28 +9,31 @@ package org.opendaylight.controller.sal.binding.generator.impl;
 
 import org.opendaylight.controller.binding.generator.util.ReferencedTypeImpl;
 import org.opendaylight.controller.binding.generator.util.Types;
+import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
 import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
 import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
 import org.opendaylight.controller.sal.binding.generator.spi.TypeProvider;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
-import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.*;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
 import org.opendaylight.controller.sal.binding.yang.types.TypeProviderImpl;
+import org.opendaylight.controller.yang.binding.Notification;
 import org.opendaylight.controller.yang.common.QName;
+import org.opendaylight.controller.yang.common.RpcResult;
 import org.opendaylight.controller.yang.model.api.*;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
 import org.opendaylight.controller.yang.model.util.DataNodeIterator;
 import org.opendaylight.controller.yang.model.util.ExtendedType;
+import org.opendaylight.controller.yang.model.util.SchemaContextUtil;
 
 import java.util.*;
+import java.util.concurrent.Future;
 
 import static org.opendaylight.controller.binding.generator.util.BindingGeneratorUtil.*;
 import static org.opendaylight.controller.yang.model.util.SchemaContextUtil.findDataSchemaNode;
 import static org.opendaylight.controller.yang.model.util.SchemaContextUtil.findParentModule;
 
-public class BindingGeneratorImpl implements BindingGenerator {
+public final class BindingGeneratorImpl implements BindingGenerator {
 
     private Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders;
     private TypeProvider typeProvider;
@@ -43,94 +46,206 @@ public class BindingGeneratorImpl implements BindingGenerator {
     @Override
     public List<Type> generateTypes(final SchemaContext context) {
         if (context == null) {
-            throw new IllegalArgumentException("Schema Context reference cannot be NULL");
+            throw new IllegalArgumentException("Schema Context reference "
+                    + "cannot be NULL!");
         }
         if (context.getModules() == null) {
-            throw new IllegalStateException("Schema Context does not contain defined modules!");
+            throw new IllegalStateException("Schema Context does not contain "
+                    + "defined modules!");
         }
 
-        final List<Type> genTypes = new ArrayList<>();
+        final List<Type> generatedTypes = new ArrayList<>();
         schemaContext = context;
         typeProvider = new TypeProviderImpl(context);
         final Set<Module> modules = context.getModules();
         genTypeBuilders = new HashMap<>();
         for (final Module module : modules) {
-            final DataNodeIterator moduleIterator = new DataNodeIterator(
-                    module);
-
-            final List<AugmentationSchema> sortedAugmentations = provideSortedAugmentations(module);
-            final List<ContainerSchemaNode> schemaContainers = moduleIterator
-                    .allContainers();
-            final List<ListSchemaNode> schemaLists = moduleIterator
-                    .allLists();
-
-            final String basePackageName = moduleNamespaceToPackageName(module);
-            if ((schemaContainers != null)
-                    && !schemaContainers.isEmpty()) {
-                for (final ContainerSchemaNode container : schemaContainers) {
-                    genTypes.add(containerToGenType(basePackageName,
-                            container));
-                }
-            }
-            if ((schemaLists != null) && !schemaLists.isEmpty()) {
-                for (final ListSchemaNode list : schemaLists) {
-                    genTypes.addAll(listToGenType(basePackageName, list));
-                }
+            generatedTypes.add(moduleToDataType(module));
+            generatedTypes.addAll(allTypeDefinitionsToGenTypes(module));
+            generatedTypes.addAll(allContainersToGenTypes(module));
+            generatedTypes.addAll(allListsToGenTypes(module));
+            generatedTypes.addAll(allAugmentsToGenTypes(module));
+            generatedTypes.addAll(allRPCMethodsToGenType(module));
+            generatedTypes.addAll(allNotificationsToGenType(module));
+            generatedTypes.addAll(allIdentitiesToGenTypes(module, context));
+            generatedTypes.addAll(allGroupingsToGenTypes(module));
+        }
+        return generatedTypes;
+    }
+
+    @Override
+    public List<Type> generateTypes(final SchemaContext context,
+            final Set<Module> modules) {
+        if (context == null) {
+            throw new IllegalArgumentException("Schema Context reference "
+                    + "cannot be NULL!");
+        }
+        if (context.getModules() == null) {
+            throw new IllegalStateException("Schema Context does not contain "
+                    + "defined modules!");
+        }
+        if (modules == null) {
+            throw new IllegalArgumentException("Sef of Modules cannot be "
+                    + "NULL!");
+        }
+
+        final List<Type> filteredGenTypes = new ArrayList<>();
+        schemaContext = context;
+        typeProvider = new TypeProviderImpl(context);
+        final Set<Module> contextModules = context.getModules();
+        genTypeBuilders = new HashMap<>();
+        for (final Module contextModule : contextModules) {
+            final List<Type> generatedTypes = new ArrayList<>();
+
+            generatedTypes.add(moduleToDataType(contextModule));
+            generatedTypes.addAll(allTypeDefinitionsToGenTypes(contextModule));
+            generatedTypes.addAll(allContainersToGenTypes(contextModule));
+            generatedTypes.addAll(allListsToGenTypes(contextModule));
+            generatedTypes.addAll(allAugmentsToGenTypes(contextModule));
+            generatedTypes.addAll(allRPCMethodsToGenType(contextModule));
+            generatedTypes.addAll(allNotificationsToGenType(contextModule));
+            generatedTypes.addAll(allIdentitiesToGenTypes(contextModule,
+                    context));
+            generatedTypes.addAll(allGroupingsToGenTypes(contextModule));
+
+            if (modules.contains(contextModule)) {
+                filteredGenTypes.addAll(generatedTypes);
             }
+        }
+        return filteredGenTypes;
+    }
 
-            if ((sortedAugmentations != null)
-                    && !sortedAugmentations.isEmpty()) {
-                for (final AugmentationSchema augment : sortedAugmentations) {
-                    genTypes.addAll(augmentationToGenTypes(basePackageName, augment));
+    private List<Type> allTypeDefinitionsToGenTypes(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException(
+                    "Module reference cannot be NULL!");
+        }
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+        if (module.getTypeDefinitions() == null) {
+            throw new IllegalArgumentException("Type Definitions for module "
+                    + module.getName() + " cannot be NULL!");
+        }
+
+        final Set<TypeDefinition<?>> typeDefinitions = module
+                .getTypeDefinitions();
+        final List<Type> generatedTypes = new ArrayList<>();
+        for (final TypeDefinition<?> typedef : typeDefinitions) {
+            if (typedef != null) {
+                final Type type = ((TypeProviderImpl) typeProvider)
+                        .generatedTypeForExtendedDefinitionType(typedef);
+                if ((type != null) && !generatedTypes.contains(type)) {
+                    generatedTypes.add(type);
                 }
             }
+        }
+        return generatedTypes;
+    }
+
+    private List<Type> allContainersToGenTypes(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException(
+                    "Module reference cannot be NULL!");
+        }
 
-            final GeneratedType genDataType = moduleToDataType(basePackageName, module);
-            final List<GeneratedType> genRpcType = rpcMethodsToGenType(basePackageName, module);
-            final List<Type> genNotifyType = notifycationsToGenType(basePackageName, module);
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
 
-            if (genDataType != null) {
-                genTypes.add(genDataType);
-            }
-            if (genRpcType != null) {
-                genTypes.addAll(genRpcType);
-            }
-            if (genNotifyType != null) {
-                genTypes.addAll(genNotifyType);
+        if (module.getChildNodes() == null) {
+            throw new IllegalArgumentException("Reference to Set of Child "
+                    + "Nodes in module " + module.getName() + " cannot be "
+                    + "NULL!");
+        }
+
+        final List<Type> generatedTypes = new ArrayList<>();
+        final DataNodeIterator it = new DataNodeIterator(module);
+        final List<ContainerSchemaNode> schemaContainers = it.allContainers();
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        for (final ContainerSchemaNode container : schemaContainers) {
+            generatedTypes.add(containerToGenType(basePackageName, container));
+        }
+        return generatedTypes;
+    }
+
+    private List<Type> allListsToGenTypes(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException(
+                    "Module reference cannot be NULL!");
+        }
+
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+
+        if (module.getChildNodes() == null) {
+            throw new IllegalArgumentException("Reference to Set of Child "
+                    + "Nodes in module " + module.getName() + " cannot be "
+                    + "NULL!");
+        }
+
+        final List<Type> generatedTypes = new ArrayList<>();
+        final DataNodeIterator it = new DataNodeIterator(module);
+        final List<ListSchemaNode> schemaLists = it.allLists();
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        if (schemaLists != null) {
+            for (final ListSchemaNode list : schemaLists) {
+                generatedTypes.addAll(listToGenType(basePackageName, list));
             }
         }
-        genTypes.addAll(((TypeProviderImpl) typeProvider)
-                .getGeneratedTypeDefs());
+        return generatedTypes;
+    }
+
+    private List<Type> allAugmentsToGenTypes(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException(
+                    "Module reference cannot be NULL!");
+        }
 
-        return genTypes;
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+
+        if (module.getChildNodes() == null) {
+            throw new IllegalArgumentException("Reference to Set of "
+                    + "Augmentation Definitions in module " + module.getName()
+                    + " cannot be NULL!");
+        }
+
+        final List<Type> generatedTypes = new ArrayList<>();
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        final List<AugmentationSchema> augmentations = resolveAugmentations(module);
+        for (final AugmentationSchema augment : augmentations) {
+            generatedTypes.addAll(augmentationToGenTypes(basePackageName,
+                    augment));
+        }
+        return generatedTypes;
     }
 
-    private List<AugmentationSchema> provideSortedAugmentations(final Module module) {
+    private List<AugmentationSchema> resolveAugmentations(final Module module) {
         if (module == null) {
-            throw new IllegalArgumentException("Module reference cannot be NULL!");
+            throw new IllegalArgumentException(
+                    "Module reference cannot be NULL!");
         }
         if (module.getAugmentations() == null) {
             throw new IllegalStateException("Augmentations Set cannot be NULL!");
         }
 
-        final Set<AugmentationSchema> augmentations = module
-                .getAugmentations();
+        final Set<AugmentationSchema> augmentations = module.getAugmentations();
         final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(
                 augmentations);
         Collections.sort(sortedAugmentations,
                 new Comparator<AugmentationSchema>() {
 
                     @Override
-                    public int compare(
-                            AugmentationSchema augSchema1,
+                    public int compare(AugmentationSchema augSchema1,
                             AugmentationSchema augSchema2) {
 
-                        if (augSchema1.getTargetPath().getPath()
-                                .size() > augSchema2
+                        if (augSchema1.getTargetPath().getPath().size() > augSchema2
                                 .getTargetPath().getPath().size()) {
                             return 1;
-                        } else if (augSchema1.getTargetPath()
-                                .getPath().size() < augSchema2
+                        } else if (augSchema1.getTargetPath().getPath().size() < augSchema2
                                 .getTargetPath().getPath().size()) {
                             return -1;
                         }
@@ -142,32 +257,229 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return sortedAugmentations;
     }
 
-    private GeneratedType moduleToDataType(final String basePackageName, final Module module) {
+    private GeneratedType moduleToDataType(final Module module) {
         if (module == null) {
-            throw new IllegalArgumentException("Module reference cannot be NULL!");
+            throw new IllegalArgumentException(
+                    "Module reference cannot be NULL!");
         }
 
         final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(
                 module, "Data");
 
+        final String basePackageName = moduleNamespaceToPackageName(module);
         if (moduleDataTypeBuilder != null) {
             final Set<DataSchemaNode> dataNodes = module.getChildNodes();
-            resolveDataSchemaNodes(basePackageName, moduleDataTypeBuilder, dataNodes);
+            resolveDataSchemaNodes(basePackageName, moduleDataTypeBuilder,
+                    dataNodes);
         }
         return moduleDataTypeBuilder.toInstance();
     }
 
-    private boolean isDerivedFromEnumerationType(
-            final TypeDefinition<?> typeDefinition) {
-        if (typeDefinition != null) {
-            if (typeDefinition.getBaseType() instanceof EnumTypeDefinition) {
-                return true;
-            } else if (typeDefinition.getBaseType() instanceof ExtendedType) {
-                return isDerivedFromEnumerationType(typeDefinition
-                        .getBaseType());
+    private List<Type> allRPCMethodsToGenType(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException(
+                    "Module reference cannot be NULL!");
+        }
+
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+
+        if (module.getChildNodes() == null) {
+            throw new IllegalArgumentException("Reference to Set of "
+                    + "RPC Method Definitions in module " + module.getName()
+                    + " cannot be NULL!");
+        }
+
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
+        final List<Type> genRPCTypes = new ArrayList<>();
+        final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module,
+                "Service");
+        final Type future = Types.typeForClass(Future.class);
+        for (final RpcDefinition rpc : rpcDefinitions) {
+            if (rpc != null) {
+
+                String rpcName = parseToClassName(rpc.getQName()
+                        .getLocalName());
+                MethodSignatureBuilder method = interfaceBuilder
+                        .addMethod(rpcName);
+
+                final List<DataNodeIterator> rpcInOut = new ArrayList<>();
+
+                ContainerSchemaNode input = rpc.getInput();
+                ContainerSchemaNode output = rpc.getOutput();
+
+                if (input != null) {
+                    rpcInOut.add(new DataNodeIterator(input));
+                    GeneratedTypeBuilder inType = addRawInterfaceDefinition(
+                            basePackageName, input, rpcName);
+                    resolveDataSchemaNodes(basePackageName, inType, input.getChildNodes());
+                    Type inTypeInstance = inType.toInstance();
+                    genRPCTypes.add(inTypeInstance);
+                    method.addParameter(inTypeInstance, "input");
+                }
+
+                Type outTypeInstance = Types.typeForClass(Void.class);
+                if (output != null) {
+                    rpcInOut.add(new DataNodeIterator(output));
+
+                    GeneratedTypeBuilder outType = addRawInterfaceDefinition(
+                            basePackageName, output, rpcName);
+                    resolveDataSchemaNodes(basePackageName, outType, output.getChildNodes());
+                    outTypeInstance = outType.toInstance();
+                    genRPCTypes.add(outTypeInstance);
+
+                }
+
+                final Type rpcRes = Types.parameterizedTypeFor(
+                        Types.typeForClass(RpcResult.class), outTypeInstance);
+                method.addReturnType(Types.parameterizedTypeFor(future, rpcRes));
+                for (DataNodeIterator it : rpcInOut) {
+                    List<ContainerSchemaNode> nContainers = it.allContainers();
+                    if ((nContainers != null) && !nContainers.isEmpty()) {
+                        for (final ContainerSchemaNode container : nContainers) {
+                            genRPCTypes.add(containerToGenType(basePackageName,
+                                    container));
+                        }
+                    }
+                    List<ListSchemaNode> nLists = it.allLists();
+                    if ((nLists != null) && !nLists.isEmpty()) {
+                        for (final ListSchemaNode list : nLists) {
+                            genRPCTypes.addAll(listToGenType(basePackageName,
+                                    list));
+                        }
+                    }
+                }
             }
         }
-        return false;
+        genRPCTypes.add(interfaceBuilder.toInstance());
+        return genRPCTypes;
+    }
+
+    private List<Type> allNotificationsToGenType(final Module module) {
+        if (module == null) {
+            throw new IllegalArgumentException(
+                    "Module reference cannot be NULL!");
+        }
+
+        if (module.getName() == null) {
+            throw new IllegalArgumentException("Module name cannot be NULL!");
+        }
+
+        if (module.getChildNodes() == null) {
+            throw new IllegalArgumentException("Reference to Set of "
+                    + "Notification Definitions in module " + module.getName()
+                    + " cannot be NULL!");
+        }
+
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        final List<Type> genNotifyTypes = new ArrayList<>();
+        final Set<NotificationDefinition> notifications = module
+                .getNotifications();
+
+        for (final NotificationDefinition notification : notifications) {
+            if (notification != null) {
+                DataNodeIterator it = new DataNodeIterator(notification);
+
+                // Containers
+                for (ContainerSchemaNode node : it.allContainers()) {
+                    genNotifyTypes
+                            .add(containerToGenType(basePackageName, node));
+                }
+                // Lists
+                for (ListSchemaNode node : it.allLists()) {
+                    genNotifyTypes.addAll(listToGenType(basePackageName, node));
+                }
+                final GeneratedTypeBuilder notificationTypeBuilder = addRawInterfaceDefinition(
+                        basePackageName, notification);
+                notificationTypeBuilder.addImplementsType(Types
+                        .typeForClass(Notification.class));
+                // Notification object
+                resolveDataSchemaNodes(basePackageName,
+                        notificationTypeBuilder, notification.getChildNodes());
+                genNotifyTypes.add(notificationTypeBuilder.toInstance());
+            }
+        }
+        return genNotifyTypes;
+    }
+
+    private List<Type> allIdentitiesToGenTypes(final Module module,
+            final SchemaContext context) {
+        List<Type> genTypes = new ArrayList<Type>();
+
+        final Set<IdentitySchemaNode> schemaIdentities = module.getIdentities();
+
+        final String basePackageName = moduleNamespaceToPackageName(module);
+
+        if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
+            for (final IdentitySchemaNode identity : schemaIdentities) {
+                genTypes.add(identityToGenType(basePackageName, identity,
+                        context));
+            }
+        }
+        return genTypes;
+    }
+
+    private GeneratedType identityToGenType(final String basePackageName,
+            IdentitySchemaNode identity, SchemaContext context) {
+        if (identity == null) {
+            return null;
+        }
+
+        final String packageName = packageNameForGeneratedType(basePackageName,
+                identity.getPath());
+
+        final String genTypeName = parseToClassName(identity.getQName()
+                .getLocalName());
+        final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(
+                packageName, genTypeName);
+
+        IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
+        if (baseIdentity != null) {
+            Module baseIdentityParentModule = SchemaContextUtil.findParentModule(
+                    context, baseIdentity);
+
+            final String returnTypePkgName = moduleNamespaceToPackageName(baseIdentityParentModule);
+            final String returnTypeName = parseToClassName(baseIdentity
+                    .getQName().getLocalName());
+
+            GeneratedTransferObject gto = new GeneratedTOBuilderImpl(
+                    returnTypePkgName, returnTypeName).toInstance();
+            newType.addExtendsType(gto);
+        } else {
+            newType.addExtendsType(Types.getBaseIdentityTO());
+        }
+
+        return newType.toIdentityInstance();
+    }
+
+    private List<Type> allGroupingsToGenTypes(Module module) {
+        final List<Type> genTypes = new ArrayList<Type>();
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        Set<GroupingDefinition> groupings = module.getGroupings();
+        if (groupings != null && !groupings.isEmpty()) {
+            for (final GroupingDefinition grouping : groupings) {
+                genTypes.add(groupingToGenType(basePackageName, grouping));
+            }
+        }
+        return genTypes;
+    }
+
+    private GeneratedType groupingToGenType(final String basePackageName,
+            GroupingDefinition grouping) {
+        if (grouping == null) {
+            return null;
+        }
+
+        final String packageName = packageNameForGeneratedType(basePackageName,
+                grouping.getPath());
+        final Set<DataSchemaNode> schemaNodes = grouping.getChildNodes();
+        final GeneratedTypeBuilder typeBuilder = addRawInterfaceDefinition(
+                packageName, grouping);
+
+        resolveDataSchemaNodes(basePackageName, typeBuilder, schemaNodes);
+        return typeBuilder.toInstance();
     }
 
     private EnumTypeDefinition enumTypeDefFromExtendedType(
@@ -182,7 +494,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return null;
     }
 
-    private EnumBuilder resolveEnumFromTypeDefinition(
+    private EnumBuilder resolveInnerEnumFromTypeDefinition(
             final EnumTypeDefinition enumTypeDef, final String enumName,
             final GeneratedTypeBuilder typeBuilder) {
         if ((enumTypeDef != null) && (typeBuilder != null)
@@ -218,89 +530,20 @@ public class BindingGeneratorImpl implements BindingGenerator {
     }
 
     private GeneratedTypeBuilder moduleTypeBuilder(final Module module,
-                                                   final String postfix) {
+            final String postfix) {
         if (module == null) {
-            throw new IllegalArgumentException("Module reference cannot be NULL!");
+            throw new IllegalArgumentException(
+                    "Module reference cannot be NULL!");
         }
         String packageName = moduleNamespaceToPackageName(module);
-        final String moduleName = parseToClassName(module.getName())
-                + postfix;
+        final String moduleName = parseToClassName(module.getName()) + postfix;
 
         return new GeneratedTypeBuilderImpl(packageName, moduleName);
 
     }
 
-    private List<GeneratedType> rpcMethodsToGenType(final String basePackageName, final Module module) {
-        if (module == null) {
-            throw new IllegalArgumentException("Module reference cannot be NULL!");
-        }
-
-        final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
-        final List<GeneratedType> rpcTypes = new ArrayList<>();
-
-        if ((rpcDefinitions != null) && !rpcDefinitions.isEmpty()) {
-            for (final RpcDefinition rpc : rpcDefinitions) {
-                if (rpc != null) {
-                    final List<DataNodeIterator> rpcInOut = new ArrayList<>();
-                    rpcInOut.add(new DataNodeIterator(rpc.getInput()));
-                    rpcInOut.add(new DataNodeIterator(rpc.getOutput()));
-
-                    for (DataNodeIterator it : rpcInOut) {
-                        List<ContainerSchemaNode> nContainers = it.allContainers();
-                        if ((nContainers != null) && !nContainers.isEmpty()) {
-                            for (final ContainerSchemaNode container : nContainers) {
-                                rpcTypes.add(containerToGenType(basePackageName, container));
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        return rpcTypes;
-    }
-
-    private List<Type> notifycationsToGenType(final String basePackageName, final Module module) {
-        if (module == null) {
-            throw new IllegalArgumentException("Module reference cannot be NULL!");
-        }
-        final List<Type> notificationTypes = new ArrayList<>();
-        final Set<NotificationDefinition> notifications = module
-                .getNotifications();
-
-        if ((notifications != null) && !notifications.isEmpty()) {
-            for (final NotificationDefinition notification : notifications) {
-                if (notification != null) {
-                    final List<DataNodeIterator> notifyChildren = new ArrayList<>();
-
-                    for (DataSchemaNode childNode : notification.getChildNodes()) {
-                        if (childNode instanceof DataNodeContainer) {
-                            notifyChildren.add(new DataNodeIterator((DataNodeContainer) childNode));
-                        }
-                    }
-
-                    for (DataNodeIterator it : notifyChildren) {
-                        List<ContainerSchemaNode> nContainers = it.allContainers();
-                        List<ListSchemaNode> nLists = it.allLists();
-                        if ((nContainers != null) && !nContainers.isEmpty()) {
-                            for (final ContainerSchemaNode container : nContainers) {
-                                notificationTypes.add(containerToGenType(basePackageName, container));
-                            }
-                        }
-                        if ((nLists != null) && !nLists.isEmpty()) {
-                            for (final ListSchemaNode list : nLists) {
-
-                                notificationTypes.addAll(listToGenType(basePackageName, list));
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        return notificationTypes;
-    }
-
     private List<Type> augmentationToGenTypes(final String augmentPackageName,
-                                              final AugmentationSchema augSchema) {
+            final AugmentationSchema augSchema) {
         if (augmentPackageName == null) {
             throw new IllegalArgumentException("Package Name cannot be NULL!");
         }
@@ -318,23 +561,23 @@ public class BindingGeneratorImpl implements BindingGenerator {
         // EVERY augmented interface will extends Augmentation<T> interface
         // and DataObject interface!!!
         final SchemaPath targetPath = augSchema.getTargetPath();
-        final DataSchemaNode targetSchemaNode = findDataSchemaNode(schemaContext,
-                targetPath);
-        if ((targetSchemaNode != null) &&
-                (targetSchemaNode.getQName() != null) &&
-                (targetSchemaNode.getQName().getLocalName() != null)) {
+        final DataSchemaNode targetSchemaNode = findDataSchemaNode(
+                schemaContext, targetPath);
+        if ((targetSchemaNode != null) && (targetSchemaNode.getQName() != null)
+                && (targetSchemaNode.getQName().getLocalName() != null)) {
             final Module targetModule = findParentModule(schemaContext,
                     targetSchemaNode);
 
             final String targetBasePackage = moduleNamespaceToPackageName(targetModule);
-            final String targetPackageName = packageNameForGeneratedType(targetBasePackage,
-                    targetSchemaNode.getPath());
+            final String targetPackageName = packageNameForGeneratedType(
+                    targetBasePackage, targetSchemaNode.getPath());
 
-            final String targetSchemaNodeName = targetSchemaNode.getQName().getLocalName();
-            final Set<DataSchemaNode> augChildNodes = augSchema
-                    .getChildNodes();
+            final String targetSchemaNodeName = targetSchemaNode.getQName()
+                    .getLocalName();
+            final Set<DataSchemaNode> augChildNodes = augSchema.getChildNodes();
             final GeneratedTypeBuilder augTypeBuilder = addRawAugmentGenTypeDefinition(
-                    augmentPackageName, targetPackageName, targetSchemaNodeName, augSchema);
+                    augmentPackageName, targetPackageName,
+                    targetSchemaNodeName, augSchema);
             if (augTypeBuilder != null) {
                 genTypes.add(augTypeBuilder.toInstance());
             }
@@ -357,10 +600,11 @@ public class BindingGeneratorImpl implements BindingGenerator {
             genTypeBuilders.put(augmentPackageName, augmentBuilders);
         }
 
-        final String augTypeName = augGenTypeName(augmentBuilders, targetTypeName);
-        final Type targetTypeRef = new ReferencedTypeImpl(targetPackageName, targetTypeName);
-        final Set<DataSchemaNode> augChildNodes = augSchema
-                .getChildNodes();
+        final String augTypeName = augGenTypeName(augmentBuilders,
+                targetTypeName);
+        final Type targetTypeRef = new ReferencedTypeImpl(targetPackageName,
+                targetTypeName);
+        final Set<DataSchemaNode> augChildNodes = augSchema.getChildNodes();
 
         final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(
                 augmentPackageName, augTypeName);
@@ -369,13 +613,15 @@ public class BindingGeneratorImpl implements BindingGenerator {
         augTypeBuilder.addImplementsType(Types
                 .augmentationTypeFor(targetTypeRef));
 
-        augSchemaNodeToMethods(augmentPackageName, augTypeBuilder, augChildNodes);
+        augSchemaNodeToMethods(augmentPackageName, augTypeBuilder,
+                augChildNodes);
         augmentBuilders.put(augTypeName, augTypeBuilder);
         return augTypeBuilder;
     }
 
-    private List<Type> augmentationBodyToGenTypes(final String augBasePackageName,
-                                                  final Set<DataSchemaNode> augChildNodes) {
+    private List<Type> augmentationBodyToGenTypes(
+            final String augBasePackageName,
+            final Set<DataSchemaNode> augChildNodes) {
         final List<Type> genTypes = new ArrayList<>();
         final List<DataNodeIterator> augSchemaIts = new ArrayList<>();
         for (final DataSchemaNode childNode : augChildNodes) {
@@ -399,13 +645,12 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
             if ((augContainers != null) && !augContainers.isEmpty()) {
                 for (final ContainerSchemaNode container : augContainers) {
-                    genTypes.add(containerToGenType(augBasePackageName, container));
+                    genTypes.add(containerToGenType(augBasePackageName,
+                            container));
                 }
             }
             if ((augLists != null) && !augLists.isEmpty()) {
                 for (final ListSchemaNode list : augLists) {
-//                    final String listPackageName = packageNameForAugmentedType(
-//                            augBasePackageName, list.getPath());
                     genTypes.addAll(listToGenType(augBasePackageName, list));
                 }
             }
@@ -427,13 +672,13 @@ public class BindingGeneratorImpl implements BindingGenerator {
     }
 
     private GeneratedType containerToGenType(final String basePackageName,
-                                             ContainerSchemaNode containerNode) {
+            ContainerSchemaNode containerNode) {
         if (containerNode == null) {
             return null;
         }
 
-        final String packageName = packageNameForGeneratedType(
-                basePackageName, containerNode.getPath());
+        final String packageName = packageNameForGeneratedType(basePackageName,
+                containerNode.getPath());
         final Set<DataSchemaNode> schemaNodes = containerNode.getChildNodes();
         final GeneratedTypeBuilder typeBuilder = addRawInterfaceDefinition(
                 packageName, containerNode);
@@ -452,7 +697,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
                 if (schemaNode.isAugmenting()) {
                     continue;
                 }
-                addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder);
+                addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode,
+                        typeBuilder);
             }
         }
         return typeBuilder;
@@ -466,15 +712,15 @@ public class BindingGeneratorImpl implements BindingGenerator {
         if ((schemaNodes != null) && (typeBuilder != null)) {
             for (final DataSchemaNode schemaNode : schemaNodes) {
                 if (schemaNode.isAugmenting()) {
-                    addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder);
+                    addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode,
+                            typeBuilder);
                 }
             }
         }
         return typeBuilder;
     }
 
-    private void addSchemaNodeToBuilderAsMethod(
-            final String basePackageName,
+    private void addSchemaNodeToBuilderAsMethod(final String basePackageName,
             final DataSchemaNode schemaNode,
             final GeneratedTypeBuilder typeBuilder) {
         if (schemaNode != null && typeBuilder != null) {
@@ -507,31 +753,27 @@ public class BindingGeneratorImpl implements BindingGenerator {
                 final TypeDefinition<?> typeDef = leaf.getType();
 
                 Type returnType = null;
-                if (!(typeDef instanceof EnumTypeDefinition)
-                        && !isDerivedFromEnumerationType(typeDef)) {
+                if (!(typeDef instanceof EnumTypeDefinition)) {
                     returnType = typeProvider
                             .javaTypeForSchemaDefinitionType(typeDef);
                 } else {
-                    if (isImported(leaf.getPath(), typeDef.getPath())) {
-                        // TODO: resolving of imported enums as references to
-                        // GeneratedTypeData interface
-                    } else {
-                        final EnumTypeDefinition enumTypeDef = enumTypeDefFromExtendedType(typeDef);
-                        final EnumBuilder enumBuilder = resolveEnumFromTypeDefinition(
-                                enumTypeDef, leafName, typeBuilder);
-
-                        if (enumBuilder != null) {
-                            returnType = new ReferencedTypeImpl(
-                                    enumBuilder.getPackageName(),
-                                    enumBuilder.getName());
-                        }
+                    final EnumTypeDefinition enumTypeDef = enumTypeDefFromExtendedType(typeDef);
+                    final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(
+                            enumTypeDef, leafName, typeBuilder);
+
+                    if (enumBuilder != null) {
+                        returnType = new ReferencedTypeImpl(
+                                enumBuilder.getPackageName(),
+                                enumBuilder.getName());
                     }
+                    ((TypeProviderImpl) typeProvider).putReferencedType(
+                            leaf.getPath(), returnType);
                 }
-
                 if (returnType != null) {
                     constructGetter(typeBuilder, leafName, leafDesc, returnType);
                     if (!leaf.isConfiguration()) {
-                        constructSetter(typeBuilder, leafName, leafDesc, returnType);
+                        constructSetter(typeBuilder, leafName, leafDesc,
+                                returnType);
                     }
                     return true;
                 }
@@ -540,26 +782,6 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return false;
     }
 
-    private boolean isImported(final SchemaPath leafPath,
-                               final SchemaPath typeDefPath) {
-        if ((leafPath != null) && (leafPath.getPath() != null)
-                && (typeDefPath != null) && (typeDefPath.getPath() != null)) {
-
-            final QName leafPathQName = leafPath.getPath().get(0);
-            final QName typePathQName = typeDefPath.getPath().get(0);
-
-            if ((leafPathQName != null)
-                    && (leafPathQName.getNamespace() != null)
-                    && (typePathQName != null)
-                    && (typePathQName.getNamespace() != null)) {
-
-                return !leafPathQName.getNamespace().equals(
-                        typePathQName.getNamespace());
-            }
-        }
-        return false;
-    }
-
     private boolean resolveLeafSchemaNodeAsProperty(
             final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
             boolean isReadOnly) {
@@ -622,8 +844,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
     }
 
     private boolean resolveContainerSchemaNode(final String basePackageName,
-                                               final GeneratedTypeBuilder typeBuilder,
-                                               final ContainerSchemaNode containerNode) {
+            final GeneratedTypeBuilder typeBuilder,
+            final ContainerSchemaNode containerNode) {
         if ((containerNode != null) && (typeBuilder != null)) {
             final String nodeName = containerNode.getQName().getLocalName();
 
@@ -642,8 +864,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
     }
 
     private boolean resolveListSchemaNode(final String basePackageName,
-                                          final GeneratedTypeBuilder typeBuilder,
-                                          final ListSchemaNode schemaNode) {
+            final GeneratedTypeBuilder typeBuilder,
+            final ListSchemaNode schemaNode) {
         if ((schemaNode != null) && (typeBuilder != null)) {
             final String listName = schemaNode.getQName().getLocalName();
 
@@ -665,7 +887,13 @@ public class BindingGeneratorImpl implements BindingGenerator {
     }
 
     private GeneratedTypeBuilder addRawInterfaceDefinition(
-            final String packageName, final DataSchemaNode schemaNode) {
+            final String packageName, final SchemaNode schemaNode) {
+        return addRawInterfaceDefinition(packageName, schemaNode, "");
+    }
+
+    private GeneratedTypeBuilder addRawInterfaceDefinition(
+            final String packageName, final SchemaNode schemaNode,
+            final String prefix) {
         if (schemaNode == null) {
             return null;
         }
@@ -673,7 +901,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
         final String schemaNodeName = schemaNode.getQName().getLocalName();
 
         if ((packageName != null) && (schemaNodeName != null)) {
-            final String genTypeName = parseToClassName(schemaNodeName);
+            final String genTypeName = prefix + parseToClassName(schemaNodeName)
+                    ;
             final GeneratedTypeBuilder newType = new GeneratedTypeBuilderImpl(
                     packageName, genTypeName);
 
@@ -738,9 +967,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return setMethod;
     }
 
-
     private List<Type> listToGenType(final String basePackageName,
-                                     final ListSchemaNode list) {
+            final ListSchemaNode list) {
         if (basePackageName == null) {
             throw new IllegalArgumentException(
                     "Package Name for Generated Type cannot be NULL!");
@@ -750,8 +978,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
                     "List Schema Node cannot be NULL!");
         }
 
-        final String packageName = packageNameForGeneratedType(
-                basePackageName, list.getPath());
+        final String packageName = packageNameForGeneratedType(basePackageName,
+                list.getPath());
         final GeneratedTypeBuilder typeBuilder = resolveListTypeBuilder(
                 packageName, list);
         final List<String> listKeys = listKeys(list);
@@ -764,34 +992,16 @@ public class BindingGeneratorImpl implements BindingGenerator {
             if (schemaNode.isAugmenting()) {
                 continue;
             }
-            addSchemaNodeToListBuilders(basePackageName, schemaNode, typeBuilder,
-                    genTOBuilder, listKeys);
-        }
-
-//        if (list.isAugmenting()) {
-//            for (final DataSchemaNode schemaNode : schemaNodes) {
-//                if (schemaNode.isAugmenting()) {
-//                    addSchemaNodeToListBuilders(basePackageName, schemaNode, typeBuilder,
-//                            genTOBuilder, listKeys);
-//                }
-//            }
-//        } else {
-//            for (final DataSchemaNode schemaNode : schemaNodes) {
-//                if (schemaNode.isAugmenting()) {
-//                    continue;
-//                }
-//                addSchemaNodeToListBuilders(basePackageName, schemaNode, typeBuilder,
-//                        genTOBuilder, listKeys);
-//            }
-//        }
+            addSchemaNodeToListBuilders(basePackageName, schemaNode,
+                    typeBuilder, genTOBuilder, listKeys);
+        }
         return typeBuildersToGenTypes(typeBuilder, genTOBuilder);
     }
 
     private void addSchemaNodeToListBuilders(final String basePackageName,
-                                             final DataSchemaNode schemaNode,
-                                             final GeneratedTypeBuilder typeBuilder,
-                                             final GeneratedTOBuilder genTOBuilder,
-                                             final List<String> listKeys) {
+            final DataSchemaNode schemaNode,
+            final GeneratedTypeBuilder typeBuilder,
+            final GeneratedTOBuilder genTOBuilder, final List<String> listKeys) {
         if (schemaNode == null) {
             throw new IllegalArgumentException(
                     "Data Schema Node cannot be NULL!");
@@ -816,9 +1026,9 @@ public class BindingGeneratorImpl implements BindingGenerator {
             resolveContainerSchemaNode(basePackageName, typeBuilder,
                     (ContainerSchemaNode) schemaNode);
         } else if (schemaNode instanceof ListSchemaNode) {
-            resolveListSchemaNode(basePackageName, typeBuilder, (ListSchemaNode) schemaNode);
+            resolveListSchemaNode(basePackageName, typeBuilder,
+                    (ListSchemaNode) schemaNode);
         }
-
     }
 
     private List<Type> typeBuildersToGenTypes(
@@ -845,13 +1055,13 @@ public class BindingGeneratorImpl implements BindingGenerator {
      * @return
      */
     private GeneratedTOBuilder resolveListKey(final String packageName,
-                                              final ListSchemaNode list) {
+            final ListSchemaNode list) {
         final String listName = list.getQName().getLocalName() + "Key";
         return schemaNodeToTransferObjectBuilder(packageName, list, listName);
     }
 
     private boolean isPartOfListKey(final LeafSchemaNode leaf,
-                                    final List<String> keys) {
+            final List<String> keys) {
         if ((leaf != null) && (keys != null) && (leaf.getQName() != null)) {
             final String leafName = leaf.getQName().getLocalName();
             if (keys.contains(leafName)) {
@@ -889,7 +1099,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
         final String genTypeName = parseToClassName(schemaNodeName);
 
         GeneratedTypeBuilder typeBuilder = null;
-        final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
+        final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders
+                .get(packageName);
         if (builders != null) {
             typeBuilder = builders.get(genTypeName);
         }
@@ -906,7 +1117,6 @@ public class BindingGeneratorImpl implements BindingGenerator {
         if (listKeys.size() > 0) {
             genTOBuilder = resolveListKey(packageName, list);
         }
-
         return genTOBuilder;
     }
 }
index 374ad8bf9251463b0dc9e86896a105b4f64f20e0..4a74ce6a9eca339893092f47776f40901f613bbe 100644 (file)
@@ -16,7 +16,7 @@ import org.opendaylight.controller.sal.binding.generator.spi.TypeProvider;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 import org.opendaylight.controller.yang.model.api.TypeDefinition;
 
-public class BaseYangTypes {
+public final class BaseYangTypes {
 
     private static Map<String, Type> typeMap = new HashMap<String, Type>();
 
@@ -32,6 +32,7 @@ public class BaseYangTypes {
     public static final Type UINT16_TYPE = Types.typeForClass(Integer.class);
     public static final Type UINT32_TYPE = Types.typeForClass(Long.class);
     public static final Type UINT64_TYPE = Types.typeForClass(BigInteger.class);
+    public static final Type BINARY_TYPE = Types.primitiveType("byte[]");
 
     static {
         typeMap.put("boolean", BOOLEAN_TYPE);
@@ -46,6 +47,7 @@ public class BaseYangTypes {
         typeMap.put("uint16", UINT16_TYPE);
         typeMap.put("uint32", UINT32_TYPE);
         typeMap.put("uint64", UINT64_TYPE);
+        typeMap.put("binary", BINARY_TYPE);
     }
 
     public static final TypeProvider BASE_YANG_TYPES_PROVIDER = new TypeProvider() {
index 0618efc8aec7f8a0732a8daafaf14e1c11203bbc..96069c273c071b96d3594b484055f0c32913a6f1 100644 (file)
@@ -7,15 +7,7 @@
  */
 package org.opendaylight.controller.sal.binding.yang.types;
 
-import static org.opendaylight.controller.yang.model.util.SchemaContextUtil.*;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.controller.binding.generator.util.BindingGeneratorUtil;
+import org.opendaylight.controller.binding.generator.util.ReferencedTypeImpl;
 import org.opendaylight.controller.binding.generator.util.Types;
 import org.opendaylight.controller.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
 import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
@@ -27,13 +19,8 @@ import org.opendaylight.controller.sal.binding.model.api.type.builder.EnumBuilde
 import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTOBuilder;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
-import org.opendaylight.controller.yang.model.api.DataSchemaNode;
-import org.opendaylight.controller.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.controller.yang.model.api.LeafSchemaNode;
-import org.opendaylight.controller.yang.model.api.Module;
-import org.opendaylight.controller.yang.model.api.RevisionAwareXPath;
-import org.opendaylight.controller.yang.model.api.SchemaContext;
-import org.opendaylight.controller.yang.model.api.TypeDefinition;
+import org.opendaylight.controller.yang.common.QName;
+import org.opendaylight.controller.yang.model.api.*;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
 import org.opendaylight.controller.yang.model.api.type.IdentityrefTypeDefinition;
@@ -41,11 +28,19 @@ import org.opendaylight.controller.yang.model.api.type.LeafrefTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.UnionTypeDefinition;
 import org.opendaylight.controller.yang.model.util.ExtendedType;
 
-public class TypeProviderImpl implements TypeProvider {
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.opendaylight.controller.binding.generator.util.BindingGeneratorUtil.*;
+import static org.opendaylight.controller.yang.model.util.SchemaContextUtil.*;
+
+public final class TypeProviderImpl implements TypeProvider {
 
     private final SchemaContext schemaContext;
-    private Map<String, Map<String, GeneratedTransferObject>> genTypeDefsContextMap;
-    private final List<GeneratedTransferObject> allTypeDefinitions;
+    private Map<String, Map<String, Type>> genTypeDefsContextMap;
+    private final Map<SchemaPath, Type> referencedTypes;
 
     public TypeProviderImpl(final SchemaContext schemaContext) {
         if (schemaContext == null) {
@@ -53,12 +48,23 @@ public class TypeProviderImpl implements TypeProvider {
         }
 
         this.schemaContext = schemaContext;
-        this.genTypeDefsContextMap = new HashMap<String, Map<String, GeneratedTransferObject>>();
-        allTypeDefinitions = resolveTypeDefsFromContext();
+        this.genTypeDefsContextMap = new HashMap<>();
+        this.referencedTypes = new HashMap<>();
+        resolveTypeDefsFromContext();
     }
 
-    public List<GeneratedTransferObject> getGeneratedTypeDefs() {
-        return allTypeDefinitions;
+    public void putReferencedType(final SchemaPath refTypePath,
+                                  final Type refType) {
+        if (refTypePath == null) {
+            throw new IllegalArgumentException("Path reference of " +
+                    "Enumeration Type Definition cannot be NULL!");
+        }
+
+        if (refType == null) {
+            throw new IllegalArgumentException("Reference to Enumeration " +
+                    "Type cannot be NULL!");
+        }
+        referencedTypes.put(refTypePath, refType);
     }
 
     /*
@@ -78,103 +84,179 @@ public class TypeProviderImpl implements TypeProvider {
     public Type javaTypeForSchemaDefinitionType(
             final TypeDefinition<?> typeDefinition) {
         Type returnType = null;
-        if (typeDefinition != null) {
-            final String typedefName = typeDefinition.getQName().getLocalName();
-            if (typeDefinition instanceof ExtendedType) {
-                final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
-
-                if (baseTypeDef instanceof LeafrefTypeDefinition) {
-                    final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) baseTypeDef;
-                    returnType = provideTypeForLeafref(leafref);
-                } else if (baseTypeDef instanceof IdentityrefTypeDefinition) {
-
-                } else if (baseTypeDef instanceof EnumTypeDefinition) {
-                    final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
-                    returnType = resolveEnumFromTypeDefinition(enumTypeDef,
-                            typedefName);
-                } else {
-
-                    final Module module = resolveModuleFromTypePath(schemaContext, typeDefinition);
-
-                    if (module != null) {
-                        final Map<String, GeneratedTransferObject> genTOs = genTypeDefsContextMap
-                                .get(module.getName());
-                        if (genTOs != null) {
-                            returnType = genTOs.get(typedefName);
-                        }
+        if (typeDefinition == null) {
+            throw new IllegalArgumentException("Type Definition cannot be " +
+                    "NULL!");
+        }
+        if (typeDefinition.getQName() == null) {
+            throw new IllegalArgumentException("Type Definition cannot have " +
+                    "non specified QName (QName cannot be NULL!)");
+        }
+        if (typeDefinition.getQName().getLocalName() == null) {
+            throw new IllegalArgumentException("Type Definitions Local Name " +
+                    "cannot be NULL!");
+        }
+        final String typedefName = typeDefinition.getQName().getLocalName();
+        if (typeDefinition instanceof ExtendedType) {
+            final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
+
+            if (baseTypeDef instanceof LeafrefTypeDefinition) {
+                final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) baseTypeDef;
+                returnType = provideTypeForLeafref(leafref);
+            } else if (baseTypeDef instanceof IdentityrefTypeDefinition) {
+                final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition)typeDefinition;
+                returnType = returnTypeForIdentityref(idref);
+            } else if (baseTypeDef instanceof EnumTypeDefinition) {
+                final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
+                returnType = resolveEnumFromTypeDefinition(enumTypeDef,
+                        typedefName);
+            } else {
+                final Module module = findParentModuleForTypeDefinition(schemaContext,
+                        typeDefinition);
+                if (module != null) {
+                    final Map<String, Type> genTOs = genTypeDefsContextMap
+                            .get(module.getName());
+                    if (genTOs != null) {
+                        returnType = genTOs.get(typedefName);
+                    }
+                    if (returnType == null) {
+                        returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+                                .javaTypeForSchemaDefinitionType(baseTypeDef);
                     }
                 }
+            }
+        } else {
+            if (typeDefinition instanceof LeafrefTypeDefinition) {
+                final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
+                returnType = provideTypeForLeafref(leafref);
+            } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
+                final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition)typeDefinition;
+                returnType = returnTypeForIdentityref(idref);
             } else {
-                if (typeDefinition instanceof LeafrefTypeDefinition) {
-                    final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
-                    returnType = provideTypeForLeafref(leafref);
-                } else if (typeDefinition instanceof EnumTypeDefinition) {
-                    final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDefinition;
-                    returnType = resolveEnumFromTypeDefinition(enumTypeDef,
-                            typedefName);
-                } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
-
-                } else {
-                    returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
-                            .javaTypeForSchemaDefinitionType(typeDefinition);
-                }
+                returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+                        .javaTypeForSchemaDefinitionType(typeDefinition);
             }
         }
+        //TODO: add throw exception when we will be able to resolve ALL yang
+        // types!
+//        if (returnType == null) {
+//            throw new IllegalArgumentException("Type Provider can't resolve " +
+//                    "type for specified Type Definition " + typedefName);
+//        }
         return returnType;
     }
-
-    private TypeDefinition<?> baseTypeDefForExtendedType(
-            final TypeDefinition<?> extendTypeDef) {
-        if (extendTypeDef != null) {
-            final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
-            if (baseTypeDef instanceof ExtendedType) {
-                return baseTypeDefForExtendedType(baseTypeDef);
-            } else {
-                return baseTypeDef;
+    
+    private Type returnTypeForIdentityref(IdentityrefTypeDefinition idref) {
+        QName baseIdQName = idref.getIdentity();
+        Module module = schemaContext.findModuleByNamespace(baseIdQName.getNamespace());
+        IdentitySchemaNode identity = null;
+        for(IdentitySchemaNode id : module.getIdentities()) {
+            if(id.getQName().equals(baseIdQName)) {
+                identity = id;
             }
         }
-        return null;
+        if(identity == null) {
+            throw new IllegalArgumentException("Target identity '" + baseIdQName + "' do not exists");
+        }
+
+        final String basePackageName = moduleNamespaceToPackageName(module);
+        final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
+        final String genTypeName = parseToClassName(identity.getQName().getLocalName());
+
+        Type baseType = Types.typeForClass(Class.class);
+        Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
+        Type returnType = Types.parameterizedTypeFor(baseType, paramType);
+        return returnType;
     }
 
-    public Type baseTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
+    public Type generatedTypeForExtendedDefinitionType(
+            final TypeDefinition<?> typeDefinition) {
         Type returnType = null;
-        if (typeDefinition != null) {
-            final TypeDefinition<?> baseTypeDefinition = baseTypeDefForExtendedType(typeDefinition);
+        if (typeDefinition == null) {
+            throw new IllegalArgumentException("Type Definition cannot be " +
+                    "NULL!");
+        }
+        if (typeDefinition.getQName() == null) {
+            throw new IllegalArgumentException("Type Definition cannot have " +
+                    "non specified QName (QName cannot be NULL!)");
+        }
+        if (typeDefinition.getQName() == null) {
+            throw new IllegalArgumentException("Type Definitions Local Name " +
+                    "cannot be NULL!");
+        }
 
-            if (baseTypeDefinition instanceof EnumTypeDefinition) {
-                final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDefinition;
-                final String enumName = enumTypeDef.getQName().getLocalName();
-                return resolveEnumFromTypeDefinition(enumTypeDef, enumName);
-            } else {
-                returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
-                        .javaTypeForSchemaDefinitionType(typeDefinition);
+        final String typedefName = typeDefinition.getQName().getLocalName();
+        if (typeDefinition instanceof ExtendedType) {
+            final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
+
+            if (!(baseTypeDef instanceof LeafrefTypeDefinition)
+                    && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
+                final Module module = findParentModuleForTypeDefinition(schemaContext,
+                        typeDefinition);
+
+                if (module != null) {
+                    final Map<String, Type> genTOs = genTypeDefsContextMap
+                            .get(module.getName());
+                    if (genTOs != null) {
+                        returnType = genTOs.get(typedefName);
+                    }
+                }
             }
         }
         return returnType;
     }
 
+    private TypeDefinition<?> baseTypeDefForExtendedType(
+            final TypeDefinition<?> extendTypeDef) {
+        if (extendTypeDef == null) {
+            throw new IllegalArgumentException("Type Definiition reference " +
+                    "cannot be NULL!");
+        }
+        final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
+        if (baseTypeDef instanceof ExtendedType) {
+            return baseTypeDefForExtendedType(baseTypeDef);
+        } else {
+            return baseTypeDef;
+        }
+
+    }
+
     public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType) {
         Type returnType = null;
-        if ((leafrefType != null) && (leafrefType.getPathStatement() != null)
-                && (leafrefType.getPath() != null)) {
+        if (leafrefType == null) {
+            throw new IllegalArgumentException("Leafref Type Definition " +
+                    "reference cannot be NULL!");
+        }
 
-            final RevisionAwareXPath xpath = leafrefType.getPathStatement();
-            final String strXPath = xpath.toString();
+        if (leafrefType.getPathStatement() == null) {
+            throw new IllegalArgumentException("The Path Statement for " +
+                    "Leafref Type Definition cannot be NULL!");
+        }
 
-            if (strXPath != null) {
-                if (strXPath.matches(".*//[.* | .*//].*")) {
-                    returnType = Types.typeForClass(Object.class);
-                } else {
-                    final Module module = resolveModuleFromTypePath(schemaContext, leafrefType);
-                    if (module != null) {
-                        final DataSchemaNode dataNode;
-                        if (xpath.isAbsolute()) {
-                            dataNode = findDataSchemaNode(schemaContext,
-                                    module, xpath);
-                        } else {
-                            dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module,
-                                            leafrefType, xpath);
-                        }
+        final RevisionAwareXPath xpath = leafrefType.getPathStatement();
+        final String strXPath = xpath.toString();
+
+        if (strXPath != null) {
+            if (strXPath.matches(".*//[.* | .*//].*")) {
+                returnType = Types.typeForClass(Object.class);
+            } else {
+                final Module module = findParentModuleForTypeDefinition(schemaContext, leafrefType);
+                if (module != null) {
+                    final DataSchemaNode dataNode;
+                    if (xpath.isAbsolute()) {
+                        dataNode = findDataSchemaNode(schemaContext, module,
+                                xpath);
+                    } else {
+                        dataNode = findDataSchemaNodeForRelativeXPath(schemaContext,
+                                module, leafrefType, xpath);
+                    }
+
+                    if (leafContainsEnumDefinition(dataNode)) {
+                        returnType = referencedTypes.get(dataNode.getPath());
+                    } else if (leafListContainsEnumDefinition(dataNode)) {
+                        returnType = Types.listTypeFor(referencedTypes.get(
+                                dataNode.getPath()));
+                    } else {
                         returnType = resolveTypeFromDataSchemaNode(dataNode);
                     }
                 }
@@ -183,83 +265,112 @@ public class TypeProviderImpl implements TypeProvider {
         return returnType;
     }
 
-    private EnumBuilder resolveEnumFromTypeDefinition(
-            final EnumTypeDefinition enumTypeDef, final String enumName,
-            final GeneratedTypeBuilder typeBuilder) {
-        if ((enumTypeDef != null) && (typeBuilder != null)
-                && (enumTypeDef.getQName() != null)
-                && (enumTypeDef.getQName().getLocalName() != null)) {
-
-            final String enumerationName = BindingGeneratorUtil
-                    .parseToClassName(enumName);
-            final EnumBuilder enumBuilder = typeBuilder
-                    .addEnumeration(enumerationName);
-
-            if (enumBuilder != null) {
-                final List<EnumPair> enums = enumTypeDef.getValues();
-                if (enums != null) {
-                    int listIndex = 0;
-                    for (final EnumPair enumPair : enums) {
-                        if (enumPair != null) {
-                            final String enumPairName = BindingGeneratorUtil
-                                    .parseToClassName(enumPair.getName());
-                            Integer enumPairValue = enumPair.getValue();
-
-                            if (enumPairValue == null) {
-                                enumPairValue = listIndex;
-                            }
-                            enumBuilder.addValue(enumPairName, enumPairValue);
-                            listIndex++;
-                        }
-                    }
-                }
-                return enumBuilder;
+    private boolean leafContainsEnumDefinition(final DataSchemaNode dataNode) {
+        if (dataNode instanceof LeafSchemaNode) {
+            final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
+            if (leaf.getType() instanceof EnumTypeDefinition) {
+                return true;
             }
         }
-        return null;
+        return false;
+    }
+
+    private boolean leafListContainsEnumDefinition(
+            final DataSchemaNode dataNode) {
+        if (dataNode instanceof LeafListSchemaNode) {
+            final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
+            if (leafList.getType() instanceof EnumTypeDefinition) {
+                return true;
+            }
+        }
+        return false;
     }
 
     private Enumeration resolveEnumFromTypeDefinition(
             final EnumTypeDefinition enumTypeDef, final String enumName) {
-        if ((enumTypeDef != null) && (enumTypeDef.getQName() != null)
-                && (enumTypeDef.getQName().getLocalName() != null)) {
-
-            final String enumerationName = BindingGeneratorUtil
-                    .parseToClassName(enumName);
-
-            Module module = resolveModuleFromTypePath(schemaContext, enumTypeDef);
-
-            final String basePackageName = BindingGeneratorUtil
-                    .moduleNamespaceToPackageName(module);
-            final String packageName = BindingGeneratorUtil
-                    .packageNameForGeneratedType(basePackageName,
-                            enumTypeDef.getPath());
-
-            final EnumBuilder enumBuilder = new EnumerationBuilderImpl(
-                    packageName, enumerationName);
-
-            if (enumBuilder != null) {
-                final List<EnumPair> enums = enumTypeDef.getValues();
-                if (enums != null) {
-                    int listIndex = 0;
-                    for (final EnumPair enumPair : enums) {
-                        if (enumPair != null) {
-                            final String enumPairName = BindingGeneratorUtil
-                                    .parseToClassName(enumPair.getName());
-                            Integer enumPairValue = enumPair.getValue();
-
-                            if (enumPairValue == null) {
-                                enumPairValue = listIndex;
-                            }
-                            enumBuilder.addValue(enumPairName, enumPairValue);
-                            listIndex++;
+        if (enumTypeDef == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition reference " +
+                    "cannot be NULL!");
+        }
+        if (enumTypeDef.getValues() == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
+                    "contain at least ONE value definition!");
+        }
+        if (enumTypeDef.getQName() == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
+                    "contain NON-NULL QName!");
+        }
+        if (enumTypeDef.getQName().getLocalName() == null) {
+            throw new IllegalArgumentException("Local Name in " +
+                    "EnumTypeDefinition QName cannot be NULL!");
+        }
+
+        final String enumerationName = parseToClassName(enumName);
+
+        Module module = findParentModuleForTypeDefinition(schemaContext, enumTypeDef);
+        final String basePackageName = moduleNamespaceToPackageName(module);
+
+        final EnumBuilder enumBuilder = new EnumerationBuilderImpl(
+                basePackageName, enumerationName);
+        updateEnumPairsFromEnumTypeDef(enumTypeDef, enumBuilder);
+        return enumBuilder.toInstance(null);
+    }
+
+    private EnumBuilder resolveInnerEnumFromTypeDefinition(
+            final EnumTypeDefinition enumTypeDef, final String enumName,
+            final GeneratedTypeBuilder typeBuilder) {
+        if (enumTypeDef == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition reference " +
+                    "cannot be NULL!");
+        }
+        if (enumTypeDef.getValues() == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
+                    "contain at least ONE value definition!");
+        }
+        if (enumTypeDef.getQName() == null) {
+            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
+                    "contain NON-NULL QName!");
+        }
+        if (enumTypeDef.getQName().getLocalName() == null) {
+            throw new IllegalArgumentException("Local Name in " +
+                    "EnumTypeDefinition QName cannot be NULL!");
+        }
+        if (typeBuilder == null) {
+            throw new IllegalArgumentException("Generated Type Builder " +
+                    "reference cannot be NULL!");
+        }
+
+        final String enumerationName = parseToClassName(enumName);
+        final EnumBuilder enumBuilder = typeBuilder
+                .addEnumeration(enumerationName);
+
+        updateEnumPairsFromEnumTypeDef(enumTypeDef, enumBuilder);
+
+        return enumBuilder;
+    }
+
+    private void updateEnumPairsFromEnumTypeDef(
+            final EnumTypeDefinition enumTypeDef,
+            final EnumBuilder enumBuilder) {
+        if (enumBuilder != null) {
+            final List<EnumPair> enums = enumTypeDef.getValues();
+            if (enums != null) {
+                int listIndex = 0;
+                for (final EnumPair enumPair : enums) {
+                    if (enumPair != null) {
+                        final String enumPairName = parseToClassName(enumPair
+                                .getName());
+                        Integer enumPairValue = enumPair.getValue();
+
+                        if (enumPairValue == null) {
+                            enumPairValue = listIndex;
                         }
+                        enumBuilder.addValue(enumPairName, enumPairValue);
+                        listIndex++;
                     }
                 }
-                return enumBuilder.toInstance(null);
             }
         }
-        return null;
     }
 
     private Type resolveTypeFromDataSchemaNode(final DataSchemaNode dataNode) {
@@ -276,129 +387,185 @@ public class TypeProviderImpl implements TypeProvider {
         return returnType;
     }
 
-    private List<GeneratedTransferObject> resolveTypeDefsFromContext() {
-        final List<GeneratedTransferObject> genTypeDefs = new ArrayList<GeneratedTransferObject>();
+    private void resolveTypeDefsFromContext() {
         final Set<Module> modules = schemaContext.getModules();
-        if (modules != null) {
-            for (final Module module : modules) {
-                if (module != null) {
-                    final String moduleName = module.getName();
-                    final String basePackageName = BindingGeneratorUtil
-                            .moduleNamespaceToPackageName(module);
-
-                    final Set<TypeDefinition<?>> typeDefinitions = module
-                            .getTypeDefinitions();
-
-                    if ((typeDefinitions != null) && (basePackageName != null)) {
-                        for (final TypeDefinition<?> typedef : typeDefinitions) {
-                            final GeneratedTransferObject genTransObj = toGeneratedTransferObject(
-                                    basePackageName, moduleName, typedef);
-                            if (genTransObj != null) {
-                                genTypeDefs.add(genTransObj);
-                            }
-                        }
-                        // for (final TypeDefinition<?> typedef :
-                        // typeDefinitions) {
-                        // addUnionGeneratedTypeDefinition(basePackageName,
-                        // module.getName(), typedef);
-                        // }
-                    }
+        if (modules == null) {
+            throw new IllegalArgumentException("Sef of Modules cannot be " +
+                    "NULL!");
+        }
+        for (final Module module : modules) {
+            if (module == null) {
+                continue;
+            }
+            final String moduleName = module.getName();
+            final String basePackageName = moduleNamespaceToPackageName(module);
+
+            final Set<TypeDefinition<?>> typeDefinitions = module
+                    .getTypeDefinitions();
+
+            final Map<String, Type> typeMap = new HashMap<>();
+            genTypeDefsContextMap.put(moduleName, typeMap);
+
+            if ((typeDefinitions != null) && (basePackageName != null)) {
+                for (final TypeDefinition<?> typedef : typeDefinitions) {
+                    typedefToGeneratedType(basePackageName, moduleName, typedef);
+                }
+                final List<ExtendedType> extUnions = UnionDependencySort
+                        .sort(typeDefinitions);
+                for (final ExtendedType extUnionType : extUnions) {
+                    addUnionGeneratedTypeDefinition(basePackageName, extUnionType);
                 }
             }
         }
-        return genTypeDefs;
     }
 
-    private GeneratedTransferObject toGeneratedTransferObject(
-            final String basePackageName, final String moduleName,
-            final TypeDefinition<?> typedef) {
+    private Type typedefToGeneratedType(final String basePackageName,
+                                        final String moduleName, final TypeDefinition<?> typedef) {
         if ((basePackageName != null) && (moduleName != null)
                 && (typedef != null) && (typedef.getQName() != null)) {
-            final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(
-                    basePackageName, typedef);
 
-            final String typedefName = typedef.getQName().getLocalName();
-            final String propertyName = BindingGeneratorUtil
-                    .parseToValidParamName(typedefName);
 
+            final String typedefName = typedef.getQName().getLocalName();
             final TypeDefinition<?> baseTypeDefinition = baseTypeDefForExtendedType(typedef);
             if (!(baseTypeDefinition instanceof LeafrefTypeDefinition)
                     && !(baseTypeDefinition instanceof IdentityrefTypeDefinition)) {
-                Type returnType = null;
+                Type returnType;
                 if (baseTypeDefinition instanceof EnumTypeDefinition) {
                     final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDefinition;
                     returnType = resolveEnumFromTypeDefinition(enumTypeDef,
                             typedefName);
+
                 } else {
-                    returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+                    final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
                             .javaTypeForSchemaDefinitionType(baseTypeDefinition);
-                }
 
+                    returnType = wrapJavaTypeIntoTO(basePackageName, typedef,
+                            javaType);
+                }
                 if (returnType != null) {
-                    final GeneratedPropertyBuilder genPropBuilder = genTOBuilder
-                            .addProperty(propertyName);
-
-                    genPropBuilder.addReturnType(returnType);
-                    genTOBuilder.addEqualsIdentity(genPropBuilder);
-                    genTOBuilder.addHashIdentity(genPropBuilder);
-                    genTOBuilder.addToStringProperty(genPropBuilder);
-
-                    Map<String, GeneratedTransferObject> transferObjectsMap = genTypeDefsContextMap
-                            .get(moduleName);
-                    if (transferObjectsMap == null) {
-                        transferObjectsMap = new HashMap<String, GeneratedTransferObject>();
-                        genTypeDefsContextMap.put(moduleName,
-                                transferObjectsMap);
-                    }
-
-                    final GeneratedTransferObject transferObject = genTOBuilder
-                            .toInstance();
-                    if (transferObject != null) {
-                        transferObjectsMap.put(typedefName, transferObject);
-                        return transferObject;
+                    final Map<String, Type> typeMap = genTypeDefsContextMap.get
+                            (moduleName);
+                    if (typeMap != null) {
+                        typeMap.put(typedefName, returnType);
                     }
+                    return returnType;
                 }
             }
         }
         return null;
     }
 
+    private GeneratedTransferObject wrapJavaTypeIntoTO(
+            final String basePackageName, final TypeDefinition<?> typedef,
+            final Type javaType) {
+        if (javaType != null) {
+            final String typedefName = typedef.getQName().getLocalName();
+            final String propertyName = parseToValidParamName(typedefName);
+
+            final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(
+                    basePackageName, typedef);
+
+            final GeneratedPropertyBuilder genPropBuilder = genTOBuilder
+                    .addProperty(propertyName);
+
+            genPropBuilder.addReturnType(javaType);
+            genTOBuilder.addEqualsIdentity(genPropBuilder);
+            genTOBuilder.addHashIdentity(genPropBuilder);
+            genTOBuilder.addToStringProperty(genPropBuilder);
+            return genTOBuilder.toInstance();
+        }
+        return null;
+    }
+
     private void addUnionGeneratedTypeDefinition(final String basePackageName,
-            final String moduleName, final TypeDefinition<?> typedef) {
-        if ((basePackageName != null) && (moduleName != null)
-                && (typedef != null) && (typedef.getQName() != null)) {
-            final TypeDefinition<?> baseTypeDefinition = baseTypeDefForExtendedType(typedef);
+                                                 final TypeDefinition<?> typedef) {
+        if (basePackageName == null) {
+            throw new IllegalArgumentException("Base Package Name cannot be " +
+                    "NULL!");
+        }
+        if (typedef == null) {
+            throw new IllegalArgumentException("Type Definition cannot be " +
+                    "NULL!");
+        }
+        if (typedef.getQName() == null) {
+            throw new IllegalArgumentException("Type Definition cannot have " +
+                    "non specified QName (QName cannot be NULL!)");
+        }
 
-            if ((baseTypeDefinition != null)
-                    && (baseTypeDefinition instanceof UnionTypeDefinition)) {
-                final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
-
-                final List<TypeDefinition<?>> unionTypes = unionTypeDef
-                        .getTypes();
-                final Map<String, GeneratedTransferObject> genTOsMap = genTypeDefsContextMap
-                        .get(moduleName);
-                final GeneratedTOBuilder unionGenTransObject = typedefToTransferObject(
-                        basePackageName, typedef);
-                if ((unionTypes != null) && (genTOsMap != null)
-                        && (unionGenTransObject != null)) {
-                    for (final TypeDefinition<?> unionType : unionTypes) {
-                        final String typeName = unionType.getQName()
-                                .getLocalName();
-                        final GeneratedTransferObject genTransferObject = genTOsMap
-                                .get(typeName);
-
-                        if (genTransferObject != null) {
-                            unionGenTransObject
-                                    .addProperty(
-                                            BindingGeneratorUtil
-                                                    .parseToValidParamName(genTransferObject
-                                                            .getName()))
-                                    .addReturnType(genTransferObject);
+        final TypeDefinition<?> baseTypeDefinition = typedef.getBaseType();
+        if ((baseTypeDefinition != null)
+                && (baseTypeDefinition instanceof UnionTypeDefinition)) {
+            final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
+            final List<TypeDefinition<?>> unionTypes = unionTypeDef
+                    .getTypes();
+            final Module parentModule = findParentModuleForTypeDefinition(schemaContext,
+                    typedef);
+
+            Map<String, Type> genTOsMap = null;
+            if (parentModule != null && parentModule.getName() != null) {
+                genTOsMap = genTypeDefsContextMap.get(parentModule.getName());
+            }
+
+            final GeneratedTOBuilder unionGenTransObject = typedefToTransferObject(
+                    basePackageName, typedef);
+            if ((unionTypes != null) && (unionGenTransObject != null)) {
+                for (final TypeDefinition<?> unionType : unionTypes) {
+                    final String typeName = unionType.getQName()
+                            .getLocalName();
+                    if (unionType instanceof ExtendedType) {
+                        final Module unionTypeModule = findParentModuleForTypeDefinition(schemaContext,
+                                unionType);
+                        if (unionTypeModule != null && unionTypeModule.getName() != null) {
+                            final Map<String, Type> innerGenTOs = genTypeDefsContextMap
+                                    .get(unionTypeModule.getName());
+
+                            final GeneratedTransferObject genTransferObject =
+                                    (GeneratedTransferObject) innerGenTOs.get(typeName);
+                            if (genTransferObject != null) {
+                                updateUnionTypeAsProperty(unionGenTransObject,
+                                        genTransferObject,
+                                        genTransferObject.getName());
+                            }
+                        }
+                    } else if (unionType instanceof EnumTypeDefinition) {
+                        final EnumBuilder
+                                enumBuilder = resolveInnerEnumFromTypeDefinition(
+                                (EnumTypeDefinition) unionType, typeName,
+                                unionGenTransObject);
+                        final Type enumRefType = new ReferencedTypeImpl(
+                                enumBuilder.getPackageName(),
+                                enumBuilder.getName());
+                        updateUnionTypeAsProperty(unionGenTransObject,
+                                enumRefType, typeName);
+                    } else {
+                        final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+                                .javaTypeForSchemaDefinitionType(unionType);
+                        if (javaType != null) {
+                            updateUnionTypeAsProperty(unionGenTransObject,
+                                    javaType, typeName);
                         }
                     }
-                    genTOsMap.put(unionTypeDef.getQName().getLocalName(),
-                            unionGenTransObject.toInstance());
                 }
+                genTOsMap.put(typedef.getQName().getLocalName(),
+                        unionGenTransObject.toInstance());
+            }
+        }
+    }
+
+    private void updateUnionTypeAsProperty(
+            final GeneratedTOBuilder unionGenTransObject, final Type type,
+            final String propertyName) {
+        if (unionGenTransObject != null && type != null) {
+            final GeneratedPropertyBuilder propBuilder =
+                    unionGenTransObject.addProperty(parseToValidParamName(
+                            propertyName));
+            propBuilder.addReturnType(type);
+            propBuilder.setReadOnly(false);
+
+            if (!(type instanceof Enumeration)) {
+                unionGenTransObject.addEqualsIdentity(propBuilder);
+                unionGenTransObject.addHashIdentity(propBuilder);
+                unionGenTransObject.addToStringProperty(propBuilder);
             }
         }
     }
@@ -406,14 +573,13 @@ public class TypeProviderImpl implements TypeProvider {
     private GeneratedTOBuilder typedefToTransferObject(
             final String basePackageName, final TypeDefinition<?> typedef) {
 
-        final String packageName = BindingGeneratorUtil
-                .packageNameForGeneratedType(basePackageName, typedef.getPath());
+        final String packageName = packageNameForGeneratedType(basePackageName,
+                typedef.getPath());
         final String typeDefTOName = typedef.getQName().getLocalName();
 
         if ((packageName != null) && (typedef != null)
                 && (typeDefTOName != null)) {
-            final String genTOName = BindingGeneratorUtil
-                    .parseToClassName(typeDefTOName);
+            final String genTOName = parseToClassName(typeDefTOName);
             final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(
                     packageName, genTOName);
 
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/UnionDependencySort.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/UnionDependencySort.java
new file mode 100644 (file)
index 0000000..d19ac3f
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+ * 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.sal.binding.yang.types;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Function;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import org.opendaylight.controller.yang.model.api.TypeDefinition;
+import org.opendaylight.controller.yang.model.api.type.UnionTypeDefinition;
+import org.opendaylight.controller.yang.model.util.ExtendedType;
+import org.opendaylight.controller.yang.parser.util.TopologicalSort;
+import org.opendaylight.controller.yang.parser.util.TopologicalSort.Node;
+import org.opendaylight.controller.yang.parser.util.TopologicalSort.NodeImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class UnionDependencySort {
+    private static final Logger logger = LoggerFactory
+            .getLogger(UnionDependencySort.class);
+
+    public static List<ExtendedType> sort(
+            final Set<TypeDefinition<?>> typeDefinitions) {
+        if (typeDefinitions == null) {
+            logger.error("Set of Type Definitions cannot be NULL!");
+            throw new IllegalArgumentException("Set of Type Definitions " +
+                    "cannot be NULL!");
+        }
+
+        final Set<ExtendedType> extUnionTypes =
+                unionsFromTypeDefinitions(typeDefinitions);
+
+        final Set<Node> unsorted = unionTypesToUnionNodes(extUnionTypes);
+
+        final List<Node> sortedNodes = TopologicalSort.sort(unsorted);
+        return Lists.transform(sortedNodes, new Function<Node, ExtendedType>() {
+            @Override
+            public ExtendedType apply(Node input) {
+                return ((UnionNode) input).getUnionType();
+            }
+        });
+    }
+
+    private static Set<ExtendedType> unionsFromTypeDefinitions(
+            final Set<TypeDefinition<?>> typeDefinitions) {
+        final Set<ExtendedType> unions = Sets.newHashSet();
+
+        for (final TypeDefinition<?> typedef : typeDefinitions) {
+            if ((typedef != null) && (typedef.getBaseType() != null)) {
+                if (typedef instanceof ExtendedType
+                        && typedef.getBaseType() instanceof UnionTypeDefinition) {
+                    unions.add((ExtendedType) typedef);
+                }
+            }
+        }
+        return unions;
+    }
+
+    private static Set<Node> unionTypesToUnionNodes(
+            final Set<ExtendedType> extUnionTypes) {
+        final Map<ExtendedType, Node> nodeMap = Maps.newHashMap();
+        final Set<Node> resultNodes = Sets.newHashSet();
+
+        for (final ExtendedType unionType : extUnionTypes) {
+            final Node node = new UnionNode(unionType);
+            nodeMap.put(unionType, node);
+            resultNodes.add(node);
+        }
+
+        for (final Node node : resultNodes) {
+            final UnionNode unionNode = (UnionNode) node;
+            final ExtendedType extUnionType = unionNode.getUnionType();
+
+            final UnionTypeDefinition unionType = (UnionTypeDefinition)
+                    extUnionType.getBaseType();
+
+            final List<TypeDefinition<?>> innerTypes = unionType.getTypes();
+            for (final TypeDefinition<?> typedef : innerTypes) {
+                if (extUnionTypes.contains(typedef)) {
+                    final Node toNode = nodeMap.get(typedef);
+                    unionNode.addEdge(toNode);
+                }
+            }
+        }
+
+        return resultNodes;
+    }
+
+    private static UnionNode unionTypeToUnionNode(
+            final ExtendedType extUnionType,
+            final Set<ExtendedType> extUnionTypes) {
+        final UnionNode node = new UnionNode(extUnionType);
+
+        if (extUnionType.getBaseType() instanceof UnionTypeDefinition) {
+            final UnionTypeDefinition unionType = (UnionTypeDefinition)
+                    extUnionType.getBaseType();
+
+            final List<TypeDefinition<?>> innerTypes = unionType.getTypes();
+            for (final TypeDefinition<?> typedef : innerTypes) {
+                if ((typedef != null) && (typedef instanceof ExtendedType)
+                        && (typedef.getBaseType() instanceof UnionTypeDefinition)) {
+                    if (extUnionTypes.contains(typedef)) {
+                        node.addEdge(new UnionNode((ExtendedType) typedef));
+                    }
+                }
+            }
+        }
+
+        return node;
+    }
+
+    @VisibleForTesting
+    static final class UnionNode extends NodeImpl {
+        private final ExtendedType unionType;
+
+        UnionNode(ExtendedType unionType) {
+            this.unionType = unionType;
+        }
+
+        ExtendedType getUnionType() {
+            return unionType;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof UnionNode)) {
+                return false;
+            }
+            UnionNode unionNode = (UnionNode) o;
+            if (!unionType.equals(unionNode.unionType)) {
+                return false;
+            }
+            return true;
+        }
+
+        @Override
+        public int hashCode() {
+            return unionType.hashCode();
+        }
+
+        @Override
+        public String toString() {
+            return "UnionNode{" +
+                    "unionType=" + unionType +
+                    '}';
+        }
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/AugmentRleativeXPathTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/AugmentRleativeXPathTest.java
new file mode 100644 (file)
index 0000000..aac64e8
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * 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.sal.binding.generator.impl;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+public class AugmentRleativeXPathTest {
+
+    private final static List<File> augmentModels = new ArrayList<>();
+    private final static String augmentFolderPath = AugmentedTypeTest.class
+            .getResource("/augment-relative-xpath-models").getPath();
+
+    @BeforeClass
+    public static void loadTestResources() {
+        final File augFolder = new File(augmentFolderPath);
+
+        for (final File fileEntry : augFolder.listFiles()) {
+            if (fileEntry.isFile()) {
+                augmentModels.add(fileEntry);
+            }
+        }
+    }
+
+    @Test
+    public void AugmentationWithRelativeXPathTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(augmentModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        assertNotNull("context is null", context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+
+        assertNotNull("genTypes is null", genTypes);
+        assertFalse("genTypes is empty", genTypes.isEmpty());
+
+        //TODO: implement test
+    }
+}
index 448f610c49ba42265e080324c0ce0023c758b8f7..0fc4e43b0c4e299aef81c8d5d20990170f064bbc 100644 (file)
@@ -7,26 +7,22 @@
  */
 package org.opendaylight.controller.sal.binding.generator.impl;
 
-import static org.junit.Assert.*;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
-import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
-import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.*;
 import org.opendaylight.controller.yang.model.api.Module;
 import org.opendaylight.controller.yang.model.api.SchemaContext;
 import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
 import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
 
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.*;
+
 public class AugmentedTypeTest {
 
     private final static List<File> augmentModels = new ArrayList<>();
@@ -63,16 +59,16 @@ public class AugmentedTypeTest {
         GeneratedTransferObject gtTunnelKey = null;
         GeneratedType gtNetworkLink2 = null;
 
-        for(final Type type : genTypes) {
-            if(type.getName().equals("InterfaceKey") && type.getPackageName().contains("augment._abstract.topology")) {
+        for (final Type type : genTypes) {
+            if (type.getName().equals("InterfaceKey") && type.getPackageName().contains("augment._abstract.topology")) {
                 gtInterfaceKey = (GeneratedTransferObject) type;
-            } else if(type.getName().equals("Interface") && type.getPackageName().contains("augment._abstract.topology")) {
+            } else if (type.getName().equals("Interface") && type.getPackageName().contains("augment._abstract.topology")) {
                 gtInterface = (GeneratedType) type;
-            } else if(type.getName().equals("Tunnel") && type.getPackageName().contains("augment._abstract.topology")) {
+            } else if (type.getName().equals("Tunnel") && type.getPackageName().contains("augment._abstract.topology")) {
                 gtTunnel = (GeneratedType) type;
-            } else if(type.getName().equals("TunnelKey") && type.getPackageName().contains("augment._abstract.topology")) {
+            } else if (type.getName().equals("TunnelKey") && type.getPackageName().contains("augment._abstract.topology")) {
                 gtTunnelKey = (GeneratedTransferObject) type;
-            } else if(type.getName().equals("NetworkLink2") && type.getPackageName().contains("augment._abstract.topology")) {
+            } else if (type.getName().equals("NetworkLink2") && type.getPackageName().contains("augment._abstract.topology")) {
                 gtNetworkLink2 = (GeneratedType) type;
             }
         }
@@ -90,8 +86,10 @@ public class AugmentedTypeTest {
         }
         assertNotNull("getIfcKeyMethod is null", getIfcKeyMethod);
         assertNotNull("getIfcKeyMethod.getReturnType() is null", getIfcKeyMethod.getReturnType());
-        assertFalse("getIfcKeyMethod.getReturnType() should not be Void", getIfcKeyMethod.getReturnType().equals("java.lang.Void"));
-        assertTrue("getIfcKeyMethod.getReturnType().getName() must be InterfaceKey", getIfcKeyMethod.getReturnType().getName().equals("InterfaceKey"));
+        assertFalse("getIfcKeyMethod.getReturnType() should not be Void",
+                getIfcKeyMethod.getReturnType().equals("java.lang.Void"));
+        assertTrue("getIfcKeyMethod.getReturnType().getName() must be InterfaceKey",
+                getIfcKeyMethod.getReturnType().getName().equals("InterfaceKey"));
 
         MethodSignature getHigherLayerIfMethod = null;
         for (final MethodSignature method : gtInterfaceMethods) {
@@ -101,9 +99,12 @@ public class AugmentedTypeTest {
             }
         }
         assertNotNull("getHigherLayerIfMethod is null", getHigherLayerIfMethod);
-        assertNotNull("getHigherLayerIfMethod.getReturnType() is null", getHigherLayerIfMethod.getReturnType());
-        assertFalse("getHigherLayerIfMethod.getReturnType() should not be Void", getHigherLayerIfMethod.getReturnType().equals("java.lang.Void"));
-        assertTrue("getHigherLayerIfMethod.getReturnType().getName() must be List", getHigherLayerIfMethod.getReturnType().getName().equals("List"));
+        assertNotNull("getHigherLayerIfMethod.getReturnType() is null",
+                getHigherLayerIfMethod.getReturnType());
+        assertFalse("getHigherLayerIfMethod.getReturnType() should not be Void",
+                getHigherLayerIfMethod.getReturnType().equals("java.lang.Void"));
+        assertTrue("getHigherLayerIfMethod.getReturnType().getName() must be List",
+                getHigherLayerIfMethod.getReturnType().getName().equals("List"));
 
         // 'InterfaceKey'
         assertNotNull("gtInterfaceKey is null", gtInterfaceKey);
@@ -118,8 +119,10 @@ public class AugmentedTypeTest {
         }
         assertNotNull("gtInterfaceId is null", gtInterfaceId);
         assertNotNull("gtInterfaceId.getReturnType() is null", gtInterfaceId.getReturnType());
-        assertFalse("gtInterfaceId.getReturnType() should not be Void", gtInterfaceId.getReturnType().equals("java.lang.Void"));
-        assertTrue("gtInterfaceId.getReturnType().getName() must be String", gtInterfaceId.getReturnType().getName().equals("String"));
+        assertFalse("gtInterfaceId.getReturnType() should not be Void",
+                gtInterfaceId.getReturnType().equals("java.lang.Void"));
+        assertTrue("gtInterfaceId.getReturnType().getName() must be String",
+                gtInterfaceId.getReturnType().getName().equals("String"));
 
         // 'Tunnel'
         assertNotNull("gtTunnel is null", gtTunnel);
@@ -133,9 +136,12 @@ public class AugmentedTypeTest {
             }
         }
         assertNotNull("getTunnelKeyMethod is null", getTunnelKeyMethod);
-        assertNotNull("getTunnelKeyMethod.getReturnType()", getTunnelKeyMethod.getReturnType());
-        assertFalse("getTunnelKeyMethod.getReturnType() should not be Void", getTunnelKeyMethod.getReturnType().equals("java.lang.Void"));
-        assertTrue("getTunnelKeyMethod.getReturnType().getName() must be TunnelKey", getTunnelKeyMethod.getReturnType().getName().equals("TunnelKey"));
+        assertNotNull("getTunnelKeyMethod.getReturnType()",
+                getTunnelKeyMethod.getReturnType());
+        assertFalse("getTunnelKeyMethod.getReturnType() should not be Void",
+                getTunnelKeyMethod.getReturnType().equals("java.lang.Void"));
+        assertTrue("getTunnelKeyMethod.getReturnType().getName() must be TunnelKey",
+                getTunnelKeyMethod.getReturnType().getName().equals("TunnelKey"));
 
         // 'TunnelKey'
         assertNotNull("gtTunnelKey is null", gtTunnelKey);
@@ -149,9 +155,12 @@ public class AugmentedTypeTest {
             }
         }
         assertNotNull("gtTunnelId is null", gtTunnelId);
-        assertNotNull("gtTunnelId.getReturnType() is null", gtTunnelId.getReturnType());
-        assertFalse("gtTunnelId.getReturnType() should not be Void", gtTunnelId.getReturnType().equals("java.lang.Void"));
-        assertTrue("gtTunnelId.getReturnType().getName() must be Integer", gtTunnelId.getReturnType().getName().equals("Integer"));
+        assertNotNull("gtTunnelId.getReturnType() is null",
+                gtTunnelId.getReturnType());
+        assertFalse("gtTunnelId.getReturnType() should not be Void",
+                gtTunnelId.getReturnType().equals("java.lang.Void"));
+        assertTrue("gtTunnelId.getReturnType().getName() must be Integer",
+                gtTunnelId.getReturnType().getName().equals("Integer"));
 
         // 'NetworkLink2'
         assertNotNull("gtNetworkLink2 is null", gtNetworkLink2);
@@ -160,21 +169,18 @@ public class AugmentedTypeTest {
         assertNotNull("networkLink2Methods is null", networkLink2Methods);
 
 //        FIXME: in some cases getIfcMethod is null which causes test fail. fix ASAP
-//        MethodSignature getIfcMethod = null;
-//        for (MethodSignature method : networkLink2Methods) {
-//            if (method.getName().equals("getInterface")) {
-//                getIfcMethod = method;
-//                break;
-//            }
-//        }
+//      MethodSignature getIfcMethod = null;
+//      for (MethodSignature method : networkLink2Methods) {
+//          if (method.getName().equals("getInterface")) {
+//              getIfcMethod = method;
+//              break;
+//          }
+//      }
 //
-//        assertNotNull("getIfcMethod is null", getIfcMethod);
-//        assertNotNull("getIfcMethod.getReturnType() is null",
-//                getIfcMethod.getReturnType());
-//        assertFalse("getIfcMethod.getReturnType() should not be Void",
-//                getIfcMethod.getReturnType().equals("java.lang.Void"));
-//        assertTrue("getIfcMethod.getReturnType().getName() must be String",
-//                getIfcMethod.getReturnType().getName().equals("String"));
+//      assertNotNull("getIfcMethod is null", getIfcMethod);
+//      assertNotNull("getIfcMethod.getReturnType() is null", getIfcMethod.getReturnType());
+//      assertFalse("getIfcMethod.getReturnType() should not be Void", getIfcMethod.getReturnType().equals("java.lang.Void"));
+//      assertTrue("getIfcMethod.getReturnType().getName() must be String", getIfcMethod.getReturnType().getName().equals("String"));
     }
 
     @Test
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/BinaryTypeTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/BinaryTypeTest.java
new file mode 100644 (file)
index 0000000..a3d2d27
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+* 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.sal.binding.generator.impl;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+public class BinaryTypeTest {
+    private final static List<File> yangModels = new ArrayList<>();
+    private final static String yangModelsFolder = AugmentedTypeTest.class
+            .getResource("/binary-type-test-models").getPath();
+
+    @BeforeClass
+    public static void loadTestResources() {
+        final File augFolder = new File(yangModelsFolder);
+        for (final File fileEntry : augFolder.listFiles()) {
+            if (fileEntry.isFile()) {
+                yangModels.add(fileEntry);
+            }
+        }
+    }
+
+    @Test
+    public void binaryTypeTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(yangModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        assertNotNull("context is null", context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+
+        assertNotNull("genTypes is null", genTypes);
+        assertFalse("genTypes is empty", genTypes.isEmpty());
+
+        //TODO: implement test
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenEnumResolvingTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenEnumResolvingTest.java
new file mode 100644 (file)
index 0000000..a95eb07
--- /dev/null
@@ -0,0 +1,213 @@
+/*
+ * 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.sal.binding.generator.impl;
+
+import org.junit.Test;
+import org.opendaylight.controller.binding.generator.util.ReferencedTypeImpl;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
+import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+public class GenEnumResolvingTest {
+
+    private SchemaContext resolveSchemaContextFromFiles(
+            final String... yangFiles) {
+        final YangModelParser parser = new YangParserImpl();
+
+        final List<File> inputFiles = new ArrayList<File>();
+        for (int i = 0; i < yangFiles.length; ++i) {
+            inputFiles.add(new File(yangFiles[i]));
+        }
+
+        final Set<Module> modules = parser.parseYangModels(inputFiles);
+        return parser.resolveSchemaContext(modules);
+    }
+
+    @Test
+    public void testLeafEnumResolving() {
+        final String ietfInterfacesPath = getClass().getResource(
+                "/enum-test-models/ietf-interfaces@2012-11-15.yang").getPath();
+        final String ifTypePath = getClass().getResource(
+                "/enum-test-models/iana-if-type@2012-06-05.yang").getPath();
+        final String yangTypesPath = getClass().getResource(
+                "/enum-test-models/ietf-yang-types@2010-09-24.yang").getPath();
+
+        final SchemaContext context = resolveSchemaContextFromFiles(
+                ietfInterfacesPath, ifTypePath, yangTypesPath);
+        assertTrue(context != null);
+
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+        assertTrue(genTypes != null);
+
+        assertEquals("Expected count of all Generated Types from yang models " +
+                "is 22", 25, genTypes.size());
+
+        GeneratedType genInterface = null;
+        for (final Type type : genTypes) {
+            if (type instanceof GeneratedType) {
+                if (type.getName().equals("Interface")) {
+                    genInterface = (GeneratedType) type;
+                }
+            }
+        }
+        assertNotNull("Generated Type Interface is not present in list of " +
+                "Generated Types", genInterface);
+
+        Enumeration linkUpDownTrapEnable = null;
+        Enumeration operStatus = null;
+        final List<Enumeration> enums = genInterface.getEnumDefintions();
+        assertNotNull("Generated Type Interface cannot contain NULL reference" +
+                " to Enumeration types!", enums);
+        assertEquals("Generated Type Interface MUST contain 2 Enumeration " +
+                "Types", 2, enums.size());
+        for (final Enumeration e : enums) {
+            if (e.getName().equals("LinkUpDownTrapEnable")) {
+                linkUpDownTrapEnable = e;
+            } else if (e.getName().equals("OperStatus")) {
+                operStatus = e;
+            }
+        }
+
+        assertNotNull("Expected Enum LinkUpDownTrapEnable, but was NULL!",
+                linkUpDownTrapEnable);
+        assertNotNull("Expected Enum OperStatus, but was NULL!", operStatus);
+
+        assertNotNull("Enum LinkUpDownTrapEnable MUST contain Values definition " +
+                "not NULL reference!", linkUpDownTrapEnable.getValues());
+        assertNotNull("Enum OperStatus MUST contain Values definition not " +
+                "NULL reference!", operStatus.getValues());
+        assertEquals("Enum LinkUpDownTrapEnable MUST contain 2 values!", 2,
+                linkUpDownTrapEnable.getValues().size());
+        assertEquals("Enum OperStatus MUST contain 7 values!", 7,
+                operStatus.getValues().size());
+
+        final List<MethodSignature> methods = genInterface
+                .getMethodDefinitions();
+
+        assertNotNull("Generated Interface cannot contain NULL reference for " +
+                "Method Signature Definitions!", methods);
+
+        assertEquals("Expected count of method signature definitions is 26",
+                26, methods.size());
+        Enumeration ianaIfType = null;
+        for (final MethodSignature method : methods) {
+            if (method.getName().equals("getType")) {
+                if (method.getReturnType() instanceof Enumeration) {
+                    ianaIfType = (Enumeration)method.getReturnType();
+                }
+            }
+        }
+
+        assertNotNull("Method getType MUST return Enumeration Type, " +
+                "not NULL reference!", ianaIfType);
+        assertEquals("Enumeration getType MUST contain 272 values!", 272,
+                ianaIfType.getValues().size());
+    }
+
+    @Test
+    public void testTypedefEnumResolving() {
+        final String ianaIfTypePath = getClass().getResource(
+                "/leafref-test-models/iana-if-type@2012-06-05.yang").getPath();
+
+        final SchemaContext context = resolveSchemaContextFromFiles(ianaIfTypePath);
+        assertTrue(context != null);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+        assertTrue(genTypes != null);
+        assertEquals(3, genTypes.size());
+
+        final Type type = genTypes.get(1);
+        assertTrue(type instanceof Enumeration);
+
+        final Enumeration enumer = (Enumeration) type;
+        assertEquals("Enumeration type MUST contain 272 values!", 272,
+                enumer.getValues().size());
+    }
+
+    @Test
+    public void testLeafrefEnumResolving() {
+        final String ietfInterfacesPath = getClass().getResource(
+                "/enum-test-models/ietf-interfaces@2012-11-15.yang").getPath();
+        final String ifTypePath = getClass().getResource(
+                "/enum-test-models/iana-if-type@2012-06-05.yang").getPath();
+        final String yangTypesPath = getClass().getResource(
+                "/enum-test-models/ietf-yang-types@2010-09-24.yang").getPath();
+        final String topologyPath = getClass().getResource(
+                "/enum-test-models/abstract-topology@2013-02-08.yang")
+                .getPath();
+        final String inetTypesPath = getClass().getResource(
+                "/enum-test-models/ietf-inet-types@2010-09-24.yang")
+                .getPath();
+        final SchemaContext context = resolveSchemaContextFromFiles(
+                ietfInterfacesPath, ifTypePath, yangTypesPath, topologyPath,
+                inetTypesPath);
+
+        assertNotNull(context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+        assertNotNull(genTypes);
+        assertTrue(!genTypes.isEmpty());
+
+        GeneratedType genInterface = null;
+        for (final Type type : genTypes) {
+            if (type instanceof GeneratedType) {
+                if (type.getPackageName().equals("org.opendaylight.yang.gen.v1.urn.model._abstract.topology.rev201328.topology.interfaces")
+                        && type.getName().equals("Interface")) {
+                    genInterface = (GeneratedType) type;
+                }
+            }
+        }
+        assertNotNull("Generated Type Interface is not present in list of " +
+                "Generated Types", genInterface);
+
+        Type linkUpDownTrapEnable = null;
+        Type operStatus = null;
+        final List<MethodSignature> methods = genInterface.getMethodDefinitions();
+        assertNotNull("Generated Type Interface cannot contain NULL reference" +
+                " to Enumeration types!", methods);
+        assertEquals("Generated Type Interface MUST contain 7 Methods ",
+                7, methods.size());
+        for (final MethodSignature method : methods) {
+            if (method.getName().equals("getLinkUpDownTrapEnable")) {
+                linkUpDownTrapEnable = method.getReturnType();
+            } else if (method.getName().equals("getOperStatus")) {
+                operStatus = method.getReturnType();
+            }
+        }
+
+        assertNotNull("Expected Referenced Enum LinkUpDownTrapEnable, but was NULL!",
+                linkUpDownTrapEnable);
+        assertTrue("Expected LinkUpDownTrapEnable of type ReferencedTypeImpl",
+                linkUpDownTrapEnable instanceof ReferencedTypeImpl);
+        assertEquals(linkUpDownTrapEnable.getPackageName(),
+                "org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev20121115.interfaces.Interface");
+
+        assertNotNull("Expected Referenced Enum OperStatus, but was NULL!",
+                operStatus);
+        assertTrue("Expected OperStatus of type ReferencedTypeImpl",
+                operStatus instanceof  ReferencedTypeImpl);
+        assertEquals(operStatus.getPackageName(),
+                "org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev20121115.interfaces.Interface");
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenTypesSubSetTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenTypesSubSetTest.java
new file mode 100644 (file)
index 0000000..16eff0b
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * 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.sal.binding.generator.impl;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+import java.io.File;
+import java.util.*;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+public class GenTypesSubSetTest {
+
+    private final static List<File> yangModels = new ArrayList<>();
+    private final static String yangModelsFolder = AugmentedTypeTest.class
+            .getResource("/leafref-test-models").getPath();
+
+    @BeforeClass
+    public static void loadTestResources() {
+        final File augFolder = new File(yangModelsFolder);
+
+        for (final File fileEntry : augFolder.listFiles()) {
+            if (fileEntry.isFile()) {
+                yangModels.add(fileEntry);
+            }
+        }
+    }
+
+    @Test
+    public void genTypesFromSubsetOfTwoModulesTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(yangModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        final Set<Module> toGenModules = new HashSet<>();
+        for (final Module module : modules) {
+            if (module.getName().equals("abstract-topology")) {
+                toGenModules.add(module);
+            } else if (module.getName().equals("ietf-interfaces")) {
+                toGenModules.add(module);
+            }
+        }
+
+        assertEquals("Set of to Generate Modules must contain 2 modules", 2,
+                toGenModules.size());
+        assertNotNull("Schema Context is null", context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context, toGenModules);
+        assertNotNull("genTypes is null", genTypes);
+        assertFalse("genTypes is empty", genTypes.isEmpty());
+        assertEquals("Expected Generated Types from provided sub set of " +
+                "modules should be 23!", 25,
+                genTypes.size());
+    }
+
+    @Test
+    public void genTypesFromSubsetOfThreeModulesTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(yangModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        final Set<Module> toGenModules = new HashSet<>();
+        for (final Module module : modules) {
+            if (module.getName().equals("abstract-topology")) {
+                toGenModules.add(module);
+            } else if (module.getName().equals("ietf-interfaces")) {
+                toGenModules.add(module);
+            } else if (module.getName().equals("iana-if-type")) {
+                toGenModules.add(module);
+            }
+        }
+
+        assertEquals("Set of to Generate Modules must contain 3 modules", 3,
+                toGenModules.size());
+
+        assertNotNull("Schema Context is null", context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context, toGenModules);
+        assertNotNull("genTypes is null", genTypes);
+        assertFalse("genTypes is empty", genTypes.isEmpty());
+        assertEquals("Expected Generated Types from provided sub set of "  +
+                "modules should be 25!", 28, genTypes.size());
+    }
+}
index 66c293eebc5beadf52cb7614dacf5f5bad2a5c4e..b226252eaea7a635cace166cb3721f307725058a 100644 (file)
@@ -42,53 +42,6 @@ public class GeneratedTypesTest {
         return parser.resolveSchemaContext(modules);
     }
 
-    @Test
-    public void testLeafEnumResolving() {
-        final String ietfInterfacesPath = getClass().getResource(
-                "/enum-test-models/ietf-interfaces@2012-11-15.yang").getPath();
-        final String ifTypePath = getClass().getResource(
-                "/enum-test-models/iana-if-type@2012-06-05.yang").getPath();
-        final String yangTypesPath = getClass().getResource(
-                "/enum-test-models/ietf-yang-types@2010-09-24.yang").getPath();
-
-        final SchemaContext context = resolveSchemaContextFromFiles(
-                ietfInterfacesPath, ifTypePath, yangTypesPath);
-        assertTrue(context != null);
-
-        final BindingGenerator bindingGen = new BindingGeneratorImpl();
-        final List<Type> genTypes = bindingGen.generateTypes(context);
-        assertTrue(genTypes != null);
-    }
-
-    @Test
-    public void testTypedefEnumResolving() {
-        final String ianaIfTypePath = getClass().getResource(
-                "/leafref-test-models/iana-if-type@2012-06-05.yang").getPath();
-
-        final SchemaContext context = resolveSchemaContextFromFiles(ianaIfTypePath);
-        assertTrue(context != null);
-        final BindingGenerator bindingGen = new BindingGeneratorImpl();
-        final List<Type> genTypes = bindingGen.generateTypes(context);
-        assertTrue(genTypes != null);
-        assertEquals(2, genTypes.size());
-
-        final Type type = genTypes.get(1);
-        assertTrue(type instanceof GeneratedTransferObject);
-
-        final GeneratedTransferObject genTransObj = (GeneratedTransferObject) type;
-        final List<GeneratedProperty> properties = genTransObj.getProperties();
-        assertNotNull(properties);
-        assertEquals(1, properties.size());
-
-        GeneratedProperty property = properties.get(0);
-        assertNotNull(property);
-        assertNotNull(property.getReturnType());
-
-        assertTrue(property.getReturnType() instanceof Enumeration);
-        final Enumeration enumer = (Enumeration) property.getReturnType();
-        assertEquals(272, enumer.getValues().size());
-    }
-
     @Test
     public void testMultipleModulesResolving() {
         final String topologyPath = getClass().getResource(
@@ -103,7 +56,7 @@ public class GeneratedTypesTest {
         final List<Type> genTypes = bindingGen.generateTypes(context);
 
         assertTrue(genTypes != null);
-        assertEquals(24, genTypes.size());
+        assertEquals(29, genTypes.size());
     }
 
     @Test
@@ -140,7 +93,7 @@ public class GeneratedTypesTest {
         final BindingGenerator bindingGen = new BindingGeneratorImpl();
         final List<Type> genTypes = bindingGen.generateTypes(context);
 
-        assertEquals(50, genTypes.size());
+        assertEquals(57, genTypes.size());
         assertTrue(genTypes != null);
 
         GeneratedTransferObject gtIfcKey = null;
@@ -308,10 +261,10 @@ public class GeneratedTypesTest {
         final List<Type> genTypes = bindingGen.generateTypes(context);
 
         assertTrue(genTypes != null);
-        assertEquals(3, genTypes.size());
+        assertEquals(4, genTypes.size());
 
-        final GeneratedType simpleContainer = (GeneratedType) genTypes.get(0);
-        final GeneratedType nestedContainer = (GeneratedType) genTypes.get(1);
+        final GeneratedType simpleContainer = (GeneratedType) genTypes.get(1);
+        final GeneratedType nestedContainer = (GeneratedType) genTypes.get(2);
 
         assertEquals("SimpleContainer", simpleContainer.getName());
         assertEquals("NestedContainer", nestedContainer.getName());
@@ -386,10 +339,10 @@ public class GeneratedTypesTest {
         final List<Type> genTypes = bindingGen.generateTypes(context);
 
         assertTrue(genTypes != null);
-        assertEquals(3, genTypes.size());
+        assertEquals(4, genTypes.size());
 
-        final GeneratedType simpleContainer = (GeneratedType) genTypes.get(0);
-        final GeneratedType nestedContainer = (GeneratedType) genTypes.get(1);
+        final GeneratedType simpleContainer = (GeneratedType) genTypes.get(1);
+        final GeneratedType nestedContainer = (GeneratedType) genTypes.get(2);
 
         assertEquals("SimpleContainer", simpleContainer.getName());
         assertEquals("NestedContainer", nestedContainer.getName());
@@ -459,7 +412,7 @@ public class GeneratedTypesTest {
         final List<Type> genTypes = bindingGen.generateTypes(context);
 
         assertTrue(genTypes != null);
-        assertEquals(5, genTypes.size());
+        assertEquals(6, genTypes.size());
 
         int genTypesCount = 0;
         int genTOsCount = 0;
@@ -543,7 +496,7 @@ public class GeneratedTypesTest {
         final List<Type> genTypes = bindingGen.generateTypes(context);
 
         assertTrue(genTypes != null);
-        assertEquals(7, genTypes.size());
+        assertEquals(8, genTypes.size());
 
         int genTypesCount = 0;
         int genTOsCount = 0;
@@ -576,7 +529,7 @@ public class GeneratedTypesTest {
             }
         }
 
-        assertEquals(5, genTypesCount);
+        assertEquals(6, genTypesCount);
         assertEquals(2, genTOsCount);
     }
 
@@ -591,7 +544,7 @@ public class GeneratedTypesTest {
         final List<Type> genTypes = bindingGen.generateTypes(context);
 
         assertTrue(genTypes != null);
-        assertEquals(14, genTypes.size());
+        assertEquals(15, genTypes.size());
 
         int genTypesCount = 0;
         int genTOsCount = 0;
@@ -604,7 +557,7 @@ public class GeneratedTypesTest {
             }
         }
 
-        assertEquals(11, genTypesCount);
+        assertEquals(12, genTypesCount);
         assertEquals(3, genTOsCount);
     }
 }
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/UnionTypeDefTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/UnionTypeDefTest.java
new file mode 100644 (file)
index 0000000..7ff6283
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * 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.sal.binding.generator.impl;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+public class UnionTypeDefTest {
+    private final static List<File> yangModels = new ArrayList<>();
+    private final static String yangModelsFolder = AugmentedTypeTest.class
+            .getResource("/union-test-models").getPath();
+
+    @BeforeClass
+    public static void loadTestResources() {
+        final File augFolder = new File(yangModelsFolder);
+
+        for (final File fileEntry : augFolder.listFiles()) {
+            if (fileEntry.isFile()) {
+                yangModels.add(fileEntry);
+            }
+        }
+    }
+
+    @Test
+    public void unionTypeResolvingTest() {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModels(yangModels);
+        final SchemaContext context = parser.resolveSchemaContext(modules);
+
+        assertNotNull("context is null", context);
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+
+        assertNotNull("genTypes is null", genTypes);
+        assertFalse("genTypes is empty", genTypes.isEmpty());
+
+        //TODO: implement test
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/abstract-topology@2013-02-08.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/abstract-topology@2013-02-08.yang
new file mode 100644 (file)
index 0000000..d80a3e9
--- /dev/null
@@ -0,0 +1,101 @@
+module abstract-topology {
+    yang-version 1;
+    namespace "urn:model:abstract:topology";
+    prefix "tp";
+
+    import ietf-inet-types { 
+        prefix "inet"; 
+        revision-date 2010-09-24;
+    }
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    description
+        "This module contains the definitions of elements that creates network 
+    topology i.e. definition of network nodes and links. This module is not designed 
+    to be used solely for network representation. This module SHOULD be used as base 
+    module in defining the network topology.";
+
+    revision "2013-02-08" {
+        reference "http://www.opendaylight.org/";
+    }
+    
+    typedef node-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-nodes/tp:network-node/tp:node-id";
+        }
+        description "This type is used for leafs that reference network node instance.";
+    }
+
+    typedef link-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-links/tp:network-link/tp:link-id";
+        }
+        description "This type is used for leafs that reference network link instance.";
+    }
+
+    container topology {
+        description "This is the model of abstract topology which contains 
+        only Network Nodes and Network Links. Each topology MUST be identified by unique 
+        topology-id for reason that the store could contain many topologies.";
+
+        leaf topology-id {
+            type inet:uri;
+            description "It is presumed that datastore will contain many topologies. 
+            To distinguish between topologies it is vital to have
+            UNIQUE topology identifier.";
+        }
+
+        container network-nodes {
+            list network-node {
+                key "node-id";
+
+                leaf node-id {
+                    type inet:uri;
+                    description "The Topology identifier of network-node.";
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Node contains.";
+                }
+                description "The list of network nodes defined for topology.";
+            }
+        }
+        
+        container network-links {
+            list network-link {
+                key "link-id";
+
+                leaf link-id {
+                    type inet:uri;
+                    description "";
+                }
+
+                container source-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Source node identifier.";
+                    }
+                }
+
+                container destination-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Destination node identifier.";
+                    }
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Link contains.";
+                }
+                description "The Network Link which is defined by Local (Source) and Remote (Destination) 
+                Network Nodes. Every link MUST be defined either by identifier and
+                his local and remote Network Nodes (In real applications it is common that 
+                many links are originated from one node and end up in same remote node). 
+                To ensure that we would always know to distinguish between links, every link 
+                SHOULD have identifier.";
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/augment-abstract-topology@2013-05-03.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/augment-abstract-topology@2013-05-03.yang
new file mode 100644 (file)
index 0000000..051b2d9
--- /dev/null
@@ -0,0 +1,69 @@
+module augment-abstract-topology {
+    yang-version 1;
+    namespace "urn:model:augment:abstract:topology";
+    prefix "atp";
+
+    import ietf-inet-types { 
+        prefix "inet";
+        revision-date 2010-09-24;
+    }
+
+    import ietf-interfaces {
+        prefix "if";
+        revision-date 2012-11-15;
+    }
+
+    import abstract-topology {
+        prefix "at";
+        revision-date 2013-02-08;
+    }
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    revision "2013-05-03" {
+        reference "http://www.opendaylight.org/";
+    }
+
+    augment "at:topology" {
+        container interfaces {
+            list interface {
+                key "interface-id";
+
+                leaf interface-id {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:name";
+                    }
+                }
+
+                leaf-list higher-layer-if {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:higher-layer-if";
+                    }
+                }
+            }
+        }
+    }
+
+    augment "at:topology/at:network-links/at:network-link" {
+        container tunnels {
+            list tunnel {
+                key "tunnel-id";
+
+                leaf tunnel-id {
+                    type leafref {
+                        path "../../../link-id";
+                    }
+                }
+            }
+        }
+    }
+
+    augment "at:topology/at:network-links/at:network-link" {
+        leaf interface {
+            type leafref {
+                path "../../../atp:interfaces/atp:interface/atp:interface-id";
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/iana-if-type@2012-06-05.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/iana-if-type@2012-06-05.yang
new file mode 100644 (file)
index 0000000..a7fa137
--- /dev/null
@@ -0,0 +1,1516 @@
+module iana-if-type {
+  namespace "urn:ietf:params:xml:ns:yang:iana-if-type";
+  prefix ianaift;
+
+  organization "IANA";
+  contact
+    "        Internet Assigned Numbers Authority
+
+     Postal: ICANN
+             4676 Admiralty Way, Suite 330
+             Marina del Rey, CA 90292
+
+     Tel:    +1 310 823 9358
+     E-Mail: iana&iana.org";
+  description
+    "This YANG module defines the iana-if-type typedef, which
+     contains YANG definitions for IANA-registered interface types.
+
+     This YANG module is maintained by IANA, and reflects the
+     'ifType definitions' registry.
+
+     The latest revision of this YANG module can be obtained from
+     the IANA web site.
+
+     Copyright (c) 2011 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or
+     without modification, is permitted pursuant to, and subject
+     to the license terms contained in, the Simplified BSD License
+     set forth in Section 4.c of the IETF Trust's Legal Provisions
+     Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC XXXX; see
+     the RFC itself for full legal notices.";
+  // RFC Ed.: replace XXXX with actual RFC number and remove this
+  // note.
+
+  // RFC Ed.: update the date below with the date of RFC publication
+  // and remove this note.
+  revision 2012-06-05 {
+    description
+      "Initial revision.";
+    reference
+      "RFC XXXX: TITLE";
+  }
+
+  typedef iana-if-type {
+    type enumeration {
+      enum "other" {
+        value 1;
+        description
+          "None of the following";
+      }
+      enum "regular1822" {
+        value 2;
+      }
+      enum "hdh1822" {
+        value 3;
+      }
+      enum "ddnX25" {
+        value 4;
+      }
+      enum "rfc877x25" {
+        value 5;
+        reference
+          "RFC 1382 - SNMP MIB Extension for the X.25 Packet Layer";
+      }
+      enum "ethernetCsmacd" {
+        value 6;
+        description
+          "For all ethernet-like interfaces, regardless of speed,
+           as per RFC3635.";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "iso88023Csmacd" {
+        value 7;
+        status deprecated;
+        description
+          "Deprecated via RFC3635.
+           Use ethernetCsmacd(6) instead.";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "iso88024TokenBus" {
+        value 8;
+      }
+      enum "iso88025TokenRing" {
+        value 9;
+      }
+      enum "iso88026Man" {
+        value 10;
+      }
+      enum "starLan" {
+        value 11;
+        status deprecated;
+        description
+          "Deprecated via RFC3635.
+           Use ethernetCsmacd(6) instead.";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "proteon10Mbit" {
+        value 12;
+      }
+      enum "proteon80Mbit" {
+        value 13;
+      }
+      enum "hyperchannel" {
+        value 14;
+      }
+      enum "fddi" {
+        value 15;
+        reference
+          "RFC 1512 - FDDI Management Information Base";
+      }
+      enum "lapb" {
+        value 16;
+        reference
+          "RFC 1381 - SNMP MIB Extension for X.25 LAPB";
+      }
+      enum "sdlc" {
+        value 17;
+      }
+      enum "ds1" {
+        value 18;
+        description
+          "DS1-MIB";
+        reference
+          "RFC 4805 - Definitions of Managed Objects for the
+                      DS1, J1, E1, DS2, and E2 Interface Types";
+      }
+      enum "e1" {
+        value 19;
+        status obsolete;
+        description
+          "Obsolete see DS1-MIB";
+        reference
+          "RFC 4805 - Definitions of Managed Objects for the
+                      DS1, J1, E1, DS2, and E2 Interface Types";
+      }
+      enum "basicISDN" {
+        value 20;
+        description
+          "see also RFC2127";
+      }
+      enum "primaryISDN" {
+        value 21;
+      }
+      enum "propPointToPointSerial" {
+        value 22;
+        description
+          "proprietary serial";
+      }
+      enum "ppp" {
+        value 23;
+      }
+      enum "softwareLoopback" {
+        value 24;
+      }
+      enum "eon" {
+        value 25;
+        description
+          "CLNP over IP";
+      }
+      enum "ethernet3Mbit" {
+        value 26;
+      }
+      enum "nsip" {
+        value 27;
+        description
+          "XNS over IP";
+      }
+      enum "slip" {
+        value 28;
+        description
+          "generic SLIP";
+      }
+      enum "ultra" {
+        value 29;
+        description
+          "ULTRA technologies";
+      }
+      enum "ds3" {
+        value 30;
+        description
+          "DS3-MIB";
+        reference
+          "RFC 3896 - Definitions of Managed Objects for the
+                      DS3/E3 Interface Type";
+      }
+      enum "sip" {
+        value 31;
+        description
+          "SMDS, coffee";
+        reference
+          "RFC 1694 - Definitions of Managed Objects for SMDS
+                      Interfaces using SMIv2";
+      }
+      enum "frameRelay" {
+        value 32;
+        description
+          "DTE only.";
+        reference
+          "RFC 2115 - Management Information Base for Frame Relay
+                      DTEs Using SMIv2";
+      }
+      enum "rs232" {
+        value 33;
+        reference
+          "RFC 1659 - Definitions of Managed Objects for RS-232-like
+                      Hardware Devices using SMIv2";
+      }
+      enum "para" {
+        value 34;
+        description
+          "parallel-port";
+        reference
+          "RFC 1660 - Definitions of Managed Objects for
+                      Parallel-printer-like Hardware Devices using
+                      SMIv2";
+      }
+      enum "arcnet" {
+        value 35;
+        description
+          "arcnet";
+      }
+      enum "arcnetPlus" {
+        value 36;
+        description
+          "arcnet plus";
+      }
+      enum "atm" {
+        value 37;
+        description
+          "ATM cells";
+      }
+      enum "miox25" {
+        value 38;
+        reference
+          "RFC 1461 - SNMP MIB extension for Multiprotocol
+                      Interconnect over X.25";
+      }
+      enum "sonet" {
+        value 39;
+        description
+          "SONET or SDH";
+      }
+      enum "x25ple" {
+        value 40;
+        reference
+          "RFC 2127 - ISDN Management Information Base using SMIv2";
+      }
+      enum "iso88022llc" {
+        value 41;
+      }
+      enum "localTalk" {
+        value 42;
+      }
+      enum "smdsDxi" {
+        value 43;
+      }
+      enum "frameRelayService" {
+        value 44;
+        description
+          "FRNETSERV-MIB";
+        reference
+          "RFC 2954 - Definitions of Managed Objects for Frame
+                      Relay Service";
+      }
+      enum "v35" {
+        value 45;
+      }
+      enum "hssi" {
+        value 46;
+      }
+      enum "hippi" {
+        value 47;
+      }
+      enum "modem" {
+        value 48;
+        description
+          "Generic modem";
+      }
+      enum "aal5" {
+        value 49;
+        description
+          "AAL5 over ATM";
+      }
+      enum "sonetPath" {
+        value 50;
+      }
+      enum "sonetVT" {
+        value 51;
+      }
+      enum "smdsIcip" {
+        value 52;
+        description
+          "SMDS InterCarrier Interface";
+      }
+      enum "propVirtual" {
+        value 53;
+        description
+          "proprietary virtual/internal";
+        reference
+          "RFC 2863 - The Interfaces Group MIB";
+      }
+      enum "propMultiplexor" {
+        value 54;
+        description
+          "proprietary multiplexing";
+        reference
+          "RFC 2863 - The Interfaces Group MIB";
+      }
+      enum "ieee80212" {
+        value 55;
+        description
+          "100BaseVG";
+      }
+      enum "fibreChannel" {
+        value 56;
+        description
+          "Fibre Channel";
+      }
+      enum "hippiInterface" {
+        value 57;
+        description
+          "HIPPI interfaces";
+      }
+      enum "frameRelayInterconnect" {
+        value 58;
+        status obsolete;
+        description
+          "Obsolete use either
+           frameRelay(32) or frameRelayService(44).";
+      }
+      enum "aflane8023" {
+        value 59;
+        description
+          "ATM Emulated LAN for 802.3";
+      }
+      enum "aflane8025" {
+        value 60;
+        description
+          "ATM Emulated LAN for 802.5";
+      }
+      enum "cctEmul" {
+        value 61;
+        description
+         "ATM Emulated circuit";
+      }
+      enum "fastEther" {
+        value 62;
+        status deprecated;
+        description
+          "Obsoleted via RFC3635.
+          ethernetCsmacd(6) should be used instead";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "isdn" {
+        value 63;
+        description
+          "ISDN and X.25";
+        reference
+          "RFC 1356 - Multiprotocol Interconnect on X.25 and ISDN
+                      in the Packet Mode";
+      }
+      enum "v11" {
+        value 64;
+        description
+         "CCITT V.11/X.21";
+      }
+      enum "v36" {
+        value 65;
+        description
+          "CCITT V.36";
+      }
+      enum "g703at64k" {
+        value 66;
+        description
+          "CCITT G703 at 64Kbps";
+      }
+      enum "g703at2mb" {
+        value 67;
+        status obsolete;
+        description
+          "Obsolete see DS1-MIB";
+      }
+      enum "qllc" {
+        value 68;
+        description
+          "SNA QLLC";
+      }
+      enum "fastEtherFX" {
+        value 69;
+        status deprecated;
+        description
+          "Obsoleted via RFC3635
+          ethernetCsmacd(6) should be used instead";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "channel" {
+        value 70;
+        description
+          "channel";
+      }
+      enum "ieee80211" {
+        value 71;
+        description
+          "radio spread spectrum";
+      }
+      enum "ibm370parChan" {
+        value 72;
+        description
+          "IBM System 360/370 OEMI Channel";
+      }
+      enum "escon" {
+        value 73;
+        description
+          "IBM Enterprise Systems Connection";
+      }
+      enum "dlsw" {
+        value 74;
+        description
+          "Data Link Switching";
+      }
+      enum "isdns" {
+        value 75;
+        description
+          "ISDN S/T interface";
+      }
+      enum "isdnu" {
+        value 76;
+        description
+          "ISDN U interface";
+      }
+      enum "lapd" {
+        value 77;
+        description
+          "Link Access Protocol D";
+      }
+      enum "ipSwitch" {
+        value 78;
+        description
+          "IP Switching Objects";
+      }
+      enum "rsrb" {
+        value 79;
+        description
+          "Remote Source Route Bridging";
+      }
+      enum "atmLogical" {
+        value 80;
+        description
+          "ATM Logical Port";
+        reference
+          "RFC 3606 - Definitions of Supplemental Managed Objects
+                      for ATM Interface";
+      }
+      enum "ds0" {
+        value 81;
+        description
+          "Digital Signal Level 0";
+        reference
+          "RFC 2494 - Definitions of Managed Objects for the DS0
+                      and DS0 Bundle Interface Type";
+      }
+      enum "ds0Bundle" {
+        value 82;
+        description
+          "group of ds0s on the same ds1";
+        reference
+          "RFC 2494 - Definitions of Managed Objects for the DS0
+                      and DS0 Bundle Interface Type";
+      }
+      enum "bsc" {
+        value 83;
+        description
+          "Bisynchronous Protocol";
+      }
+      enum "async" {
+        value 84;
+        description
+          "Asynchronous Protocol";
+      }
+      enum "cnr" {
+        value 85;
+        description
+          "Combat Net Radio";
+      }
+      enum "iso88025Dtr" {
+        value 86;
+        description
+          "ISO 802.5r DTR";
+      }
+      enum "eplrs" {
+        value 87;
+        description
+          "Ext Pos Loc Report Sys";
+      }
+      enum "arap" {
+        value 88;
+        description
+          "Appletalk Remote Access Protocol";
+      }
+      enum "propCnls" {
+        value 89;
+        description
+          "Proprietary Connectionless Protocol";
+      }
+      enum "hostPad" {
+        value 90;
+        description
+          "CCITT-ITU X.29 PAD Protocol";
+      }
+      enum "termPad" {
+        value 91;
+        description
+          "CCITT-ITU X.3 PAD Facility";
+      }
+      enum "frameRelayMPI" {
+        value 92;
+        description
+          "Multiproto Interconnect over FR";
+      }
+      enum "x213" {
+        value 93;
+        description
+          "CCITT-ITU X213";
+      }
+      enum "adsl" {
+        value 94;
+        description
+          "Asymmetric Digital Subscriber Loop";
+      }
+      enum "radsl" {
+        value 95;
+        description
+          "Rate-Adapt. Digital Subscriber Loop";
+      }
+      enum "sdsl" {
+        value 96;
+        description
+          "Symmetric Digital Subscriber Loop";
+      }
+      enum "vdsl" {
+        value 97;
+        description
+          "Very H-Speed Digital Subscrib. Loop";
+      }
+      enum "iso88025CRFPInt" {
+        value 98;
+        description
+          "ISO 802.5 CRFP";
+      }
+      enum "myrinet" {
+        value 99;
+        description
+          "Myricom Myrinet";
+      }
+      enum "voiceEM" {
+        value 100;
+        description
+          "voice recEive and transMit";
+      }
+      enum "voiceFXO" {
+        value 101;
+        description
+          "voice Foreign Exchange Office";
+      }
+      enum "voiceFXS" {
+        value 102;
+        description
+          "voice Foreign Exchange Station";
+      }
+      enum "voiceEncap" {
+        value 103;
+        description
+          "voice encapsulation";
+      }
+      enum "voiceOverIp" {
+        value 104;
+        description
+          "voice over IP encapsulation";
+      }
+      enum "atmDxi" {
+        value 105;
+        description
+          "ATM DXI";
+      }
+      enum "atmFuni" {
+        value 106;
+        description
+          "ATM FUNI";
+      }
+      enum "atmIma" {
+        value 107;
+        description
+          "ATM IMA";
+      }
+      enum "pppMultilinkBundle" {
+        value 108;
+        description
+          "PPP Multilink Bundle";
+      }
+      enum "ipOverCdlc" {
+        value 109;
+        description
+          "IBM ipOverCdlc";
+      }
+      enum "ipOverClaw" {
+        value 110;
+        description
+          "IBM Common Link Access to Workstn";
+      }
+      enum "stackToStack" {
+        value 111;
+        description
+          "IBM stackToStack";
+      }
+      enum "virtualIpAddress" {
+        value 112;
+        description
+          "IBM VIPA";
+      }
+      enum "mpc" {
+        value 113;
+        description
+          "IBM multi-protocol channel support";
+      }
+      enum "ipOverAtm" {
+        value 114;
+        description
+          "IBM ipOverAtm";
+        reference
+          "RFC 2320 - Definitions of Managed Objects for Classical IP
+                      and ARP Over ATM Using SMIv2 (IPOA-MIB)";
+      }
+      enum "iso88025Fiber" {
+        value 115;
+        description
+          "ISO 802.5j Fiber Token Ring";
+      }
+      enum "tdlc" {
+        value 116;
+        description
+          "IBM twinaxial data link control";
+      }
+      enum "gigabitEthernet" {
+        value 117;
+        status deprecated;
+        description
+          "Obsoleted via RFC3635
+           ethernetCsmacd(6) should be used instead";
+        reference
+          "RFC 3635 - Definitions of Managed Objects for the
+                      Ethernet-like Interface Types.";
+      }
+      enum "hdlc" {
+        value 118;
+        description
+          "HDLC";
+      }
+      enum "lapf" {
+        value 119;
+        description
+          "LAP F";
+      }
+      enum "v37" {
+        value 120;
+        description
+          "V.37";
+      }
+      enum "x25mlp" {
+        value 121;
+        description
+          "Multi-Link Protocol";
+      }
+      enum "x25huntGroup" {
+        value 122;
+        description
+          "X25 Hunt Group";
+      }
+      enum "transpHdlc" {
+        value 123;
+        description
+          "Transp HDLC";
+      }
+      enum "interleave" {
+        value 124;
+        description
+          "Interleave channel";
+      }
+      enum "fast" {
+        value 125;
+        description
+          "Fast channel";
+      }
+      enum "ip" {
+        value 126;
+        description
+          "IP (for APPN HPR in IP networks)";
+      }
+      enum "docsCableMaclayer" {
+        value 127;
+        description
+          "CATV Mac Layer";
+      }
+      enum "docsCableDownstream" {
+        value 128;
+        description
+          "CATV Downstream interface";
+      }
+      enum "docsCableUpstream" {
+        value 129;
+        description
+          "CATV Upstream interface";
+      }
+      enum "a12MppSwitch" {
+        value 130;
+        description
+          "Avalon Parallel Processor";
+      }
+      enum "tunnel" {
+        value 131;
+        description
+          "Encapsulation interface";
+      }
+      enum "coffee" {
+        value 132;
+        description
+          "coffee pot";
+        reference
+          "RFC 2325 - Coffee MIB";
+      }
+      enum "ces" {
+        value 133;
+        description
+          "Circuit Emulation Service";
+      }
+      enum "atmSubInterface" {
+        value 134;
+        description
+          "ATM Sub Interface";
+      }
+      enum "l2vlan" {
+        value 135;
+        description
+          "Layer 2 Virtual LAN using 802.1Q";
+      }
+      enum "l3ipvlan" {
+        value 136;
+        description
+          "Layer 3 Virtual LAN using IP";
+      }
+      enum "l3ipxvlan" {
+        value 137;
+        description
+          "Layer 3 Virtual LAN using IPX";
+      }
+      enum "digitalPowerline" {
+        value 138;
+        description
+          "IP over Power Lines";
+      }
+      enum "mediaMailOverIp" {
+        value 139;
+        description
+          "Multimedia Mail over IP";
+      }
+      enum "dtm" {
+        value 140;
+        description
+          "Dynamic syncronous Transfer Mode";
+      }
+      enum "dcn" {
+        value 141;
+        description
+          "Data Communications Network";
+      }
+      enum "ipForward" {
+        value 142;
+        description
+          "IP Forwarding Interface";
+      }
+      enum "msdsl" {
+        value 143;
+        description
+          "Multi-rate Symmetric DSL";
+      }
+      enum "ieee1394" {
+        value 144;
+        description
+          "IEEE1394 High Performance Serial Bus";
+      }
+      enum "if-gsn" {
+        value 145;
+        description
+          "HIPPI-6400";
+      }
+      enum "dvbRccMacLayer" {
+        value 146;
+        description
+          "DVB-RCC MAC Layer";
+      }
+      enum "dvbRccDownstream" {
+        value 147;
+        description
+          "DVB-RCC Downstream Channel";
+      }
+      enum "dvbRccUpstream" {
+        value 148;
+        description
+          "DVB-RCC Upstream Channel";
+      }
+      enum "atmVirtual" {
+        value 149;
+        description
+          "ATM Virtual Interface";
+      }
+      enum "mplsTunnel" {
+        value 150;
+        description
+          "MPLS Tunnel Virtual Interface";
+      }
+      enum "srp" {
+        value 151;
+        description
+          "Spatial Reuse Protocol       ";
+      }
+      enum "voiceOverAtm" {
+        value 152;
+        description
+          "Voice Over ATM";
+      }
+      enum "voiceOverFrameRelay" {
+        value 153;
+        description
+          "Voice Over Frame Relay";
+      }
+      enum "idsl" {
+        value 154;
+        description
+          "Digital Subscriber Loop over ISDN";
+      }
+      enum "compositeLink" {
+        value 155;
+        description
+          "Avici Composite Link Interface";
+      }
+      enum "ss7SigLink" {
+        value 156;
+        description
+          "SS7 Signaling Link";
+      }
+      enum "propWirelessP2P" {
+        value 157;
+        description
+          "Prop. P2P wireless interface";
+      }
+      enum "frForward" {
+        value 158;
+        description
+          "Frame Forward Interface";
+      }
+      enum "rfc1483" {
+        value 159;
+        description
+          "Multiprotocol over ATM AAL5";
+        reference
+          "RFC 1483 - Multiprotocol Encapsulation over ATM
+                      Adaptation Layer 5";
+      }
+      enum "usb" {
+        value 160;
+        description
+          "USB Interface";
+      }
+      enum "ieee8023adLag" {
+        value 161;
+        description
+          "IEEE 802.3ad Link Aggregate";
+      }
+      enum "bgppolicyaccounting" {
+        value 162;
+        description
+          "BGP Policy Accounting";
+      }
+      enum "frf16MfrBundle" {
+        value 163;
+        description
+          "FRF .16 Multilink Frame Relay";
+      }
+      enum "h323Gatekeeper" {
+        value 164;
+        description
+          "H323 Gatekeeper";
+      }
+      enum "h323Proxy" {
+        value 165;
+        description
+          "H323 Voice and Video Proxy";
+      }
+      enum "mpls" {
+        value 166;
+        description
+          "MPLS";
+      }
+      enum "mfSigLink" {
+        value 167;
+        description
+          "Multi-frequency signaling link";
+      }
+      enum "hdsl2" {
+        value 168;
+        description
+          "High Bit-Rate DSL - 2nd generation";
+      }
+      enum "shdsl" {
+        value 169;
+        description
+          "Multirate HDSL2";
+      }
+      enum "ds1FDL" {
+        value 170;
+        description
+          "Facility Data Link 4Kbps on a DS1";
+      }
+      enum "pos" {
+        value 171;
+        description
+          "Packet over SONET/SDH Interface";
+      }
+      enum "dvbAsiIn" {
+        value 172;
+        description
+          "DVB-ASI Input";
+      }
+      enum "dvbAsiOut" {
+        value 173;
+        description
+          "DVB-ASI Output";
+      }
+      enum "plc" {
+        value 174;
+        description
+          "Power Line Communtications";
+      }
+      enum "nfas" {
+        value 175;
+        description
+          "Non Facility Associated Signaling";
+      }
+      enum "tr008" {
+        value 176;
+        description
+          "TR008";
+      }
+      enum "gr303RDT" {
+        value 177;
+        description
+          "Remote Digital Terminal";
+      }
+      enum "gr303IDT" {
+        value 178;
+        description
+          "Integrated Digital Terminal";
+      }
+      enum "isup" {
+        value 179;
+        description
+          "ISUP";
+      }
+      enum "propDocsWirelessMaclayer" {
+        value 180;
+        description
+          "Cisco proprietary Maclayer";
+      }
+      enum "propDocsWirelessDownstream" {
+        value 181;
+        description
+          "Cisco proprietary Downstream";
+      }
+      enum "propDocsWirelessUpstream" {
+        value 182;
+        description
+          "Cisco proprietary Upstream";
+      }
+      enum "hiperlan2" {
+        value 183;
+        description
+          "HIPERLAN Type 2 Radio Interface";
+      }
+      enum "propBWAp2Mp" {
+        value 184;
+        description
+          "PropBroadbandWirelessAccesspt2multipt use of this value
+           for IEEE 802.16 WMAN interfaces as per IEEE Std 802.16f
+           is deprecated and ieee80216WMAN(237) should be used
+           instead.";
+      }
+      enum "sonetOverheadChannel" {
+        value 185;
+        description
+          "SONET Overhead Channel";
+      }
+      enum "digitalWrapperOverheadChannel" {
+        value 186;
+        description
+          "Digital Wrapper";
+      }
+      enum "aal2" {
+        value 187;
+        description
+          "ATM adaptation layer 2";
+      }
+      enum "radioMAC" {
+        value 188;
+        description
+          "MAC layer over radio links";
+      }
+      enum "atmRadio" {
+        value 189;
+        description
+          "ATM over radio links";
+      }
+      enum "imt" {
+        value 190;
+        description
+          "Inter Machine Trunks";
+      }
+      enum "mvl" {
+        value 191;
+        description
+          "Multiple Virtual Lines DSL";
+      }
+      enum "reachDSL" {
+        value 192;
+        description
+          "Long Reach DSL";
+      }
+      enum "frDlciEndPt" {
+        value 193;
+        description
+          "Frame Relay DLCI End Point";
+      }
+      enum "atmVciEndPt" {
+        value 194;
+        description
+          "ATM VCI End Point";
+      }
+      enum "opticalChannel" {
+        value 195;
+        description
+          "Optical Channel";
+      }
+      enum "opticalTransport" {
+        value 196;
+        description
+          "Optical Transport";
+      }
+      enum "propAtm" {
+        value 197;
+        description
+          "Proprietary ATM";
+      }
+      enum "voiceOverCable" {
+        value 198;
+        description
+          "Voice Over Cable Interface";
+      }
+      enum "infiniband" {
+        value 199;
+        description
+          "Infiniband";
+      }
+      enum "teLink" {
+        value 200;
+        description
+          "TE Link";
+      }
+      enum "q2931" {
+        value 201;
+        description
+          "Q.2931";
+      }
+      enum "virtualTg" {
+        value 202;
+        description
+          "Virtual Trunk Group";
+      }
+      enum "sipTg" {
+        value 203;
+        description
+          "SIP Trunk Group";
+      }
+      enum "sipSig" {
+        value 204;
+        description
+          "SIP Signaling";
+      }
+      enum "docsCableUpstreamChannel" {
+        value 205;
+        description
+          "CATV Upstream Channel";
+      }
+      enum "econet" {
+        value 206;
+        description
+          "Acorn Econet";
+      }
+      enum "pon155" {
+        value 207;
+        description
+          "FSAN 155Mb Symetrical PON interface";
+      }
+      enum "pon622" {
+        value 208;
+        description
+          "FSAN622Mb Symetrical PON interface";
+      }
+      enum "bridge" {
+        value 209;
+        description
+          "Transparent bridge interface";
+      }
+      enum "linegroup" {
+        value 210;
+        description
+          "Interface common to multiple lines";
+      }
+      enum "voiceEMFGD" {
+        value 211;
+        description
+          "voice E&M Feature Group D";
+      }
+      enum "voiceFGDEANA" {
+        value 212;
+        description
+          "voice FGD Exchange Access North American";
+      }
+      enum "voiceDID" {
+        value 213;
+        description
+          "voice Direct Inward Dialing";
+      }
+      enum "mpegTransport" {
+        value 214;
+        description
+          "MPEG transport interface";
+      }
+      enum "sixToFour" {
+        value 215;
+        status deprecated;
+        description
+          "6to4 interface (DEPRECATED)";
+        reference
+          "RFC 4087 - IP Tunnel MIB";
+      }
+      enum "gtp" {
+        value 216;
+        description
+          "GTP (GPRS Tunneling Protocol)";
+      }
+      enum "pdnEtherLoop1" {
+        value 217;
+        description
+          "Paradyne EtherLoop 1";
+      }
+      enum "pdnEtherLoop2" {
+        value 218;
+        description
+          "Paradyne EtherLoop 2";
+      }
+      enum "opticalChannelGroup" {
+        value 219;
+        description
+          "Optical Channel Group";
+      }
+      enum "homepna" {
+        value 220;
+        description
+          "HomePNA ITU-T G.989";
+      }
+      enum "gfp" {
+        value 221;
+        description
+          "Generic Framing Procedure (GFP)";
+      }
+      enum "ciscoISLvlan" {
+        value 222;
+        description
+          "Layer 2 Virtual LAN using Cisco ISL";
+      }
+      enum "actelisMetaLOOP" {
+        value 223;
+        description
+          "Acteleis proprietary MetaLOOP High Speed Link";
+      }
+      enum "fcipLink" {
+        value 224;
+        description
+          "FCIP Link";
+      }
+      enum "rpr" {
+        value 225;
+        description
+          "Resilient Packet Ring Interface Type";
+      }
+      enum "qam" {
+        value 226;
+        description
+          "RF Qam Interface";
+      }
+      enum "lmp" {
+        value 227;
+        description
+          "Link Management Protocol";
+        reference
+          "RFC 4327 - Link Management Protocol (LMP) Management
+                      Information Base (MIB)";
+      }
+      enum "cblVectaStar" {
+        value 228;
+        description
+          "Cambridge Broadband Networks Limited VectaStar";
+      }
+      enum "docsCableMCmtsDownstream" {
+        value 229;
+        description
+          "CATV Modular CMTS Downstream Interface";
+      }
+      enum "adsl2" {
+        value 230;
+        status deprecated;
+        description
+          "Asymmetric Digital Subscriber Loop Version 2
+           (DEPRECATED/OBSOLETED - please use adsl2plus(238)
+           instead)";
+        reference
+          "RFC 4706 - Definitions of Managed Objects for Asymmetric
+                      Digital Subscriber Line 2 (ADSL2)";
+      }
+      enum "macSecControlledIF" {
+        value 231;
+        description
+          "MACSecControlled";
+      }
+      enum "macSecUncontrolledIF" {
+        value 232;
+        description
+          "MACSecUncontrolled";
+      }
+      enum "aviciOpticalEther" {
+        value 233;
+        description
+         "Avici Optical Ethernet Aggregate";
+      }
+      enum "atmbond" {
+        value 234;
+        description
+          "atmbond";
+      }
+      enum "voiceFGDOS" {
+        value 235;
+        description
+          "voice FGD Operator Services";
+      }
+      enum "mocaVersion1" {
+        value 236;
+        description
+          "MultiMedia over Coax Alliance (MoCA) Interface
+           as documented in information provided privately to IANA";
+      }
+      enum "ieee80216WMAN" {
+        value 237;
+        description
+          "IEEE 802.16 WMAN interface";
+      }
+      enum "adsl2plus" {
+        value 238;
+        description
+          "Asymmetric Digital Subscriber Loop Version 2,
+           Version 2 Plus and all variants";
+      }
+      enum "dvbRcsMacLayer" {
+        value 239;
+        description
+          "DVB-RCS MAC Layer";
+        reference
+          "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+      }
+      enum "dvbTdm" {
+        value 240;
+        description
+          "DVB Satellite TDM";
+        reference
+          "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+      }
+      enum "dvbRcsTdma" {
+        value 241;
+        description
+          "DVB-RCS TDMA";
+        reference
+          "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+      }
+      enum "x86Laps" {
+        value 242;
+        description
+          "LAPS based on ITU-T X.86/Y.1323";
+      }
+      enum "wwanPP" {
+        value 243;
+        description
+          "3GPP WWAN";
+      }
+      enum "wwanPP2" {
+        value 244;
+        description
+          "3GPP2 WWAN";
+      }
+      enum "voiceEBS" {
+        value 245;
+        description
+          "voice P-phone EBS physical interface";
+      }
+      enum "ifPwType" {
+        value 246;
+        description
+          "Pseudowire interface type";
+        reference
+          "RFC 5601 - Pseudowire (PW) Management Information Base";
+      }
+      enum "ilan" {
+        value 247;
+        description
+          "Internal LAN on a bridge per IEEE 802.1ap";
+      }
+      enum "pip" {
+        value 248;
+        description
+          "Provider Instance Port on a bridge per IEEE 802.1ah PBB";
+      }
+      enum "aluELP" {
+        value 249;
+        description
+          "Alcatel-Lucent Ethernet Link Protection";
+      }
+      enum "gpon" {
+        value 250;
+        description
+          "Gigabit-capable passive optical networks (G-PON) as per
+           ITU-T G.948";
+      }
+      enum "vdsl2" {
+        value 251;
+        description
+          "Very high speed digital subscriber line Version 2
+           (as per ITU-T Recommendation G.993.2)";
+        reference
+          "RFC 5650 - Definitions of Managed Objects for Very High
+                      Speed Digital Subscriber Line 2 (VDSL2)";
+      }
+      enum "capwapDot11Profile" {
+        value 252;
+        description
+          "WLAN Profile Interface";
+        reference
+          "RFC 5834 - Control and Provisioning of Wireless Access
+                      Points (CAPWAP) Protocol Binding MIB for
+                      IEEE 802.11";
+      }
+      enum "capwapDot11Bss" {
+        value 253;
+        description
+          "WLAN BSS Interface";
+        reference
+          "RFC 5834 - Control and Provisioning of Wireless Access
+                      Points (CAPWAP) Protocol Binding MIB for
+                      IEEE 802.11";
+      }
+      enum "capwapWtpVirtualRadio" {
+        value 254;
+        description
+          "WTP Virtual Radio Interface";
+        reference
+          "RFC 5833 - Control and Provisioning of Wireless Access
+                      Points (CAPWAP) Protocol Base MIB";
+      }
+      enum "bits" {
+        value 255;
+        description
+          "bitsport";
+      }
+      enum "docsCableUpstreamRfPort" {
+        value 256;
+        description
+          "DOCSIS CATV Upstream RF Port";
+      }
+      enum "cableDownstreamRfPort" {
+        value 257;
+        description
+          "CATV downstream RF port";
+      }
+      enum "vmwareVirtualNic" {
+        value 258;
+        description
+          "VMware Virtual Network Interface";
+      }
+      enum "ieee802154" {
+        value 259;
+        description
+          "IEEE 802.15.4 WPAN interface";
+        reference
+          "IEEE 802.15.4-2006";
+      }
+      enum "otnOdu" {
+        value 260;
+        description
+          "OTN Optical Data Unit";
+      }
+      enum "otnOtu" {
+        value 261;
+        description
+          "OTN Optical channel Transport Unit";
+      }
+      enum "ifVfiType" {
+        value 262;
+        description
+          "VPLS Forwarding Instance Interface Type";
+      }
+      enum "g9981" {
+        value 263;
+        description
+          "G.998.1 bonded interface";
+      }
+      enum "g9982" {
+        value 264;
+        description
+          "G.998.2 bonded interface";
+      }
+      enum "g9983" {
+        value 265;
+        description
+          "G.998.3 bonded interface";
+      }
+      enum "aluEpon" {
+        value 266;
+        description
+          "Ethernet Passive Optical Networks (E-PON)";
+      }
+      enum "aluEponOnu" {
+        value 267;
+        description
+          "EPON Optical Network Unit";
+      }
+      enum "aluEponPhysicalUni" {
+        value 268;
+        description
+          "EPON physical User to Network interface";
+      }
+      enum "aluEponLogicalLink" {
+        value 269;
+        description
+          "The emulation of a point-to-point link over the EPON
+           layer";
+      }
+      enum "aluGponOnu" {
+        value 270;
+        description
+          "GPON Optical Network Unit";
+        reference
+          "ITU-T G.984.2";
+      }
+      enum "aluGponPhysicalUni" {
+        value 271;
+        description
+          "GPON physical User to Network interface";
+        reference
+          "ITU-T G.984.2";
+      }
+      enum "vmwareNicTeam" {
+        value 272;
+        description
+          "VMware NIC Team";
+      }
+    }
+    description
+      "This data type is used as the syntax of the 'type'
+       leaf in the 'interface' list in the YANG module
+       ietf-interface.
+
+       The definition of this typedef with the
+       addition of newly assigned values is published
+       periodically by the IANA, in either the Assigned
+       Numbers RFC, or some derivative of it specific to
+       Internet Network Management number assignments.  (The
+       latest arrangements can be obtained by contacting the
+       IANA.)
+
+       Requests for new values should be made to IANA via
+       email (iana&iana.org).";
+    reference
+      "ifType definitions registry.
+       <http://www.iana.org/assignments/smi-numbers>";
+  }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-inet-types@2010-09-24.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-inet-types@2010-09-24.yang
new file mode 100644 (file)
index 0000000..de20feb
--- /dev/null
@@ -0,0 +1,418 @@
+ module ietf-inet-types {
+
+   namespace "urn:ietf:params:xml:ns:yang:ietf-inet-types";
+   prefix "inet";
+
+   organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+   contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Partain
+               <mailto:david.partain@ericsson.com>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     Editor:   Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>";
+
+   description
+    "This module contains a collection of generally useful derived
+     YANG data types for Internet addresses and related things.
+
+     Copyright (c) 2010 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or without
+     modification, is permitted pursuant to, and subject to the license
+     terms contained in, the Simplified BSD License set forth in Section
+     4.c of the IETF Trust's Legal Provisions Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6021; see
+     the RFC itself for full legal notices.";
+
+   revision 2010-09-24 {
+     description
+      "Initial revision.";
+     reference
+      "RFC 6021: Common YANG Data Types";
+   }
+
+   /*** collection of protocol field related types ***/
+
+   typedef ip-version {
+     type enumeration {
+       enum unknown {
+         value "0";
+         description
+          "An unknown or unspecified version of the Internet protocol.";
+       }
+       enum ipv4 {
+         value "1";
+         description
+          "The IPv4 protocol as defined in RFC 791.";
+       }
+       enum ipv6 {
+         value "2";
+         description
+          "The IPv6 protocol as defined in RFC 2460.";
+       }
+     }
+     description
+      "This value represents the version of the IP protocol.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetVersion textual convention of the SMIv2.";
+     reference
+      "RFC  791: Internet Protocol
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   typedef dscp {
+     type uint8 {
+       range "0..63";
+     }
+     description
+      "The dscp type represents a Differentiated Services Code-Point
+       that may be used for marking packets in a traffic stream.
+
+       In the value set and its semantics, this type is equivalent
+       to the Dscp textual convention of the SMIv2.";
+     reference
+      "RFC 3289: Management Information Base for the Differentiated
+                 Services Architecture
+       RFC 2474: Definition of the Differentiated Services Field
+                 (DS Field) in the IPv4 and IPv6 Headers
+       RFC 2780: IANA Allocation Guidelines For Values In
+                 the Internet Protocol and Related Headers";
+   }
+
+   typedef ipv6-flow-label {
+     type uint32 {
+       range "0..1048575";
+     }
+     description
+      "The flow-label type represents flow identifier or Flow Label
+       in an IPv6 packet header that may be used to discriminate
+       traffic flows.
+
+       In the value set and its semantics, this type is equivalent
+       to the IPv6FlowLabel textual convention of the SMIv2.";
+     reference
+      "RFC 3595: Textual Conventions for IPv6 Flow Label
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification";
+   }
+
+   typedef port-number {
+     type uint16 {
+       range "0..65535";
+     }
+     description
+      "The port-number type represents a 16-bit port number of an
+       Internet transport layer protocol such as UDP, TCP, DCCP, or
+       SCTP.  Port numbers are assigned by IANA.  A current list of
+       all assignments is available from <http://www.iana.org/>.
+
+       Note that the port number value zero is reserved by IANA.  In
+       situations where the value zero does not make sense, it can
+       be excluded by subtyping the port-number type.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetPortNumber textual convention of the SMIv2.";
+     reference
+      "RFC  768: User Datagram Protocol
+       RFC  793: Transmission Control Protocol
+       RFC 4960: Stream Control Transmission Protocol
+       RFC 4340: Datagram Congestion Control Protocol (DCCP)
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of autonomous system related types ***/
+
+   typedef as-number {
+     type uint32;
+     description
+      "The as-number type represents autonomous system numbers
+       which identify an Autonomous System (AS).  An AS is a set
+       of routers under a single technical administration, using
+       an interior gateway protocol and common metrics to route
+       packets within the AS, and using an exterior gateway
+       protocol to route packets to other ASs'.  IANA maintains
+       the AS number space and has delegated large parts to the
+       regional registries.
+
+       Autonomous system numbers were originally limited to 16
+       bits.  BGP extensions have enlarged the autonomous system
+       number space to 32 bits.  This type therefore uses an uint32
+       base type without a range restriction in order to support
+       a larger autonomous system number space.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetAutonomousSystemNumber textual convention of
+       the SMIv2.";
+     reference
+      "RFC 1930: Guidelines for creation, selection, and registration
+                 of an Autonomous System (AS)
+       RFC 4271: A Border Gateway Protocol 4 (BGP-4)
+       RFC 4893: BGP Support for Four-octet AS Number Space
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of IP address and hostname related types ***/
+
+   typedef ip-address {
+     type union {
+       type inet:ipv4-address;
+       type inet:ipv6-address;
+     }
+     description
+      "The ip-address type represents an IP address and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-address {
+     type string {
+       pattern
+         '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+       +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+       + '(%[\p{N}\p{L}]+)?';
+     }
+     description
+       "The ipv4-address type represents an IPv4 address in
+        dotted-quad notation.  The IPv4 address may include a zone
+        index, separated by a % sign.
+
+        The zone index is used to disambiguate identical address
+        values.  For link-local addresses, the zone index will
+        typically be the interface index number or the name of an
+        interface.  If the zone index is not present, the default
+        zone of the device will be used.
+
+        The canonical format for the zone index is the numerical
+        format";
+   }
+
+   typedef ipv6-address {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(%[\p{N}\p{L}]+)?';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(%.+)?';
+     }
+     description
+      "The ipv6-address type represents an IPv6 address in full,
+       mixed, shortened, and shortened-mixed notation.  The IPv6
+       address may include a zone index, separated by a % sign.
+
+       The zone index is used to disambiguate identical address
+       values.  For link-local addresses, the zone index will
+       typically be the interface index number or the name of an
+       interface.  If the zone index is not present, the default
+       zone of the device will be used.
+
+       The canonical format of IPv6 addresses uses the compressed
+       format described in RFC 4291, Section 2.2, item 2 with the
+       following additional rules: the :: substitution must be
+       applied to the longest sequence of all-zero 16-bit chunks
+       in an IPv6 address.  If there is a tie, the first sequence
+       of all-zero 16-bit chunks is replaced by ::.  Single
+       all-zero 16-bit chunks are not compressed.  The canonical
+       format uses lowercase characters and leading zeros are
+       not allowed.  The canonical format for the zone index is
+       the numerical format as described in RFC 4007, Section
+       11.2.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture
+       RFC 4007: IPv6 Scoped Address Architecture
+       RFC 5952: A Recommendation for IPv6 Address Text Representation";
+   }
+
+   typedef ip-prefix {
+     type union {
+       type inet:ipv4-prefix;
+       type inet:ipv6-prefix;
+     }
+     description
+      "The ip-prefix type represents an IP prefix and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-prefix {
+     type string {
+       pattern
+          '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+        +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+        + '/(([0-9])|([1-2][0-9])|(3[0-2]))';
+     }
+     description
+      "The ipv4-prefix type represents an IPv4 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal to 32.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The canonical format of an IPv4 prefix has all bits of
+       the IPv4 address set to zero that are not part of the
+       IPv4 prefix.";
+   }
+
+   typedef ipv6-prefix {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(/.+)';
+     }
+     description
+      "The ipv6-prefix type represents an IPv6 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal 128.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The IPv6 address should have all bits that do not belong
+       to the prefix set to zero.
+
+       The canonical format of an IPv6 prefix has all bits of
+       the IPv6 address set to zero that are not part of the
+       IPv6 prefix.  Furthermore, IPv6 address is represented
+       in the compressed format described in RFC 4291, Section
+       2.2, item 2 with the following additional rules: the ::
+       substitution must be applied to the longest sequence of
+       all-zero 16-bit chunks in an IPv6 address.  If there is
+       a tie, the first sequence of all-zero 16-bit chunks is
+       replaced by ::.  Single all-zero 16-bit chunks are not
+       compressed.  The canonical format uses lowercase
+       characters and leading zeros are not allowed.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture";
+   }
+
+   /*** collection of domain name and URI types ***/
+
+   typedef domain-name {
+     type string {
+       pattern '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*'
+            +  '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)'
+            +  '|\.';
+       length "1..253";
+     }
+     description
+      "The domain-name type represents a DNS domain name.  The
+       name SHOULD be fully qualified whenever possible.
+
+       Internet domain names are only loosely specified.  Section
+       3.5 of RFC 1034 recommends a syntax (modified in Section
+       2.1 of RFC 1123).  The pattern above is intended to allow
+       for current practice in domain name use, and some possible
+       future expansion.  It is designed to hold various types of
+       domain names, including names used for A or AAAA records
+       (host names) and other records, such as SRV records.  Note
+       that Internet host names have a stricter syntax (described
+       in RFC 952) than the DNS recommendations in RFCs 1034 and
+       1123, and that systems that want to store host names in
+       schema nodes using the domain-name type are recommended to
+       adhere to this stricter standard to ensure interoperability.
+
+       The encoding of DNS names in the DNS protocol is limited
+       to 255 characters.  Since the encoding consists of labels
+       prefixed by a length bytes and there is a trailing NULL
+       byte, only 253 characters can appear in the textual dotted
+       notation.
+
+       The description clause of schema nodes using the domain-name
+       type MUST describe when and how these names are resolved to
+       IP addresses.  Note that the resolution of a domain-name value
+       may require to query multiple DNS records (e.g., A for IPv4
+       and AAAA for IPv6).  The order of the resolution process and
+       which DNS record takes precedence can either be defined
+       explicitely or it may depend on the configuration of the
+       resolver.
+
+       Domain-name values use the US-ASCII encoding.  Their canonical
+       format uses lowercase US-ASCII characters.  Internationalized
+       domain names MUST be encoded in punycode as described in RFC
+       3492";
+     reference
+      "RFC  952: DoD Internet Host Table Specification
+       RFC 1034: Domain Names - Concepts and Facilities
+       RFC 1123: Requirements for Internet Hosts -- Application
+                 and Support
+       RFC 2782: A DNS RR for specifying the location of services
+                 (DNS SRV)
+       RFC 3492: Punycode: A Bootstring encoding of Unicode for
+                 Internationalized Domain Names in Applications
+                 (IDNA)
+       RFC 5891: Internationalizing Domain Names in Applications
+                 (IDNA): Protocol";
+   }
+
+   typedef host {
+     type union {
+       type inet:ip-address;
+       type inet:domain-name;
+     }
+     description
+      "The host type represents either an IP address or a DNS
+       domain name.";
+   }
+
+   typedef uri {
+     type string;
+     description
+      "The uri type represents a Uniform Resource Identifier
+       (URI) as defined by STD 66.
+
+       Objects using the uri type MUST be in US-ASCII encoding,
+       and MUST be normalized as described by RFC 3986 Sections
+       6.2.1, 6.2.2.1, and 6.2.2.2.  All unnecessary
+       percent-encoding is removed, and all case-insensitive
+       characters are set to lowercase except for hexadecimal
+       digits, which are normalized to uppercase as described in
+       Section 6.2.2.1.
+
+       The purpose of this normalization is to help provide
+       unique URIs.  Note that this normalization is not
+       sufficient to provide uniqueness.  Two URIs that are
+       textually distinct after this normalization may still be
+       equivalent.
+
+       Objects using the uri type may restrict the schemes that
+       they permit.  For example, 'data:' and 'urn:' schemes
+       might not be appropriate.
+
+       A zero-length URI is not a valid URI.  This can be used to
+       express 'URI absent' where required.
+
+       In the value set and its semantics, this type is equivalent
+       to the Uri SMIv2 textual convention defined in RFC 5017.";
+     reference
+      "RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
+       RFC 3305: Report from the Joint W3C/IETF URI Planning Interest
+                 Group: Uniform Resource Identifiers (URIs), URLs,
+                 and Uniform Resource Names (URNs): Clarifications
+                 and Recommendations
+       RFC 5017: MIB Textual Conventions for Uniform Resource
+                 Identifiers (URIs)";
+   }
+
+ }
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-interfaces@2012-11-15.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-interfaces@2012-11-15.yang
new file mode 100644 (file)
index 0000000..b9117d0
--- /dev/null
@@ -0,0 +1,565 @@
+module ietf-interfaces {
+
+  namespace "urn:ietf:params:xml:ns:yang:ietf-interfaces";
+  prefix if;
+
+  import ietf-yang-types {
+    prefix yang;
+  }
+  import iana-if-type {
+    prefix ianaift;
+  }
+
+  organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+  contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     WG Chair: Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>
+
+     Editor:   Martin Bjorklund
+               <mailto:mbj@tail-f.com>";
+
+  description
+    "This module contains a collection of YANG definitions for
+     managing network interfaces.
+
+     Copyright (c) 2012 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or
+     without modification, is permitted pursuant to, and subject
+     to the license terms contained in, the Simplified BSD License
+     set forth in Section 4.c of the IETF Trust's Legal Provisions
+     Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC XXXX; see
+     the RFC itself for full legal notices.";
+
+  // RFC Ed.: replace XXXX with actual RFC number and remove this
+  // note.
+
+  // RFC Ed.: update the date below with the date of RFC publication
+  // and remove this note.
+  revision 2012-11-15 {
+    description
+      "Initial revision.";
+    reference
+      "RFC XXXX: A YANG Data Model for Interface Management";
+  }
+
+  /* Typedefs */
+
+  typedef interface-ref {
+    type leafref {
+      path "/if:interfaces/if:interface/if:name";
+    }
+    description
+      "This type is used by data models that need to reference
+       interfaces.";
+  }
+
+  /* Features */
+
+  feature arbitrary-names {
+    description
+      "This feature indicates that the server allows interfaces to
+       be named arbitrarily.";
+  }
+
+  feature if-mib {
+    description
+      "This feature indicates that the server implements IF-MIB.";
+    reference
+      "RFC 2863: The Interfaces Group MIB";
+  }
+
+  /* Data nodes */
+
+  container interfaces {
+    description
+      "Interface parameters.";
+
+    list interface {
+      key "name";
+      unique "type location";
+
+      description
+        "The list of interfaces on the device.";
+
+      leaf name {
+        type string;
+        description
+          "The name of the interface.
+
+           A device MAY restrict the allowed values for this leaf,
+           possibly depending on the type and location.
+
+           If the device allows arbitrarily named interfaces, the
+           feature 'arbitrary-names' is advertised.
+
+           This leaf MAY be mapped to ifName by an implementation.
+           Such an implementation MAY restrict the allowed values for
+           this leaf so that it matches the restrictions of ifName.
+           If a NETCONF server that implements this restriction is
+           sent a value that doesn't match the restriction, it MUST
+           reply with an rpc-error with the error-tag
+           'invalid-value'.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifName";
+      }
+
+      leaf description {
+        type string;
+        description
+          "A textual description of the interface.
+
+           This leaf MAY be mapped to ifAlias by an implementation.
+           Such an implementation MAY restrict the allowed values for
+           this leaf so that it matches the restrictions of ifAlias.
+           If a NETCONF server that implements this restriction is
+           sent a value that doesn't match the restriction, it MUST
+           reply with an rpc-error with the error-tag
+           'invalid-value'.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifAlias";
+      }
+
+      leaf type {
+        type ianaift:iana-if-type;
+        mandatory true;
+        description
+          "The type of the interface.
+
+           When an interface entry is created, a server MAY
+           initialize the type leaf with a valid value, e.g., if it
+           is possible to derive the type from the name of the
+           interface.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifType";
+      }
+
+      leaf location {
+        type string;
+        description
+          "The device-specific location of the interface of a
+           particular type.  The format of the location string
+           depends on the interface type and the device.
+
+           If the interface's type represents a physical interface,
+           this leaf MUST be set.
+
+           When an interface entry is created, a server MAY
+           initialize the location leaf with a valid value, e.g., if
+           it is possible to derive the location from the name of
+           the interface.";
+      }
+
+      leaf enabled {
+        type boolean;
+        default "true";
+        description
+          "The desired state of the interface.
+
+           This leaf contains the configured, desired state of the
+           interface.  Systems that implement the IF-MIB use the
+           value of this leaf to set IF-MIB.ifAdminStatus to 'up' or
+           'down' after an ifEntry has been initialized, as described
+           in RFC 2863.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifAdminStatus";
+      }
+
+      leaf oper-status {
+        type enumeration {
+          enum up {
+            value 1;
+            description
+              "Ready to pass packets.";
+          }
+          enum down {
+            value 2;
+            description
+              "The interface does not pass any packets.";
+          }
+          enum testing {
+            value 3;
+            description
+              "In some test mode.  No operational packets can
+               be passed.";
+          }
+          enum unknown {
+            value 4;
+            description
+              "Status cannot be determined for some reason.";
+          }
+          enum dormant {
+            value 5;
+            description
+              "Waiting for some external event.";
+          }
+          enum not-present {
+            value 6;
+            description
+              "Some component is missing.";
+          }
+          enum lower-layer-down {
+            value 7;
+            description
+              "Down due to state of lower-layer interface(s).";
+          }
+        }
+        config false;
+        description
+          "The current operational state of the interface.
+
+           If 'enabled' is 'false' then 'oper-status'
+           should be 'down'.  If 'enabled' is changed to 'true'
+           then 'oper-status' should change to 'up' if the interface
+           is ready to transmit and receive network traffic; it
+           should change to 'dormant' if the interface is waiting for
+           external actions (such as a serial line waiting for an
+           incoming connection); it should remain in the 'down' state
+           if and only if there is a fault that prevents it from
+           going to the 'up' state; it should remain in the
+           'not-present' state if the interface has missing
+           (typically, hardware) components.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifOperStatus";
+      }
+
+      leaf last-change {
+        type yang:date-and-time;
+        config false;
+        description
+          "The time the interface entered its current operational
+           state.  If the current state was entered prior to the
+           last re-initialization of the local network management
+           subsystem, then this node is not present.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifLastChange";
+      }
+
+      leaf if-index {
+        if-feature if-mib;
+        type int32 {
+          range "1..2147483647";
+        }
+        config false;
+        description
+          "The ifIndex value for the ifEntry represented by this
+           interface.
+
+           Media-specific modules must specify how the type is
+           mapped to entries in the ifTable.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifIndex";
+      }
+
+      leaf link-up-down-trap-enable {
+        if-feature if-mib;
+        type enumeration {
+          enum enabled {
+            value 1;
+          }
+          enum disabled {
+            value 2;
+          }
+        }
+        description
+          "Indicates whether linkUp/linkDown SNMP notifications
+           should be generated for this interface.
+           If this node is not configured, the value 'enabled' is
+           operationally used by the server for interfaces which do
+           not operate on top of any other interface (i.e., there are
+           no 'lower-layer-if' entries), and 'disabled' otherwise.";
+        reference
+          "RFC 2863: The Interfaces Group MIB -
+                     ifLinkUpDownTrapEnable";
+      }
+
+      leaf phys-address {
+        type yang:phys-address;
+        config false;
+        description
+          "The interface's address at its protocol sub-layer.  For
+          example, for an 802.x interface, this object normally
+          contains a MAC address.  The interface's media-specific
+          modules must define the bit and byte ordering and the
+          format of the value of this object.  For interfaces that do
+          not have such an address (e.g., a serial line), this node
+          is not present.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifPhysAddress";
+      }
+
+      leaf-list higher-layer-if {
+        type interface-ref;
+        config false;
+        description
+          "A list of references to interfaces layered on top of this
+           interface.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifStackTable";
+      }
+
+      leaf-list lower-layer-if {
+        type interface-ref;
+        config false;
+        description
+          "A list of references to interfaces layered underneath this
+           interface.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifStackTable";
+      }
+
+      leaf speed {
+        type yang:gauge64;
+        units "bits / second";
+        config false;
+        description
+            "An estimate of the interface's current bandwidth in bits
+             per second.  For interfaces which do not vary in
+             bandwidth or for those where no accurate estimation can
+             be made, this node should contain the nominal bandwidth.
+             For interfaces that has no concept of bandwidth, this
+             node is not present.";
+        reference
+          "RFC 2863: The Interfaces Group MIB -
+                     ifSpeed, ifHighSpeed";
+      }
+
+      container statistics {
+        config false;
+        description
+          "A collection of interface-related statistics objects.";
+
+        leaf discontinuity-time {
+          type yang:date-and-time;
+          description
+            "The time on the most recent occasion at which any one or
+             more of this interface's counters suffered a
+             discontinuity.  If no such discontinuities have occurred
+             since the last re-initialization of the local management
+             subsystem, then this node contains the time the local
+             management subsystem re-initialized itself.";
+        }
+
+        leaf in-octets {
+          type yang:counter64;
+          description
+            "The total number of octets received on the interface,
+             including framing characters.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCInOctets";
+        }
+        leaf in-unicast-pkts {
+          type yang:counter64;
+          description
+            "The number of packets, delivered by this sub-layer to a
+             higher (sub-)layer, which were not addressed to a
+             multicast or broadcast address at this sub-layer.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCInUcastPkts";
+        }
+        leaf in-broadcast-pkts {
+          type yang:counter64;
+          description
+            "The number of packets, delivered by this sub-layer to a
+             higher (sub-)layer, which were addressed to a broadcast
+             address at this sub-layer.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCInBroadcastPkts";
+        }
+        leaf in-multicast-pkts {
+          type yang:counter64;
+          description
+            "The number of packets, delivered by this sub-layer to a
+             higher (sub-)layer, which were addressed to a multicast
+             address at this sub-layer.  For a MAC layer protocol,
+             this includes both Group and Functional addresses.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCInMulticastPkts";
+        }
+        leaf in-discards {
+          type yang:counter32;
+          description
+            "The number of inbound packets which were chosen to be
+             discarded even though no errors had been detected to
+             prevent their being deliverable to a higher-layer
+             protocol.  One possible reason for discarding such a
+             packet could be to free up buffer space.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifInDiscards";
+        }
+        leaf in-errors {
+          type yang:counter32;
+          description
+            "For packet-oriented interfaces, the number of inbound
+             packets that contained errors preventing them from being
+             deliverable to a higher-layer protocol.  For character-
+             oriented or fixed-length interfaces, the number of
+             inbound transmission units that contained errors
+             preventing them from being deliverable to a higher-layer
+             protocol.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifInErrors";
+        }
+        leaf in-unknown-protos {
+          type yang:counter32;
+          description
+            "For packet-oriented interfaces, the number of packets
+             received via the interface which were discarded because
+             of an unknown or unsupported protocol.  For
+             character-oriented or fixed-length interfaces that
+             support protocol multiplexing the number of transmission
+             units received via the interface which were discarded
+             because of an unknown or unsupported protocol.  For any
+             interface that does not support protocol multiplexing,
+             this counter is not present.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifInUnknownProtos";
+        }
+
+        leaf out-octets {
+          type yang:counter64;
+          description
+            "The total number of octets transmitted out of the
+             interface, including framing characters.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCOutOctets";
+        }
+        leaf out-unicast-pkts {
+          type yang:counter64;
+          description
+            "The total number of packets that higher-level protocols
+             requested be transmitted, and which were not addressed
+             to a multicast or broadcast address at this sub-layer,
+             including those that were discarded or not sent.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCOutUcastPkts";
+        }
+        leaf out-broadcast-pkts {
+          type yang:counter64;
+          description
+            "The total number of packets that higher-level protocols
+             requested be transmitted, and which were addressed to a
+             broadcast address at this sub-layer, including those
+             that were discarded or not sent.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCOutBroadcastPkts";
+        }
+        leaf out-multicast-pkts {
+          type yang:counter64;
+          description
+            "The total number of packets that higher-level protocols
+             requested be transmitted, and which were addressed to a
+             multicast address at this sub-layer, including those
+             that were discarded or not sent.  For a MAC layer
+             protocol, this includes both Group and Functional
+             addresses.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCOutMulticastPkts";
+        }
+        leaf out-discards {
+          type yang:counter32;
+          description
+            "The number of outbound packets which were chosen to be
+             discarded even though no errors had been detected to
+             prevent their being transmitted.  One possible reason
+             for discarding such a packet could be to free up buffer
+             space.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifOutDiscards";
+        }
+        leaf out-errors {
+          type yang:counter32;
+          description
+            "For packet-oriented interfaces, the number of outbound
+             packets that could not be transmitted because of errors.
+             For character-oriented or fixed-length interfaces, the
+             number of outbound transmission units that could not be
+             transmitted because of errors.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifOutErrors";
+        }
+      }
+    }
+  }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-yang-types@2010-09-24.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/augment-relative-xpath-models/ietf-yang-types@2010-09-24.yang
new file mode 100644 (file)
index 0000000..e9d88ab
--- /dev/null
@@ -0,0 +1,396 @@
+ module ietf-yang-types {
+
+   namespace "urn:ietf:params:xml:ns:yang:ietf-yang-types";
+   prefix "yang";
+
+   organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+   contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Partain
+               <mailto:david.partain@ericsson.com>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     Editor:   Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>";
+
+   description
+    "This module contains a collection of generally useful derived
+     YANG data types.
+
+     Copyright (c) 2010 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or without
+     modification, is permitted pursuant to, and subject to the license
+     terms contained in, the Simplified BSD License set forth in Section
+     4.c of the IETF Trust's Legal Provisions Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6021; see
+     the RFC itself for full legal notices.";
+
+   revision 2010-09-24 {
+     description
+      "Initial revision.";
+     reference
+      "RFC 6021: Common YANG Data Types";
+   }
+
+   /*** collection of counter and gauge types ***/
+
+   typedef counter32 {
+     type uint32;
+     description
+      "The counter32 type represents a non-negative integer
+       that monotonically increases until it reaches a
+       maximum value of 2^32-1 (4294967295 decimal), when it
+       wraps around and starts increasing again from zero.
+
+       Counters have no defined 'initial' value, and thus, a
+       single value of a counter has (in general) no information
+       content.  Discontinuities in the monotonically increasing
+       value normally occur at re-initialization of the
+       management system, and at other times as specified in the
+       description of a schema node using this type.  If such
+       other times can occur, for example, the creation of
+       a schema node of type counter32 at times other than
+       re-initialization, then a corresponding schema node
+       should be defined, with an appropriate type, to indicate
+       the last discontinuity.
+
+       The counter32 type should not be used for configuration
+       schema nodes.  A default statement SHOULD NOT be used in
+       combination with the type counter32.
+
+       In the value set and its semantics, this type is equivalent
+       to the Counter32 type of the SMIv2.";
+     reference
+      "RFC 2578: Structure of Management Information Version 2 (SMIv2)";
+   }
+
+   typedef zero-based-counter32 {
+     type yang:counter32;
+     default "0";
+     description
+      "The zero-based-counter32 type represents a counter32
+       that has the defined 'initial' value zero.
+
+       A schema node of this type will be set to zero (0) on creation
+       and will thereafter increase monotonically until it reaches
+       a maximum value of 2^32-1 (4294967295 decimal), when it
+       wraps around and starts increasing again from zero.
+
+       Provided that an application discovers a new schema node
+       of this type within the minimum time to wrap, it can use the
+       'initial' value as a delta.  It is important for a management
+       station to be aware of this minimum time and the actual time
+       between polls, and to discard data if the actual time is too
+       long or there is no defined minimum time.
+
+       In the value set and its semantics, this type is equivalent
+       to the ZeroBasedCounter32 textual convention of the SMIv2.";
+     reference
+       "RFC 4502: Remote Network Monitoring Management Information
+                  Base Version 2";
+   }
+
+   typedef counter64 {
+     type uint64;
+     description
+      "The counter64 type represents a non-negative integer
+       that monotonically increases until it reaches a
+       maximum value of 2^64-1 (18446744073709551615 decimal),
+       when it wraps around and starts increasing again from zero.
+
+       Counters have no defined 'initial' value, and thus, a
+       single value of a counter has (in general) no information
+       content.  Discontinuities in the monotonically increasing
+       value normally occur at re-initialization of the
+       management system, and at other times as specified in the
+       description of a schema node using this type.  If such
+       other times can occur, for example, the creation of
+       a schema node of type counter64 at times other than
+       re-initialization, then a corresponding schema node
+       should be defined, with an appropriate type, to indicate
+       the last discontinuity.
+
+       The counter64 type should not be used for configuration
+       schema nodes.  A default statement SHOULD NOT be used in
+       combination with the type counter64.
+
+       In the value set and its semantics, this type is equivalent
+       to the Counter64 type of the SMIv2.";
+     reference
+      "RFC 2578: Structure of Management Information Version 2 (SMIv2)";
+   }
+
+   typedef zero-based-counter64 {
+     type yang:counter64;
+     default "0";
+     description
+      "The zero-based-counter64 type represents a counter64 that
+       has the defined 'initial' value zero.
+
+       A schema node of this type will be set to zero (0) on creation
+       and will thereafter increase monotonically until it reaches
+       a maximum value of 2^64-1 (18446744073709551615 decimal),
+       when it wraps around and starts increasing again from zero.
+
+       Provided that an application discovers a new schema node
+       of this type within the minimum time to wrap, it can use the
+       'initial' value as a delta.  It is important for a management
+       station to be aware of this minimum time and the actual time
+       between polls, and to discard data if the actual time is too
+       long or there is no defined minimum time.
+
+       In the value set and its semantics, this type is equivalent
+       to the ZeroBasedCounter64 textual convention of the SMIv2.";
+     reference
+      "RFC 2856: Textual Conventions for Additional High Capacity
+                 Data Types";
+   }
+
+   typedef gauge32 {
+     type uint32;
+     description
+      "The gauge32 type represents a non-negative integer, which
+       may increase or decrease, but shall never exceed a maximum
+       value, nor fall below a minimum value.  The maximum value
+       cannot be greater than 2^32-1 (4294967295 decimal), and
+       the minimum value cannot be smaller than 0.  The value of
+       a gauge32 has its maximum value whenever the information
+       being modeled is greater than or equal to its maximum
+       value, and has its minimum value whenever the information
+       being modeled is smaller than or equal to its minimum value.
+       If the information being modeled subsequently decreases
+       below (increases above) the maximum (minimum) value, the
+       gauge32 also decreases (increases).
+
+       In the value set and its semantics, this type is equivalent
+       to the Gauge32 type of the SMIv2.";
+     reference
+      "RFC 2578: Structure of Management Information Version 2 (SMIv2)";
+   }
+
+   typedef gauge64 {
+     type uint64;
+     description
+      "The gauge64 type represents a non-negative integer, which
+       may increase or decrease, but shall never exceed a maximum
+       value, nor fall below a minimum value.  The maximum value
+       cannot be greater than 2^64-1 (18446744073709551615), and
+       the minimum value cannot be smaller than 0.  The value of
+       a gauge64 has its maximum value whenever the information
+       being modeled is greater than or equal to its maximum
+       value, and has its minimum value whenever the information
+       being modeled is smaller than or equal to its minimum value.
+       If the information being modeled subsequently decreases
+       below (increases above) the maximum (minimum) value, the
+       gauge64 also decreases (increases).
+
+       In the value set and its semantics, this type is equivalent
+       to the CounterBasedGauge64 SMIv2 textual convention defined
+       in RFC 2856";
+     reference
+      "RFC 2856: Textual Conventions for Additional High Capacity
+                 Data Types";
+   }
+
+   /*** collection of identifier related types ***/
+
+   typedef object-identifier {
+     type string {
+       pattern '(([0-1](\.[1-3]?[0-9]))|(2\.(0|([1-9]\d*))))'
+             + '(\.(0|([1-9]\d*)))*';
+     }
+     description
+      "The object-identifier type represents administratively
+       assigned names in a registration-hierarchical-name tree.
+
+       Values of this type are denoted as a sequence of numerical
+       non-negative sub-identifier values.  Each sub-identifier
+       value MUST NOT exceed 2^32-1 (4294967295).  Sub-identifiers
+       are separated by single dots and without any intermediate
+       whitespace.
+
+       The ASN.1 standard restricts the value space of the first
+       sub-identifier to 0, 1, or 2.  Furthermore, the value space
+       of the second sub-identifier is restricted to the range
+       0 to 39 if the first sub-identifier is 0 or 1.  Finally,
+       the ASN.1 standard requires that an object identifier
+       has always at least two sub-identifier.  The pattern
+       captures these restrictions.
+
+       Although the number of sub-identifiers is not limited,
+       module designers should realize that there may be
+       implementations that stick with the SMIv2 limit of 128
+       sub-identifiers.
+
+       This type is a superset of the SMIv2 OBJECT IDENTIFIER type
+       since it is not restricted to 128 sub-identifiers.  Hence,
+       this type SHOULD NOT be used to represent the SMIv2 OBJECT
+       IDENTIFIER type, the object-identifier-128 type SHOULD be
+       used instead.";
+     reference
+      "ISO9834-1: Information technology -- Open Systems
+       Interconnection -- Procedures for the operation of OSI
+       Registration Authorities: General procedures and top
+       arcs of the ASN.1 Object Identifier tree";
+   }
+
+
+
+
+   typedef object-identifier-128 {
+     type object-identifier {
+       pattern '\d*(\.\d*){1,127}';
+     }
+     description
+      "This type represents object-identifiers restricted to 128
+       sub-identifiers.
+
+       In the value set and its semantics, this type is equivalent
+       to the OBJECT IDENTIFIER type of the SMIv2.";
+     reference
+      "RFC 2578: Structure of Management Information Version 2 (SMIv2)";
+   }
+
+   /*** collection of date and time related types ***/
+
+   typedef date-and-time {
+     type string {
+       pattern '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?'
+             + '(Z|[\+\-]\d{2}:\d{2})';
+     }
+     description
+      "The date-and-time type is a profile of the ISO 8601
+       standard for representation of dates and times using the
+       Gregorian calendar.  The profile is defined by the
+       date-time production in Section 5.6 of RFC 3339.
+
+       The date-and-time type is compatible with the dateTime XML
+       schema type with the following notable exceptions:
+
+       (a) The date-and-time type does not allow negative years.
+
+       (b) The date-and-time time-offset -00:00 indicates an unknown
+           time zone (see RFC 3339) while -00:00 and +00:00 and Z all
+           represent the same time zone in dateTime.
+
+       (c) The canonical format (see below) of data-and-time values
+           differs from the canonical format used by the dateTime XML
+           schema type, which requires all times to be in UTC using the
+           time-offset 'Z'.
+
+       This type is not equivalent to the DateAndTime textual
+       convention of the SMIv2 since RFC 3339 uses a different
+       separator between full-date and full-time and provides
+       higher resolution of time-secfrac.
+
+       The canonical format for date-and-time values with a known time
+       zone uses a numeric time zone offset that is calculated using
+       the device's configured known offset to UTC time.  A change of
+       the device's offset to UTC time will cause date-and-time values
+       to change accordingly.  Such changes might happen periodically
+       in case a server follows automatically daylight saving time
+       (DST) time zone offset changes.  The canonical format for
+       date-and-time values with an unknown time zone (usually referring
+       to the notion of local time) uses the time-offset -00:00.";
+     reference
+      "RFC 3339: Date and Time on the Internet: Timestamps
+       RFC 2579: Textual Conventions for SMIv2
+       XSD-TYPES: XML Schema Part 2: Datatypes Second Edition";
+   }
+
+   typedef timeticks {
+     type uint32;
+     description
+      "The timeticks type represents a non-negative integer that
+       represents the time, modulo 2^32 (4294967296 decimal), in
+       hundredths of a second between two epochs.  When a schema
+       node is defined that uses this type, the description of
+       the schema node identifies both of the reference epochs.
+
+       In the value set and its semantics, this type is equivalent
+       to the TimeTicks type of the SMIv2.";
+     reference
+      "RFC 2578: Structure of Management Information Version 2 (SMIv2)";
+   }
+
+   typedef timestamp {
+     type yang:timeticks;
+     description
+      "The timestamp type represents the value of an associated
+       timeticks schema node at which a specific occurrence happened.
+       The specific occurrence must be defined in the description
+       of any schema node defined using this type.  When the specific
+       occurrence occurred prior to the last time the associated
+       timeticks attribute was zero, then the timestamp value is
+       zero.  Note that this requires all timestamp values to be
+       reset to zero when the value of the associated timeticks
+       attribute reaches 497+ days and wraps around to zero.
+
+       The associated timeticks schema node must be specified
+       in the description of any schema node using this type.
+
+       In the value set and its semantics, this type is equivalent
+       to the TimeStamp textual convention of the SMIv2.";
+     reference
+      "RFC 2579: Textual Conventions for SMIv2";
+   }
+
+   /*** collection of generic address types ***/
+
+   typedef phys-address {
+     type string {
+       pattern '([0-9a-fA-F]{2}(:[0-9a-fA-F]{2})*)?';
+     }
+     description
+      "Represents media- or physical-level addresses represented
+       as a sequence octets, each octet represented by two hexadecimal
+       numbers.  Octets are separated by colons.  The canonical
+       representation uses lowercase characters.
+
+       In the value set and its semantics, this type is equivalent
+       to the PhysAddress textual convention of the SMIv2.";
+     reference
+      "RFC 2579: Textual Conventions for SMIv2";
+   }
+
+   typedef mac-address {
+     type string {
+       pattern '[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}';
+     }
+     description
+      "The mac-address type represents an IEEE 802 MAC address.
+       The canonical representation uses lowercase characters.
+
+       In the value set and its semantics, this type is equivalent
+       to the MacAddress textual convention of the SMIv2.";
+     reference
+      "IEEE 802: IEEE Standard for Local and Metropolitan Area
+                 Networks: Overview and Architecture
+       RFC 2579: Textual Conventions for SMIv2";
+   }
+
+   /*** collection of XML specific types ***/
+
+   typedef xpath1.0 {
+     type string;
+     description
+      "This type represents an XPATH 1.0 expression.
+
+       When a schema node is defined that uses this type, the
+       description of the schema node MUST specify the XPath
+       context in which the XPath expression is evaluated.";
+     reference
+      "XPATH: XML Path Language (XPath) Version 1.0";
+   }
+
+ }
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-type-test.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-type-test.yang
new file mode 100644 (file)
index 0000000..f0cb123
--- /dev/null
@@ -0,0 +1,57 @@
+module binary-type-test {
+    yang-version 1;
+    namespace "urn:binary:types:model";
+    prefix "btt";
+
+    import binary-types {
+        prefix "bin";
+        revision-date 2013-06-13;
+    }
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    description
+        "Simple test to test imported binary types and resolving of binary
+        type in leaf statement.";
+
+    revision "2013-06-13" {
+        reference "NO REF";
+    }
+
+    typedef binary-type {
+        type binary {
+            length 128;
+        }
+    }
+
+    container container-foo {
+        leaf binary-leaf {
+            type binary {
+                length 128;
+            }
+        }
+
+        list binary-list {
+            key "binary-key";
+
+            leaf binary-key {
+                type btt:binary-type;
+            }
+
+            leaf imported-simple-binary {
+                type bin:simple-binary;
+            }
+        }
+
+        leaf imported-restrict-binary {
+            type bin:restricted-binary;
+        }
+
+        leaf-list binary-list {
+            type binary {
+                length 256;
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-types@2013-06-13.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/binary-type-test-models/binary-types@2013-06-13.yang
new file mode 100644 (file)
index 0000000..df55441
--- /dev/null
@@ -0,0 +1,38 @@
+ module binary-types {
+
+   namespace "urn:binary:types";
+   prefix "bin";
+
+   organization "OPEN DAYLIGHT";
+
+   contact "http://www.opendaylight.org/";
+
+   description "Stand alone binary types declaration file for testing
+   purposes only.";
+
+   revision 2013-06-13 {
+     description
+      "Initial revision.";
+     reference
+      "NO REFERENCE";
+   }
+
+   /*** collection of protocol field related types ***/
+
+   typedef simple-binary {
+     type binary;
+   }
+
+   typedef restricted-binary {
+     type binary {
+        length 24;
+     }
+   }
+
+   typedef composite-binary {
+     type union {
+        type bin:simple-binary;
+        type bin:restricted-binary;
+     }
+   }
+ }
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/abstract-topology@2013-02-08.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/abstract-topology@2013-02-08.yang
new file mode 100644 (file)
index 0000000..d4a7341
--- /dev/null
@@ -0,0 +1,153 @@
+module abstract-topology {
+    yang-version 1;
+    namespace "urn:model:abstract:topology";
+    prefix "tp";
+
+    import ietf-inet-types {
+        prefix "inet";
+        revision-date 2010-09-24;
+    }
+
+    import ietf-interfaces {
+        prefix "if";
+        revision-date 2012-11-15;
+    }
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    description
+        "This module contains the definitions of elements that creates network 
+    topology i.e. definition of network nodes and links. This module is not designed to be used solely for network representation. This module SHOULD be used as base module in defining the network topology.";
+
+    revision "2013-02-08" {
+        reference "~~~ WILL BE DEFINED LATER";
+    }
+    
+    revision "2013-01-01" {
+        reference "~~~ WILL BE DEFINED LATER";
+    }
+    
+    typedef node-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-nodes/tp:network-node/tp:node-id";
+        }
+        description "This type is used for leafs that reference network node instance.";
+    }
+
+    typedef link-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-links/tp:network-link/tp:link-id";
+        }
+        description "This type is used for leafs that reference network link instance.";
+    }
+
+    typedef interface-id-ref {
+        type leafref {
+            path "/tp:topology/tp:interfaces/tp:interface/tp:interface-id";
+        }
+    }
+
+    container topology {
+        description "This is the model of abstract topology which contains only Network Nodes and Network Links. Each topology MUST be identified by unique topology-id for reason that the store could contain many topologies.";
+
+        leaf topology-id {
+            type inet:uri;
+            description "It is presumed that datastore will contain many topologies. To distinguish between topologies it is vital to have
+            UNIQUE topology identifier.";
+        }
+
+        container network-nodes {
+            list network-node {
+                key "node-id";
+
+                leaf node-id {
+                    type inet:uri;
+                    description "The Topology identifier of network-node.";
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Node contains.";
+                }
+                description "The list of network nodes defined for topology.";
+            }
+        }
+
+        container interfaces {
+            list interface {
+                key "interface-id";
+
+                leaf interface-id {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:name";
+                    }
+                }
+
+                leaf-list higher-layer-if {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:higher-layer-if";
+                    }
+                }
+
+                leaf oper-status {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:oper-status";
+                    }
+                }
+
+                leaf link-up-down-trap-enable {
+                    type leafref {
+                        path "/if:interfaces/if:interface/if:link-up-down-trap-enable";
+                    }
+                }
+            }
+        }
+        
+        container network-links {
+            list network-link {
+                key "link-id";
+
+                leaf link-id {
+                    type inet:uri;
+                    description "";
+                }
+
+                container source-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Source node identifier.";
+                    }
+                }
+
+                container destination-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Destination node identifier.";
+                    }
+                }
+
+                container tunnels {
+                    list tunnel {
+                        key "tunnel-id";
+
+                        leaf tunnel-id {
+                            type leafref {
+                                path "../../../link-id";
+                            }
+                        }
+                    }
+                }
+
+                leaf interface {
+                    type interface-id-ref;
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Link contains.";
+                }
+                description "The Network Link which is defined by Local (Source) and Remote (Destination) Network Nodes. Every link MUST be defined either by identifier and
+                his local and remote Network Nodes (In real applications it is common that many links are originated from one node and end up in same remote node). To ensure that we would always know to distinguish between links, every link SHOULD have identifier.";
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/ietf-inet-types@2010-09-24.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/enum-test-models/ietf-inet-types@2010-09-24.yang
new file mode 100644 (file)
index 0000000..6a6c748
--- /dev/null
@@ -0,0 +1,418 @@
+ module ietf-inet-types {
+
+   namespace "urn:ietf:params:xml:ns:yang:ietf-inet-types";
+   prefix "inet";
+
+   organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+   contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Partain
+               <mailto:david.partain@ericsson.com>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     Editor:   Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>";
+
+   description
+    "This module contains a collection of generally useful derived
+     YANG data types for Internet addresses and related things.
+
+     Copyright (c) 2010 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or without
+     modification, is permitted pursuant to, and subject to the license
+     terms contained in, the Simplified BSD License set forth in Section
+     4.c of the IETF Trust's Legal Provisions Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6021; see
+     the RFC itself for full legal notices.";
+
+   revision 2010-09-24 {
+     description
+      "Initial revision.";
+     reference
+      "RFC 6021: Common YANG Data Types";
+   }
+
+   /*** collection of protocol field related types ***/
+
+   typedef ip-version {
+     type enumeration {
+       enum unknown {
+         value "0";
+         description
+          "An unknown or unspecified version of the Internet protocol.";
+       }
+       enum ipv4 {
+         value "1";
+         description
+          "The IPv4 protocol as defined in RFC 791.";
+       }
+       enum ipv6 {
+         value "2";
+         description
+          "The IPv6 protocol as defined in RFC 2460.";
+       }
+     }
+     description
+      "This value represents the version of the IP protocol.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetVersion textual convention of the SMIv2.";
+     reference
+      "RFC  791: Internet Protocol
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   typedef dscp {
+     type uint8 {
+       range "0..63";
+     }
+     description
+      "The dscp type represents a Differentiated Services Code-Point
+       that may be used for marking packets in a traffic stream.
+
+       In the value set and its semantics, this type is equivalent
+       to the Dscp textual convention of the SMIv2.";
+     reference
+      "RFC 3289: Management Information Base for the Differentiated
+                 Services Architecture
+       RFC 2474: Definition of the Differentiated Services Field
+                 (DS Field) in the IPv4 and IPv6 Headers
+       RFC 2780: IANA Allocation Guidelines For Values In
+                 the Internet Protocol and Related Headers";
+   }
+
+   typedef ipv6-flow-label {
+     type uint32 {
+       range "0..1048575";
+     }
+     description
+      "The flow-label type represents flow identifier or Flow Label
+       in an IPv6 packet header that may be used to discriminate
+       traffic flows.
+
+       In the value set and its semantics, this type is equivalent
+       to the IPv6FlowLabel textual convention of the SMIv2.";
+     reference
+      "RFC 3595: Textual Conventions for IPv6 Flow Label
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification";
+   }
+
+   typedef port-number {
+     type uint16 {
+       range "0..65535";
+     }
+     description
+      "The port-number type represents a 16-bit port number of an
+       Internet transport layer protocol such as UDP, TCP, DCCP, or
+       SCTP.  Port numbers are assigned by IANA.  A current list of
+       all assignments is available from <http://www.iana.org/>.
+
+       Note that the port number value zero is reserved by IANA.  In
+       situations where the value zero does not make sense, it can
+       be excluded by subtyping the port-number type.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetPortNumber textual convention of the SMIv2.";
+     reference
+      "RFC  768: User Datagram Protocol
+       RFC  793: Transmission Control Protocol
+       RFC 4960: Stream Control Transmission Protocol
+       RFC 4340: Datagram Congestion Control Protocol (DCCP)
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of autonomous system related types ***/
+
+   typedef as-number {
+     type uint32;
+     description
+      "The as-number type represents autonomous system numbers
+       which identify an Autonomous System (AS).  An AS is a set
+       of routers under a single technical administration, using
+       an interior gateway protocol and common metrics to route
+       packets within the AS, and using an exterior gateway
+       protocol to route packets to other ASs'.  IANA maintains
+       the AS number space and has delegated large parts to the
+       regional registries.
+
+       Autonomous system numbers were originally limited to 16
+       bits.  BGP extensions have enlarged the autonomous system
+       number space to 32 bits.  This type therefore uses an uint32
+       base type without a range restriction in order to support
+       a larger autonomous system number space.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetAutonomousSystemNumber textual convention of
+       the SMIv2.";
+     reference
+      "RFC 1930: Guidelines for creation, selection, and registration
+                 of an Autonomous System (AS)
+       RFC 4271: A Border Gateway Protocol 4 (BGP-4)
+       RFC 4893: BGP Support for Four-octet AS Number Space
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of IP address and hostname related types ***/
+
+   typedef ip-address {
+     type union {
+       type inet:ipv4-address;
+       type inet:ipv6-address;
+     }
+     description
+      "The ip-address type represents an IP address and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-address {
+     type string {
+       pattern
+         '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+       +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+       + '(%[\p{N}\p{L}]+)?';
+     }
+     description
+       "The ipv4-address type represents an IPv4 address in
+        dotted-quad notation.  The IPv4 address may include a zone
+        index, separated by a % sign.
+
+        The zone index is used to disambiguate identical address
+        values.  For link-local addresses, the zone index will
+        typically be the interface index number or the name of an
+        interface.  If the zone index is not present, the default
+        zone of the device will be used.
+
+        The canonical format for the zone index is the numerical
+        format";
+   }
+
+   typedef ipv6-address {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(%[\p{N}\p{L}]+)?';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(%.+)?';
+     }
+     description
+      "The ipv6-address type represents an IPv6 address in full,
+       mixed, shortened, and shortened-mixed notation.  The IPv6
+       address may include a zone index, separated by a % sign.
+
+       The zone index is used to disambiguate identical address
+       values.  For link-local addresses, the zone index will
+       typically be the interface index number or the name of an
+       interface.  If the zone index is not present, the default
+       zone of the device will be used.
+
+       The canonical format of IPv6 addresses uses the compressed
+       format described in RFC 4291, Section 2.2, item 2 with the
+       following additional rules: the :: substitution must be
+       applied to the longest sequence of all-zero 16-bit chunks
+       in an IPv6 address.  If there is a tie, the first sequence
+       of all-zero 16-bit chunks is replaced by ::.  Single
+       all-zero 16-bit chunks are not compressed.  The canonical
+       format uses lowercase characters and leading zeros are
+       not allowed.  The canonical format for the zone index is
+       the numerical format as described in RFC 4007, Section
+       11.2.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture
+       RFC 4007: IPv6 Scoped Address Architecture
+       RFC 5952: A Recommendation for IPv6 Address Text Representation";
+   }
+
+   typedef ip-prefix {
+     type union {
+       type inet:ipv4-prefix;
+       type inet:ipv6-prefix;
+     }
+     description
+      "The ip-prefix type represents an IP prefix and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-prefix {
+     type string {
+       pattern
+          '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+        +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+        + '/(([0-9])|([1-2][0-9])|(3[0-2]))';
+     }
+     description
+      "The ipv4-prefix type represents an IPv4 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal to 32.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The canonical format of an IPv4 prefix has all bits of
+       the IPv4 address set to zero that are not part of the
+       IPv4 prefix.";
+   }
+
+   typedef ipv6-prefix {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(/.+)';
+     }
+     description
+      "The ipv6-prefix type represents an IPv6 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal 128.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The IPv6 address should have all bits that do not belong
+       to the prefix set to zero.
+
+       The canonical format of an IPv6 prefix has all bits of
+       the IPv6 address set to zero that are not part of the
+       IPv6 prefix.  Furthermore, IPv6 address is represented
+       in the compressed format described in RFC 4291, Section
+       2.2, item 2 with the following additional rules: the ::
+       substitution must be applied to the longest sequence of
+       all-zero 16-bit chunks in an IPv6 address.  If there is
+       a tie, the first sequence of all-zero 16-bit chunks is
+       replaced by ::.  Single all-zero 16-bit chunks are not
+       compressed.  The canonical format uses lowercase
+       characters and leading zeros are not allowed.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture";
+   }
+
+   /*** collection of domain name and URI types ***/
+
+   typedef domain-name {
+     type string {
+       pattern '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*'
+            +  '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)'
+            +  '|\.';
+       length "1..253";
+     }
+     description
+      "The domain-name type represents a DNS domain name.  The
+       name SHOULD be fully qualified whenever possible.
+
+       Internet domain names are only loosely specified.  Section
+       3.5 of RFC 1034 recommends a syntax (modified in Section
+       2.1 of RFC 1123).  The pattern above is intended to allow
+       for current practice in domain name use, and some possible
+       future expansion.  It is designed to hold various types of
+       domain names, including names used for A or AAAA records
+       (host names) and other records, such as SRV records.  Note
+       that Internet host names have a stricter syntax (described
+       in RFC 952) than the DNS recommendations in RFCs 1034 and
+       1123, and that systems that want to store host names in
+       schema nodes using the domain-name type are recommended to
+       adhere to this stricter standard to ensure interoperability.
+
+       The encoding of DNS names in the DNS protocol is limited
+       to 255 characters.  Since the encoding consists of labels
+       prefixed by a length bytes and there is a trailing NULL
+       byte, only 253 characters can appear in the textual dotted
+       notation.
+
+       The description clause of schema nodes using the domain-name
+       type MUST describe when and how these names are resolved to
+       IP addresses.  Note that the resolution of a domain-name value
+       may require to query multiple DNS records (e.g., A for IPv4
+       and AAAA for IPv6).  The order of the resolution process and
+       which DNS record takes precedence can either be defined
+       explicitely or it may depend on the configuration of the
+       resolver.
+
+       Domain-name values use the US-ASCII encoding.  Their canonical
+       format uses lowercase US-ASCII characters.  Internationalized
+       domain names MUST be encoded in punycode as described in RFC
+       3492";
+     reference
+      "RFC  952: DoD Internet Host Table Specification
+       RFC 1034: Domain Names - Concepts and Facilities
+       RFC 1123: Requirements for Internet Hosts -- Application
+                 and Support
+       RFC 2782: A DNS RR for specifying the location of services
+                 (DNS SRV)
+       RFC 3492: Punycode: A Bootstring encoding of Unicode for
+                 Internationalized Domain Names in Applications
+                 (IDNA)
+       RFC 5891: Internationalizing Domain Names in Applications
+                 (IDNA): Protocol";
+   }
+
+   typedef host {
+     type union {
+       type inet:ip-address;
+       type inet:domain-name;
+     }
+     description
+      "The host type represents either an IP address or a DNS
+       domain name.";
+   }
+
+   typedef uri {
+     type string;
+     description
+      "The uri type represents a Uniform Resource Identifier
+       (URI) as defined by STD 66.
+
+       Objects using the uri type MUST be in US-ASCII encoding,
+       and MUST be normalized as described by RFC 3986 Sections
+       6.2.1, 6.2.2.1, and 6.2.2.2.  All unnecessary
+       percent-encoding is removed, and all case-insensitive
+       characters are set to lowercase except for hexadecimal
+       digits, which are normalized to uppercase as described in
+       Section 6.2.2.1.
+
+       The purpose of this normalization is to help provide
+       unique URIs.  Note that this normalization is not
+       sufficient to provide uniqueness.  Two URIs that are
+       textually distinct after this normalization may still be
+       equivalent.
+
+       Objects using the uri type may restrict the schemes that
+       they permit.  For example, 'data:' and 'urn:' schemes
+       might not be appropriate.
+
+       A zero-length URI is not a valid URI.  This can be used to
+       express 'URI absent' where required.
+
+       In the value set and its semantics, this type is equivalent
+       to the Uri SMIv2 textual convention defined in RFC 5017.";
+     reference
+      "RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
+       RFC 3305: Report from the Joint W3C/IETF URI Planning Interest
+                 Group: Uniform Resource Identifiers (URIs), URLs,
+                 and Uniform Resource Names (URNs): Clarifications
+                 and Recommendations
+       RFC 5017: MIB Textual Conventions for Uniform Resource
+                 Identifiers (URIs)";
+   }
+
+ }
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/abstract-topology.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/abstract-topology.yang
new file mode 100644 (file)
index 0000000..a4b589b
--- /dev/null
@@ -0,0 +1,120 @@
+module abstract-topology {
+    yang-version 1;
+    namespace "urn:model:abstract:topology";
+    prefix "tp";
+
+    import ietf-inet-types { 
+        prefix "inet"; 
+        revision-date 2010-09-24;
+    }
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";
+
+    description
+        "This module contains the definitions of elements that creates network 
+    topology i.e. definition of network nodes and links. This module is not designed to be used solely for network representation. This module SHOULD be used as base module in defining the network topology.";
+
+    revision "2013-02-08" {
+        reference "~~~ WILL BE DEFINED LATER";
+    }
+    
+    revision "2013-01-01" {
+        reference "~~~ WILL BE DEFINED LATER";
+    }
+
+    typedef union-enum {
+        type union {
+            type int32;
+            type enumeration {
+                enum "unbounded";
+            }
+        }
+    }
+
+    typedef link-address {
+        type union {
+            type inet:ip-address;
+            type string;
+        }
+    }
+
+    typedef node-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-nodes/tp:network-node/tp:node-id";
+        }
+        description "This type is used for leafs that reference network node instance.";
+    }
+
+    typedef link-id-ref {
+        type leafref {
+            path "/tp:topology/tp:network-links/tp:network-link/tp:link-id";
+        }
+        description "This type is used for leafs that reference network link instance.";
+    }
+
+    container topology {
+        description "This is the model of abstract topology which contains only Network Nodes and Network Links. Each topology MUST be identified by unique topology-id for reason that the store could contain many topologies.";
+
+        leaf topology-id {
+            type inet:uri;
+            description "It is presumed that datastore will contain many topologies. To distinguish between topologies it is vital to have
+            UNIQUE topology identifier.";
+        }
+
+        container network-nodes {
+            list network-node {
+                key "node-id";
+
+                leaf node-id {
+                    type inet:uri;
+                    description "The Topology identifier of network-node.";
+                }
+
+                leaf bounding {
+                    type union-enum;
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Node contains.";
+                }
+                description "The list of network nodes defined for topology.";
+            }
+        }
+        
+        container network-links {
+            list network-link {
+                key "link-id";
+
+                leaf link-id {
+                    type inet:uri;
+                    description "";
+                }
+
+                leaf link-address {
+                    type link-address;
+                }
+
+                container source-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Source node identifier.";
+                    }
+                }
+
+                container destination-node {
+                    leaf id {
+                        type node-id-ref;
+                        description "Destination node identifier.";
+                    }
+                }
+
+                container attributes {
+                    description "Aditional attributes that can Network Link contains.";
+                }
+                description "The Network Link which is defined by Local (Source) and Remote (Destination) Network Nodes. Every link MUST be defined either by identifier and
+                his local and remote Network Nodes (In real applications it is common that many links are originated from one node and end up in same remote node). To ensure that we would always know to distinguish between links, every link SHOULD have identifier.";
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/ietf-inet-types@2010-09-24.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/union-test-models/ietf-inet-types@2010-09-24.yang
new file mode 100644 (file)
index 0000000..6a6c748
--- /dev/null
@@ -0,0 +1,418 @@
+ module ietf-inet-types {
+
+   namespace "urn:ietf:params:xml:ns:yang:ietf-inet-types";
+   prefix "inet";
+
+   organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+   contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Partain
+               <mailto:david.partain@ericsson.com>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     Editor:   Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>";
+
+   description
+    "This module contains a collection of generally useful derived
+     YANG data types for Internet addresses and related things.
+
+     Copyright (c) 2010 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or without
+     modification, is permitted pursuant to, and subject to the license
+     terms contained in, the Simplified BSD License set forth in Section
+     4.c of the IETF Trust's Legal Provisions Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6021; see
+     the RFC itself for full legal notices.";
+
+   revision 2010-09-24 {
+     description
+      "Initial revision.";
+     reference
+      "RFC 6021: Common YANG Data Types";
+   }
+
+   /*** collection of protocol field related types ***/
+
+   typedef ip-version {
+     type enumeration {
+       enum unknown {
+         value "0";
+         description
+          "An unknown or unspecified version of the Internet protocol.";
+       }
+       enum ipv4 {
+         value "1";
+         description
+          "The IPv4 protocol as defined in RFC 791.";
+       }
+       enum ipv6 {
+         value "2";
+         description
+          "The IPv6 protocol as defined in RFC 2460.";
+       }
+     }
+     description
+      "This value represents the version of the IP protocol.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetVersion textual convention of the SMIv2.";
+     reference
+      "RFC  791: Internet Protocol
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   typedef dscp {
+     type uint8 {
+       range "0..63";
+     }
+     description
+      "The dscp type represents a Differentiated Services Code-Point
+       that may be used for marking packets in a traffic stream.
+
+       In the value set and its semantics, this type is equivalent
+       to the Dscp textual convention of the SMIv2.";
+     reference
+      "RFC 3289: Management Information Base for the Differentiated
+                 Services Architecture
+       RFC 2474: Definition of the Differentiated Services Field
+                 (DS Field) in the IPv4 and IPv6 Headers
+       RFC 2780: IANA Allocation Guidelines For Values In
+                 the Internet Protocol and Related Headers";
+   }
+
+   typedef ipv6-flow-label {
+     type uint32 {
+       range "0..1048575";
+     }
+     description
+      "The flow-label type represents flow identifier or Flow Label
+       in an IPv6 packet header that may be used to discriminate
+       traffic flows.
+
+       In the value set and its semantics, this type is equivalent
+       to the IPv6FlowLabel textual convention of the SMIv2.";
+     reference
+      "RFC 3595: Textual Conventions for IPv6 Flow Label
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification";
+   }
+
+   typedef port-number {
+     type uint16 {
+       range "0..65535";
+     }
+     description
+      "The port-number type represents a 16-bit port number of an
+       Internet transport layer protocol such as UDP, TCP, DCCP, or
+       SCTP.  Port numbers are assigned by IANA.  A current list of
+       all assignments is available from <http://www.iana.org/>.
+
+       Note that the port number value zero is reserved by IANA.  In
+       situations where the value zero does not make sense, it can
+       be excluded by subtyping the port-number type.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetPortNumber textual convention of the SMIv2.";
+     reference
+      "RFC  768: User Datagram Protocol
+       RFC  793: Transmission Control Protocol
+       RFC 4960: Stream Control Transmission Protocol
+       RFC 4340: Datagram Congestion Control Protocol (DCCP)
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of autonomous system related types ***/
+
+   typedef as-number {
+     type uint32;
+     description
+      "The as-number type represents autonomous system numbers
+       which identify an Autonomous System (AS).  An AS is a set
+       of routers under a single technical administration, using
+       an interior gateway protocol and common metrics to route
+       packets within the AS, and using an exterior gateway
+       protocol to route packets to other ASs'.  IANA maintains
+       the AS number space and has delegated large parts to the
+       regional registries.
+
+       Autonomous system numbers were originally limited to 16
+       bits.  BGP extensions have enlarged the autonomous system
+       number space to 32 bits.  This type therefore uses an uint32
+       base type without a range restriction in order to support
+       a larger autonomous system number space.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetAutonomousSystemNumber textual convention of
+       the SMIv2.";
+     reference
+      "RFC 1930: Guidelines for creation, selection, and registration
+                 of an Autonomous System (AS)
+       RFC 4271: A Border Gateway Protocol 4 (BGP-4)
+       RFC 4893: BGP Support for Four-octet AS Number Space
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of IP address and hostname related types ***/
+
+   typedef ip-address {
+     type union {
+       type inet:ipv4-address;
+       type inet:ipv6-address;
+     }
+     description
+      "The ip-address type represents an IP address and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-address {
+     type string {
+       pattern
+         '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+       +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+       + '(%[\p{N}\p{L}]+)?';
+     }
+     description
+       "The ipv4-address type represents an IPv4 address in
+        dotted-quad notation.  The IPv4 address may include a zone
+        index, separated by a % sign.
+
+        The zone index is used to disambiguate identical address
+        values.  For link-local addresses, the zone index will
+        typically be the interface index number or the name of an
+        interface.  If the zone index is not present, the default
+        zone of the device will be used.
+
+        The canonical format for the zone index is the numerical
+        format";
+   }
+
+   typedef ipv6-address {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(%[\p{N}\p{L}]+)?';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(%.+)?';
+     }
+     description
+      "The ipv6-address type represents an IPv6 address in full,
+       mixed, shortened, and shortened-mixed notation.  The IPv6
+       address may include a zone index, separated by a % sign.
+
+       The zone index is used to disambiguate identical address
+       values.  For link-local addresses, the zone index will
+       typically be the interface index number or the name of an
+       interface.  If the zone index is not present, the default
+       zone of the device will be used.
+
+       The canonical format of IPv6 addresses uses the compressed
+       format described in RFC 4291, Section 2.2, item 2 with the
+       following additional rules: the :: substitution must be
+       applied to the longest sequence of all-zero 16-bit chunks
+       in an IPv6 address.  If there is a tie, the first sequence
+       of all-zero 16-bit chunks is replaced by ::.  Single
+       all-zero 16-bit chunks are not compressed.  The canonical
+       format uses lowercase characters and leading zeros are
+       not allowed.  The canonical format for the zone index is
+       the numerical format as described in RFC 4007, Section
+       11.2.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture
+       RFC 4007: IPv6 Scoped Address Architecture
+       RFC 5952: A Recommendation for IPv6 Address Text Representation";
+   }
+
+   typedef ip-prefix {
+     type union {
+       type inet:ipv4-prefix;
+       type inet:ipv6-prefix;
+     }
+     description
+      "The ip-prefix type represents an IP prefix and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-prefix {
+     type string {
+       pattern
+          '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+        +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+        + '/(([0-9])|([1-2][0-9])|(3[0-2]))';
+     }
+     description
+      "The ipv4-prefix type represents an IPv4 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal to 32.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The canonical format of an IPv4 prefix has all bits of
+       the IPv4 address set to zero that are not part of the
+       IPv4 prefix.";
+   }
+
+   typedef ipv6-prefix {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(/.+)';
+     }
+     description
+      "The ipv6-prefix type represents an IPv6 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal 128.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The IPv6 address should have all bits that do not belong
+       to the prefix set to zero.
+
+       The canonical format of an IPv6 prefix has all bits of
+       the IPv6 address set to zero that are not part of the
+       IPv6 prefix.  Furthermore, IPv6 address is represented
+       in the compressed format described in RFC 4291, Section
+       2.2, item 2 with the following additional rules: the ::
+       substitution must be applied to the longest sequence of
+       all-zero 16-bit chunks in an IPv6 address.  If there is
+       a tie, the first sequence of all-zero 16-bit chunks is
+       replaced by ::.  Single all-zero 16-bit chunks are not
+       compressed.  The canonical format uses lowercase
+       characters and leading zeros are not allowed.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture";
+   }
+
+   /*** collection of domain name and URI types ***/
+
+   typedef domain-name {
+     type string {
+       pattern '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*'
+            +  '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)'
+            +  '|\.';
+       length "1..253";
+     }
+     description
+      "The domain-name type represents a DNS domain name.  The
+       name SHOULD be fully qualified whenever possible.
+
+       Internet domain names are only loosely specified.  Section
+       3.5 of RFC 1034 recommends a syntax (modified in Section
+       2.1 of RFC 1123).  The pattern above is intended to allow
+       for current practice in domain name use, and some possible
+       future expansion.  It is designed to hold various types of
+       domain names, including names used for A or AAAA records
+       (host names) and other records, such as SRV records.  Note
+       that Internet host names have a stricter syntax (described
+       in RFC 952) than the DNS recommendations in RFCs 1034 and
+       1123, and that systems that want to store host names in
+       schema nodes using the domain-name type are recommended to
+       adhere to this stricter standard to ensure interoperability.
+
+       The encoding of DNS names in the DNS protocol is limited
+       to 255 characters.  Since the encoding consists of labels
+       prefixed by a length bytes and there is a trailing NULL
+       byte, only 253 characters can appear in the textual dotted
+       notation.
+
+       The description clause of schema nodes using the domain-name
+       type MUST describe when and how these names are resolved to
+       IP addresses.  Note that the resolution of a domain-name value
+       may require to query multiple DNS records (e.g., A for IPv4
+       and AAAA for IPv6).  The order of the resolution process and
+       which DNS record takes precedence can either be defined
+       explicitely or it may depend on the configuration of the
+       resolver.
+
+       Domain-name values use the US-ASCII encoding.  Their canonical
+       format uses lowercase US-ASCII characters.  Internationalized
+       domain names MUST be encoded in punycode as described in RFC
+       3492";
+     reference
+      "RFC  952: DoD Internet Host Table Specification
+       RFC 1034: Domain Names - Concepts and Facilities
+       RFC 1123: Requirements for Internet Hosts -- Application
+                 and Support
+       RFC 2782: A DNS RR for specifying the location of services
+                 (DNS SRV)
+       RFC 3492: Punycode: A Bootstring encoding of Unicode for
+                 Internationalized Domain Names in Applications
+                 (IDNA)
+       RFC 5891: Internationalizing Domain Names in Applications
+                 (IDNA): Protocol";
+   }
+
+   typedef host {
+     type union {
+       type inet:ip-address;
+       type inet:domain-name;
+     }
+     description
+      "The host type represents either an IP address or a DNS
+       domain name.";
+   }
+
+   typedef uri {
+     type string;
+     description
+      "The uri type represents a Uniform Resource Identifier
+       (URI) as defined by STD 66.
+
+       Objects using the uri type MUST be in US-ASCII encoding,
+       and MUST be normalized as described by RFC 3986 Sections
+       6.2.1, 6.2.2.1, and 6.2.2.2.  All unnecessary
+       percent-encoding is removed, and all case-insensitive
+       characters are set to lowercase except for hexadecimal
+       digits, which are normalized to uppercase as described in
+       Section 6.2.2.1.
+
+       The purpose of this normalization is to help provide
+       unique URIs.  Note that this normalization is not
+       sufficient to provide uniqueness.  Two URIs that are
+       textually distinct after this normalization may still be
+       equivalent.
+
+       Objects using the uri type may restrict the schemes that
+       they permit.  For example, 'data:' and 'urn:' schemes
+       might not be appropriate.
+
+       A zero-length URI is not a valid URI.  This can be used to
+       express 'URI absent' where required.
+
+       In the value set and its semantics, this type is equivalent
+       to the Uri SMIv2 textual convention defined in RFC 5017.";
+     reference
+      "RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
+       RFC 3305: Report from the Joint W3C/IETF URI Planning Interest
+                 Group: Uniform Resource Identifiers (URIs), URLs,
+                 and Uniform Resource Names (URNs): Clarifications
+                 and Recommendations
+       RFC 5017: MIB Textual Conventions for Uniform Resource
+                 Identifiers (URIs)";
+   }
+
+ }
\ No newline at end of file
index 3c00dee98ea30e95cb4547ffbb1b29cc5f2386f0..93be5a667ca23307002dc7ad73ff1234a94a91a8 100644 (file)
@@ -15,5 +15,21 @@ public interface TypeProvider {
     @Deprecated\r
     Type javaTypeForYangType(String type);\r
 \r
+    /**\r
+     * Resolve of yang Type Definition to it's java counter part.\r
+     * If the Type Definition contains one of yang primitive types the method\r
+     * will return java.lang. counterpart. (For example if yang type is int32\r
+     * the java counterpart is java.lang.Integer). In case that Type\r
+     * Definition contains extended type defined via yang typedef statement\r
+     * the method SHOULD return Generated Type or Generated Transfer Object\r
+     * if that Type is correctly referenced to resolved imported yang module.\r
+     * The method will return <cdoe>null</cdoe> value in situations that\r
+     * TypeDefinition can't be resolved (either due missing yang import or\r
+     * incorrectly specified type).\r
+     *\r
+     *\r
+     * @param type Type Definition to resolve from\r
+     * @return Resolved Type\r
+     */\r
     Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type);\r
 }\r
index 6683230d028ef8c419b05413d0828a31fc84f772..a9d1cf5227c4efb575debadfb52eb288f64032b7 100644 (file)
@@ -63,7 +63,9 @@ public class AbstractBaseType implements Type {
 \r
     @Override\r
     public String toString() {\r
-\r
+        if (packageName.isEmpty()) {\r
+            return "Type (" + name + ")";\r
+        }\r
         return "Type (" + packageName + "." + name + ")";\r
     }\r
 \r
index 1fb862291f19700b673a153112bf6f4352d02553..ef65a0e8f03add4a1653406c6069ed18e6c3f148 100644 (file)
@@ -3,11 +3,14 @@ package org.opendaylight.controller.binding.generator.util;
 import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTOBuilder;
 import org.opendaylight.controller.yang.common.QName;
-import org.opendaylight.controller.yang.model.api.*;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaNode;
+import org.opendaylight.controller.yang.model.api.SchemaPath;
+import org.opendaylight.controller.yang.model.api.TypeDefinition;
 
 import java.util.*;
 
-public class BindingGeneratorUtil {
+public final class BindingGeneratorUtil {
 
     private static final String[] SET_VALUES = new String[]{"abstract",
             "assert", "boolean", "break", "byte", "case", "catch", "char",
@@ -19,7 +22,8 @@ public class BindingGeneratorUtil {
             "super", "switch", "synchronized", "this", "throw", "throws",
             "transient", "true", "try", "void", "volatile", "while"};
 
-    private BindingGeneratorUtil() {}
+    private BindingGeneratorUtil() {
+    }
 
     public static final Set<String> JAVA_RESERVED_WORDS = new HashSet<String>(
             Arrays.asList(SET_VALUES));
@@ -110,22 +114,43 @@ public class BindingGeneratorUtil {
 
     public static String packageNameForGeneratedType(
             final String basePackageName, final SchemaPath schemaPath) {
+        if (basePackageName == null) {
+            throw new IllegalArgumentException("Base Package Name cannot be " +
+                    "NULL!");
+        }
+        if (schemaPath == null) {
+            throw new IllegalArgumentException("Schema Path cannot be NULL!");
+        }
+
         final StringBuilder builder = new StringBuilder();
         builder.append(basePackageName);
-        if ((schemaPath != null) && (schemaPath.getPath() != null)) {
-            final List<QName> pathToNode = schemaPath.getPath();
-            final int traversalSteps = (pathToNode.size() - 1);
-            for (int i = 0; i < traversalSteps; ++i) {
-                builder.append(".");
-                String nodeLocalName = pathToNode.get(i).getLocalName();
-
-                nodeLocalName = nodeLocalName.replace(":", ".");
-                nodeLocalName = nodeLocalName.replace("-", ".");
-                builder.append(nodeLocalName);
-            }
-            return validateJavaPackage(builder.toString());
+        final List<QName> pathToNode = schemaPath.getPath();
+        final int traversalSteps = (pathToNode.size() - 1);
+        for (int i = 0; i < traversalSteps; ++i) {
+            builder.append(".");
+            String nodeLocalName = pathToNode.get(i).getLocalName();
+
+            nodeLocalName = nodeLocalName.replace(":", ".");
+            nodeLocalName = nodeLocalName.replace("-", ".");
+            builder.append(nodeLocalName);
         }
-        return null;
+        return validateJavaPackage(builder.toString());
+    }
+
+    public static String packageNameForTypeDefinition(
+            final String basePackageName, final TypeDefinition<?> typeDefinition) {
+        if (basePackageName == null) {
+            throw new IllegalArgumentException("Base Package Name cannot be " +
+                    "NULL!");
+        }
+        if (typeDefinition == null) {
+            throw new IllegalArgumentException("Type Definition reference " +
+                    "cannot be NULL!");
+        }
+
+        final StringBuilder builder = new StringBuilder();
+        builder.append(basePackageName);
+        return validateJavaPackage(builder.toString());
     }
 
     public static String parseToClassName(String token) {
index 87bb47cb76e6819f9b93fd0180154b4545c25bd8..2e5bbf0a07a6f0a73d41af7f92c510880aae6963 100644 (file)
@@ -11,31 +11,36 @@ import java.util.List;
 import java.util.Map;\r
 import java.util.Set;\r
 \r
+import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;\r
 import org.opendaylight.controller.sal.binding.model.api.ConcreteType;\r
+import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;\r
 import org.opendaylight.controller.sal.binding.model.api.ParameterizedType;\r
 import org.opendaylight.controller.sal.binding.model.api.Type;\r
+import org.opendaylight.controller.sal.binding.model.api.WildcardType;\r
 import org.opendaylight.controller.yang.binding.Augmentable;\r
 import org.opendaylight.controller.yang.binding.Augmentation;\r
+import org.opendaylight.controller.yang.binding.BaseIdentity;\r
 import org.opendaylight.controller.yang.binding.DataObject;\r
 \r
-public class Types {\r
+public final class Types {\r
     private static final Type SET_TYPE = typeForClass(Set.class);\r
     private static final Type LIST_TYPE = typeForClass(List.class);\r
     private static final Type MAP_TYPE = typeForClass(Map.class);\r
-    \r
     public static final Type DATA_OBJECT = typeForClass(DataObject.class);\r
-    \r
-    private Types() {\r
-    }\r
 \r
     public static ConcreteType voidType() {\r
         return new ConcreteTypeImpl(Void.class.getPackage().getName(),\r
                 Void.class.getSimpleName());\r
     }\r
 \r
+    public static final Type primitiveType(final String primitiveType) {\r
+        return new ConcreteTypeImpl("", primitiveType);\r
+    }\r
+\r
+\r
     /**\r
      * Returns an instance of {@link ConcreteType} describing the class\r
-     * \r
+     *\r
      * @param cls\r
      *            Class to describe\r
      * @return Description of class\r
@@ -48,7 +53,7 @@ public class Types {
     /**\r
      * Returns an instance of {@link ParameterizedType} describing the typed\r
      * {@link Map}<K,V>\r
-     * \r
+     *\r
      * @param keyType\r
      *            Key Type\r
      * @param valueType\r
@@ -62,7 +67,7 @@ public class Types {
     /**\r
      * Returns an instance of {@link ParameterizedType} describing the typed\r
      * {@link Set}<V> with concrete type of value.\r
-     * \r
+     *\r
      * @param valueType\r
      *            Value Type\r
      * @return Description of generic type instance of Set\r
@@ -74,7 +79,7 @@ public class Types {
     /**\r
      * Returns an instance of {@link ParameterizedType} describing the typed\r
      * {@link List}<V> with concrete type of value.\r
-     * \r
+     *\r
      * @param valueType\r
      *            Value Type\r
      * @return Description of type instance of List\r
@@ -83,8 +88,15 @@ public class Types {
         return parameterizedTypeFor(LIST_TYPE, valueType);\r
     }\r
 \r
+    public static GeneratedTransferObject getBaseIdentityTO() {\r
+        Class<BaseIdentity> cls = BaseIdentity.class;\r
+        GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(cls.getPackage().getName(),\r
+                cls.getSimpleName());\r
+        return gto.toInstance();\r
+    }\r
+\r
     /**\r
-     * \r
+     *\r
      * @param type\r
      * @param parameters\r
      * @return\r
@@ -93,17 +105,21 @@ public class Types {
             Type... parameters) {\r
         return new ParametrizedTypeImpl(type, parameters);\r
     }\r
-    \r
+\r
+    public static WildcardType wildcardTypeFor(String packageName, String typeName) {\r
+        return new WildcardTypeImpl(packageName, typeName);\r
+    }\r
+\r
     public static ParameterizedType augmentableTypeFor(Type valueType) {\r
         final Type augmentable = typeForClass(Augmentable.class);\r
         return parameterizedTypeFor(augmentable, valueType);\r
     }\r
-    \r
+\r
     public static ParameterizedType augmentationTypeFor(Type valueType) {\r
         final Type augmentation = typeForClass(Augmentation.class);\r
         return parameterizedTypeFor(augmentation, valueType);\r
     }\r
-    \r
+\r
     private static class ConcreteTypeImpl extends AbstractBaseType implements\r
             ConcreteType {\r
         private ConcreteTypeImpl(String pkName, String name) {\r
@@ -134,4 +150,12 @@ public class Types {
         }\r
 \r
     }\r
+\r
+    private static class WildcardTypeImpl extends AbstractBaseType\r
+            implements WildcardType {\r
+        public WildcardTypeImpl(String packageName, String typeName) {\r
+            super(packageName, typeName);\r
+        }\r
+    }\r
+\r
 }\r
index 01d9bbfa9fb05550d0e497df74fd89c0f52ba5c7..f1683fdc6435e86ccb98ea36389c1a24053b9d13 100644 (file)
@@ -16,6 +16,7 @@ import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
 import org.opendaylight.controller.sal.binding.model.api.Constant;
 import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferIdentityObject;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
 import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
 import org.opendaylight.controller.sal.binding.model.api.Type;
@@ -26,11 +27,11 @@ import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedP
 import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTOBuilder;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.MethodSignatureBuilder;
 
-public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
+public class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
     private String packageName;
     private final String name;
     private String comment = "";
-    
+
     private GeneratedTransferObject extendsType;
     private final List<Type> implementsTypes = new ArrayList<Type>();
     private final List<EnumBuilder> enumerations = new ArrayList<EnumBuilder>();
@@ -81,7 +82,7 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
         }
         return null;
     }
-    
+
     @Override
     public boolean addImplementsType(final Type genType) {
         if (genType != null) {
@@ -98,10 +99,11 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
         }
         return false;
     }
-    
+
     @Override
     public EnumBuilder addEnumeration(String name) {
-        final EnumBuilder builder = new EnumerationBuilderImpl(packageName,
+        final String innerPackageName = packageName + "." + this.name;
+        final EnumBuilder builder = new EnumerationBuilderImpl(innerPackageName,
                 name);
         enumerations.add(builder);
         return builder;
@@ -148,10 +150,20 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
 
     @Override
     public GeneratedTransferObject toInstance() {
-        return new GeneratedTransferObjectImpl(packageName, name, comment, 
-                annotationBuilders, extendsType, implementsTypes, constantDefintions, enumerations,
-                methodDefinitions, properties, equalsProperties,
-                hashProperties, toStringProperties);
+        return new GeneratedTransferObjectImpl(packageName, name, comment,
+                annotationBuilders, extendsType, implementsTypes,
+                constantDefintions, enumerations, methodDefinitions,
+                properties, equalsProperties, hashProperties,
+                toStringProperties);
+    }
+
+    @Override
+    public GeneratedTransferObject toIdentityInstance() {
+        return new GeneratedTransferIdentityObjectImpl(packageName, name, comment,
+                annotationBuilders, extendsType, implementsTypes,
+                constantDefintions, enumerations, methodDefinitions,
+                properties, equalsProperties, hashProperties,
+                toStringProperties);
     }
 
     private static final class GeneratedPropertyBuilderImpl implements
@@ -226,8 +238,9 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
 
         @Override
         public GeneratedProperty toInstance(final Type definingType) {
-            return new GeneratedPropertyImpl(name, comment, annotationBuilders, definingType,
-                    returnType, isFinal, isReadOnly, parameters, accessModifier);
+            return new GeneratedPropertyImpl(name, comment, annotationBuilders,
+                    definingType, returnType, isFinal, isReadOnly, parameters,
+                    accessModifier);
         }
     }
 
@@ -243,9 +256,10 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
         private final boolean isReadOnly;
         private final List<MethodSignature.Parameter> parameters;
         private final AccessModifier modifier;
-        
+
         public GeneratedPropertyImpl(final String name, final String comment,
-                final List<AnnotationTypeBuilder> annotationBuilders, final Type parent, final Type returnType,
+                final List<AnnotationTypeBuilder> annotationBuilders,
+                final Type parent, final Type returnType,
                 final boolean isFinal, final boolean isReadOnly,
                 final List<Parameter> parameters, final AccessModifier modifier) {
             super();
@@ -283,7 +297,7 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
         public List<AnnotationType> getAnnotations() {
             return annotations;
         }
-        
+
         @Override
         public Type getReturnType() {
             return returnType;
@@ -309,8 +323,6 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
             return isFinal;
         }
 
-        
-
         @Override
         public int hashCode() {
             final int prime = 31;
@@ -353,7 +365,8 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
                 if (other.returnType != null) {
                     return false;
                 }
-            } else if (!returnType.getPackageName().equals(other.returnType.getPackageName())) {
+            } else if (!returnType.getPackageName().equals(
+                    other.returnType.getPackageName())) {
                 return false;
             } else if (!returnType.getName().equals(other.returnType.getName())) {
                 return false;
@@ -393,7 +406,7 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
         }
     }
 
-    private static final class GeneratedTransferObjectImpl implements
+    private static class GeneratedTransferObjectImpl implements
             GeneratedTransferObject {
 
         private final String packageName;
@@ -411,8 +424,7 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
         private final List<Type> implementsTypes;
 
         public GeneratedTransferObjectImpl(final String packageName,
-                final String name,
-                final String comment,
+                final String name, final String comment,
                 final List<AnnotationTypeBuilder> annotationBuilders,
                 final GeneratedTransferObject extendsType,
                 final List<Type> implementsTypes,
@@ -429,7 +441,8 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
             this.comment = comment;
             this.annotations = toUnmodifiableAnnotations(annotationBuilders);
             this.extendsType = extendsType;
-            this.implementsTypes = Collections.unmodifiableList(implementsTypes);
+            this.implementsTypes = Collections
+                    .unmodifiableList(implementsTypes);
             this.constants = toUnmodifiableConstant(constantBuilders);
             this.enumerations = toUnmodifiableEnumerations(enumBuilders);
             this.properties = toUnmodifiableProperties(propBuilers);
@@ -498,17 +511,17 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
         public Type getParentType() {
             return null;
         }
-        
+
         @Override
         public String getComment() {
             return comment;
         }
-        
+
         @Override
         public List<AnnotationType> getAnnotations() {
             return annotations;
         }
-        
+
         @Override
         public List<Type> getImplements() {
             return implementsTypes;
@@ -518,7 +531,7 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
         public GeneratedTransferObject getExtends() {
             return extendsType;
         }
-        
+
         @Override
         public List<Enumeration> getEnumDefintions() {
             return enumerations;
@@ -622,4 +635,26 @@ public final class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
             return builder.toString();
         }
     }
+
+    private static final class GeneratedTransferIdentityObjectImpl extends
+            GeneratedTransferObjectImpl implements
+            GeneratedTransferIdentityObject {
+        public GeneratedTransferIdentityObjectImpl(final String packageName,
+                final String name, final String comment,
+                final List<AnnotationTypeBuilder> annotationBuilders,
+                final GeneratedTransferObject extendsType,
+                final List<Type> implementsTypes,
+                final List<ConstantBuilder> constantBuilders,
+                final List<EnumBuilder> enumBuilders,
+                final List<MethodSignatureBuilder> methodBuilders,
+                final List<GeneratedPropertyBuilder> propBuilers,
+                final List<GeneratedPropertyBuilder> equalsBuilers,
+                final List<GeneratedPropertyBuilder> hashCodeBuilers,
+                final List<GeneratedPropertyBuilder> stringBuilers) {
+            super(packageName, name, comment, annotationBuilders, extendsType,
+                    implementsTypes, constantBuilders, enumBuilders,
+                    methodBuilders, propBuilers, equalsBuilers,
+                    hashCodeBuilers, stringBuilers);
+        }
+    }
 }
index 942174fdcede1485b1c931133400d945f70787c6..aaeec40604a61c264afef7d23e5f7111b115a1ef 100644 (file)
@@ -17,23 +17,28 @@ import java.util.List;
 import java.util.Map;
 
 import org.opendaylight.controller.sal.binding.model.api.CodeGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferIdentityObject;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 
-public class ClassCodeGenerator implements CodeGenerator {
+public final class ClassCodeGenerator implements CodeGenerator {
 
     private Map<String, LinkedHashMap<String, Integer>> imports;
 
     @Override
     public Writer generate(Type type) throws IOException {
         final Writer writer = new StringWriter();
+        boolean isIdentity = type instanceof GeneratedTransferIdentityObject;
+
         if (type instanceof GeneratedTransferObject) {
-            GeneratedTransferObject genTO = (GeneratedTransferObject) type;
+            GeneratedTransferObject genTO = (GeneratedTransferObject) type;            
             imports = GeneratorUtil.createImports(genTO);
-
+            
             final String currentPkg = genTO.getPackageName();
             final List<GeneratedProperty> fields = genTO.getProperties();
+            final List<Enumeration> enums = genTO.getEnumDefintions();
 
             writer.write(GeneratorUtil.createPackageDeclaration(currentPkg));
             writer.write(NL);
@@ -45,9 +50,17 @@ public class ClassCodeGenerator implements CodeGenerator {
             writer.write(NL);
 
             writer.write(GeneratorUtil.createClassDeclaration(genTO, "",
-                    imports));
+                    imports, isIdentity));
             writer.write(NL);
             writer.write(NL);
+            
+            if (enums != null) {           
+                       EnumGenerator enumGenerator = new EnumGenerator();
+               for ( Enumeration e : enums ) {                         
+                       writer.write(enumGenerator.generateInnerEnumeration(e, TAB).toString());
+                       writer.write(NL);
+               }
+            }
 
             if (fields != null) {
                 for (GeneratedProperty field : fields) {
@@ -56,7 +69,7 @@ public class ClassCodeGenerator implements CodeGenerator {
                 }
                 writer.write(NL);
                 writer.write(GeneratorUtil.createConstructor(genTO, TAB,
-                        imports) + NL);
+                        imports, isIdentity) + NL);
                 writer.write(NL);
                 for (GeneratedProperty field : fields) {
                     writer.write(GeneratorUtil.createGetter(field, TAB,
index fbbd54e2023c56e3e009dcdd9c6e9ec277021395..e5cb97f1a6e4fb7181a875f5342a40f06a7d7e87 100644 (file)
@@ -7,8 +7,7 @@
  */
 package org.opendaylight.controller.sal.java.api.generator;
 
-public class Constants {
-
+final class Constants {
     public static final String IFC = "interface";
     public static final String CLASS = "class";
     public static final String PKG = "package";
@@ -24,12 +23,19 @@ public class Constants {
     public static final String COMMA = ",";
     public static final String NL = "\n";
     public static final String SC = ";";
-    public static final String TAB = "\t";
+    public static final String TAB = "    ";
 
     public static final String PUBLIC = "public";
     public static final String PRIVATE = "private";
+    public static final String PROTECTED = "protected";
     public static final String STATIC = "static";
+    public static final String ABSTRACT = "abstract";
     public static final String FINAL = "final";
     public static final String EXTENDS = "extends";
     public static final String IMPLEMENTS = "implements";
+    
+    public static final String ENUMERATION_NAME = "value";
+    public static final String ENUMERATION_TYPE = "int";       
+    
+    private Constants() {}
 }
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/EnumGenerator.java b/opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/EnumGenerator.java
new file mode 100644 (file)
index 0000000..33d2917
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * 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.sal.java.api.generator;
+
+import static org.opendaylight.controller.sal.java.api.generator.Constants.*;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.io.Writer;
+
+import org.opendaylight.controller.sal.binding.model.api.CodeGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+
+public class EnumGenerator implements CodeGenerator {
+
+       @Override
+       public Writer generate(Type type) throws IOException {
+               final Writer writer = new StringWriter();
+
+               if (type instanceof Enumeration) {
+                       Enumeration enums = (Enumeration) type;
+                       writer.write(GeneratorUtil.createPackageDeclaration(enums
+                                       .getPackageName()));
+                       writer.write(NL + NL);
+                       writer.write(GeneratorUtil.createEnum(enums, ""));
+               }
+
+               return writer;
+       }
+
+       public Writer generateInnerEnumeration(Type type, String indent) throws IOException {
+               final Writer writer = new StringWriter();
+
+               if (type instanceof Enumeration) {
+                       Enumeration enums = (Enumeration) type;
+                       writer.write(GeneratorUtil.createEnum(enums, indent));
+               }
+
+               return writer;
+       }
+
+}
index a0db8c7b6d500d7b7ea1b420c43a7456c2081a97..ab103b471e8fc076609308078aa1bba98b3f3a11 100644 (file)
@@ -18,35 +18,45 @@ import java.util.List;
 import java.util.Set;
 
 import org.opendaylight.controller.sal.binding.model.api.CodeGenerator;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class GeneratorJavaFile {
+public final class GeneratorJavaFile {
 
     private static final Logger log = LoggerFactory
             .getLogger(GeneratorJavaFile.class);
     private final CodeGenerator interfaceGenerator;
     private final ClassCodeGenerator classGenerator;
+    private final EnumGenerator enumGenerator;
+    
     private final Set<GeneratedType> genTypes;
     private final Set<GeneratedTransferObject> genTransferObjects;
+    private final Set<Enumeration> enumerations; 
 
     public GeneratorJavaFile(final CodeGenerator codeGenerator,
             final Set<GeneratedType> types) {
         this.interfaceGenerator = codeGenerator;
         this.genTypes = types;
         this.genTransferObjects = new HashSet<>();
-        classGenerator = new ClassCodeGenerator();
+        this.enumerations = new HashSet<>();
+        this.classGenerator = new ClassCodeGenerator();
+        this.enumGenerator = new EnumGenerator();
     }
 
     public GeneratorJavaFile(final Set<GeneratedType> types,
-            final Set<GeneratedTransferObject> genTransferObjects) {
+            final Set<GeneratedTransferObject> genTransferObjects,
+            final Set<Enumeration> enumerations) {
         this.interfaceGenerator = new InterfaceGenerator();
         this.classGenerator = new ClassCodeGenerator();
+        this.enumGenerator = new EnumGenerator();
+        
         this.genTypes = types;
         this.genTransferObjects = genTransferObjects;
+        this.enumerations = enumerations;
     }
 
     public List<File> generateToFile(final File parentDirectory) throws IOException {
@@ -67,6 +77,16 @@ public class GeneratorJavaFile {
                 result.add(genFile);
             }
         }
+        
+        for (Enumeration enumeration : enumerations) {
+            final File genFile = generateTypeToJavaFile(parentDirectory,
+                    enumeration, enumGenerator);
+
+            if (genFile != null) {
+                result.add(genFile);
+            }
+        }
+        
         return result;
     }
 
index b85e2b0ed7ed78f1a43c23a2bf207f8c56df5b0e..5b3b17dbf6c73334fe471dd3e797f8a18e228749 100644 (file)
@@ -26,8 +26,9 @@ import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
 import org.opendaylight.controller.sal.binding.model.api.MethodSignature.Parameter;
 import org.opendaylight.controller.sal.binding.model.api.ParameterizedType;
 import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.WildcardType;
 
-public class GeneratorUtil {
+public final class GeneratorUtil {
 
     private GeneratorUtil() {
     }
@@ -35,15 +36,17 @@ public class GeneratorUtil {
     public static String createIfcDeclaration(final GeneratedType genType,
             final String indent,
             final Map<String, LinkedHashMap<String, Integer>> availableImports) {
-        return createFileDeclaration(IFC, genType, indent, availableImports);
+        return createFileDeclaration(IFC, genType, indent, availableImports,
+                false);
     }
 
     public static String createClassDeclaration(
             final GeneratedTransferObject genTransferObject,
             final String indent,
-            final Map<String, LinkedHashMap<String, Integer>> availableImports) {
+            final Map<String, LinkedHashMap<String, Integer>> availableImports,
+            boolean isIdentity) {
         return createFileDeclaration(CLASS, genTransferObject, indent,
-                availableImports);
+                availableImports, isIdentity);
     }
 
     public static String createPackageDeclaration(final String packageName) {
@@ -52,7 +55,8 @@ public class GeneratorUtil {
 
     private static String createFileDeclaration(final String type,
             final GeneratedType genType, final String indent,
-            final Map<String, LinkedHashMap<String, Integer>> availableImports) {
+            final Map<String, LinkedHashMap<String, Integer>> availableImports,
+            boolean isIdentity) {
         final StringBuilder builder = new StringBuilder();
         final String currentPkg = genType.getPackageName();
 
@@ -63,14 +67,25 @@ public class GeneratorUtil {
             appendAnnotations(builder, annotations);
             builder.append(NL);
         }
-        builder.append(PUBLIC + GAP + type + GAP + genType.getName() + GAP);
+
+        if (isIdentity) {
+            if (!(CLASS.equals(type))) {
+                throw new IllegalArgumentException(
+                        "'identity' has to be generated as a class");
+            }
+            builder.append(PUBLIC + GAP + ABSTRACT + GAP + type + GAP
+                    + genType.getName() + GAP);
+        } else {
+            builder.append(PUBLIC + GAP + type + GAP + genType.getName() + GAP);
+        }
 
         if (genType instanceof GeneratedTransferObject) {
             GeneratedTransferObject genTO = (GeneratedTransferObject) genType;
 
             if (genTO.getExtends() != null) {
                 builder.append(EXTENDS + GAP);
-                builder.append(genTO.getExtends() + GAP);
+                String gtoString = getExplicitType(genTO.getExtends(), availableImports, currentPkg);
+                builder.append(gtoString + GAP);
             }
         }
 
@@ -168,7 +183,6 @@ public class GeneratorUtil {
             Map<String, LinkedHashMap<String, Integer>> availableImports,
             final String currentPkg) {
         final StringBuilder builder = new StringBuilder();
-        builder.append(indent);
         if (!property.getAnnotations().isEmpty()) {
             final List<AnnotationType> annotations = property.getAnnotations();
             appendAnnotations(builder, annotations);
@@ -183,7 +197,7 @@ public class GeneratorUtil {
 
     /**
      * Create method declaration in interface.
-     *
+     * 
      * @param method
      * @param indent
      * @return
@@ -244,7 +258,8 @@ public class GeneratorUtil {
 
     public static String createConstructor(
             GeneratedTransferObject genTransferObject, final String indent,
-            Map<String, LinkedHashMap<String, Integer>> availableImports) {
+            Map<String, LinkedHashMap<String, Integer>> availableImports,
+            boolean isIdentity) {
         final StringBuilder builder = new StringBuilder();
 
         final String currentPkg = genTransferObject.getPackageName();
@@ -258,7 +273,7 @@ public class GeneratorUtil {
         }
 
         builder.append(indent);
-        builder.append(PUBLIC);
+        builder.append(isIdentity ? PROTECTED : PUBLIC);
         builder.append(GAP);
         builder.append(genTransferObject.getName());
         builder.append(LB);
@@ -438,7 +453,7 @@ public class GeneratorUtil {
                 builder.append(NL);
                 builder.append(indent);
                 builder.append(TAB);
-                builder.append("builder.append(\", ");
+                builder.append("builder.append(");
                 builder.append(property.getName());
                 builder.append(");");
             }
@@ -461,20 +476,37 @@ public class GeneratorUtil {
 
     public static String createEnum(final Enumeration enumeration,
             final String indent) {
-        final StringBuilder builder = new StringBuilder(indent + ENUM + GAP
-                + enumeration.getName() + GAP + LCB + NL);
+        if (enumeration == null || indent == null)
+            throw new IllegalArgumentException();
+        final StringBuilder builder = new StringBuilder(indent + PUBLIC + GAP
+                + ENUM + GAP + enumeration.getName() + GAP + LCB + NL);
 
-        String separator = COMMA;
+        String separator = COMMA + NL;
         final List<Pair> values = enumeration.getValues();
-        builder.append(indent + TAB);
+
         for (int i = 0; i < values.size(); i++) {
             if (i + 1 == values.size()) {
                 separator = SC;
             }
-            builder.append(values.get(i).getName() + separator);
+            builder.append(indent + TAB + values.get(i).getName() + LB
+                    + values.get(i).getValue() + RB + separator);
         }
         builder.append(NL);
+        builder.append(NL);
+        final String ENUMERATION_NAME = "value";
+        final String ENUMERATION_TYPE = "int";
+        builder.append(indent + TAB + ENUMERATION_TYPE + GAP + ENUMERATION_NAME
+                + SC);
+        builder.append(NL);
+        builder.append(indent + TAB + PRIVATE + GAP + enumeration.getName()
+                + LB + ENUMERATION_TYPE + GAP + ENUMERATION_NAME + RB + GAP
+                + LCB + NL);
+        builder.append(indent + TAB + TAB + "this." + ENUMERATION_NAME + GAP
+                + "=" + GAP + ENUMERATION_NAME + SC + NL);
+        builder.append(indent + TAB + RCB + NL);
+
         builder.append(indent + RCB);
+        builder.append(NL);
         return builder.toString();
     }
 
@@ -511,7 +543,12 @@ public class GeneratorUtil {
             if (packageName.startsWith("java.lang")) {
                 builder.append(type.getName());
             } else {
-                builder.append(packageName + "." + type.getName());
+                if (!packageName.isEmpty()) {
+                    builder.append(packageName + "." + type.getName());
+                } else {
+                    builder.append(type.getName());
+                }
+
             }
             if (type instanceof ParameterizedType) {
                 ParameterizedType pType = (ParameterizedType) type;
@@ -539,7 +576,13 @@ public class GeneratorUtil {
             if (i + 1 == pTypes.length) {
                 separator = "";
             }
-            builder.append(getExplicitType(t, availableImports, currentPkg)
+            
+            String wildcardParam = "";
+            if(t instanceof WildcardType) {
+                wildcardParam = "? extends ";
+            }
+            
+            builder.append(wildcardParam + getExplicitType(t, availableImports, currentPkg)
                     + separator);
         }
         return builder.toString();
@@ -556,6 +599,7 @@ public class GeneratorUtil {
             if (currentValue > maxValue) {
                 result.clear();
                 result.add(entry.getKey());
+                maxValue = currentValue;
             } else if (currentValue == maxValue) {
                 result.add(entry.getKey());
             }
@@ -628,7 +672,8 @@ public class GeneratorUtil {
             String genTypePkg) {
         String typeName = type.getName();
         String typePkg = type.getPackageName();
-        if (typePkg.startsWith("java.lang") || typePkg.equals(genTypePkg)) {
+               if (typePkg.startsWith("java.lang") || typePkg.equals(genTypePkg) ||
+                typePkg.isEmpty()) {
             return;
         }
         LinkedHashMap<String, Integer> packages = importedTypes.get(typeName);
index abaf4fad21bb03caa81b2b1d82677bfbd7718618..38d3bcdc070dd4522a7c9d28ef28e2721bd10561 100644 (file)
@@ -24,63 +24,86 @@ import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
 import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 
-public class InterfaceGenerator implements CodeGenerator {
-
-    private Map<String, LinkedHashMap<String, Integer>> imports;
-
-    public Writer generate(Type type) throws IOException {
-        Writer writer = new StringWriter();
-        if (type instanceof GeneratedType
-                && !(type instanceof GeneratedTransferObject)) {
-            GeneratedType genType = (GeneratedType) type;
-            imports = GeneratorUtil.createImports(genType);
-
-            final String currentPkg = genType.getPackageName();
-            final List<Constant> constants = genType.getConstantDefinitions();
-            final List<MethodSignature> methods = genType
-                    .getMethodDefinitions();
-            final List<Enumeration> enums = genType.getEnumDefintions();
-
-            writer.write(GeneratorUtil.createPackageDeclaration(genType
-                    .getPackageName()));
-            writer.write(NL);
-
-            List<String> importLines = GeneratorUtil.createImportLines(imports);
-            for (String line : importLines) {
-                writer.write(line + NL);
-            }
-            writer.write(NL);
-
-            writer.write(GeneratorUtil.createIfcDeclaration(genType, "",
-                    imports));
-            writer.write(NL);
-
-            if (constants != null) {
-                for (Constant c : constants) {
-                    writer.write(GeneratorUtil.createConstant(c, TAB, imports,
-                            currentPkg) + NL);
-                }
-                writer.write(NL);
-            }
-
-            if (methods != null) {
-                for (MethodSignature m : methods) {
-                    writer.write(GeneratorUtil.createMethodDeclaration(m, TAB,
-                            imports, currentPkg) + NL);
-                }
-                writer.write(NL);
-            }
-
-            if (enums != null) {
-                for (Enumeration e : enums) {
-                    writer.write(GeneratorUtil.createEnum(e, TAB) + NL);
-                }
-                writer.write(NL);
-            }
-
-            writer.write(RCB);
-        }
-        return writer;
-    }
+public final class InterfaceGenerator implements CodeGenerator {
+
+       private Map<String, LinkedHashMap<String, Integer>> imports;
+
+       private String generateEnums(List<Enumeration> enums) {
+               String result = "";
+               if (enums != null) {
+                       EnumGenerator enumGenerator = new EnumGenerator();
+                       for (Enumeration en : enums) {
+                               try {
+                                       result = result
+                                                       + (enumGenerator.generateInnerEnumeration(en, TAB).toString() + NL);
+                               } catch (IOException e) {
+                                       e.printStackTrace();
+                               }
+                       }
+               }
+               return result;
+       }
+
+       private String generateConstants(List<Constant> constants, String pkgName) {
+               String result = "";
+               if (constants != null) {
+                       for (Constant c : constants) {
+                               result = result
+                                               + GeneratorUtil
+                                                               .createConstant(c, TAB, imports, pkgName) + NL;
+                       }
+                       result.concat(NL);
+               }
+               return result;
+       }
+
+       public String generateMethods(List<MethodSignature> methods, String pkgName) {
+               String result = "";
+
+               if (methods != null) {
+                       for (MethodSignature m : methods) {
+                               result = result
+                                               + GeneratorUtil.createMethodDeclaration(m, TAB,
+                                                               imports, pkgName) + NL;
+                       }
+                       result = result + NL;
+               }
+               return result;
+       }
+
+       public Writer generate(Type type) throws IOException {
+               Writer writer = new StringWriter();
+               if (type instanceof GeneratedType
+                               && !(type instanceof GeneratedTransferObject)) {
+                       GeneratedType genType = (GeneratedType) type;
+                       imports = GeneratorUtil.createImports(genType);
+
+                       final String currentPkg = genType.getPackageName();
+                       final List<Constant> constants = genType.getConstantDefinitions();
+                       final List<MethodSignature> methods = genType
+                                       .getMethodDefinitions();
+                       final List<Enumeration> enums = genType.getEnumDefintions();
+
+                       writer.write(GeneratorUtil.createPackageDeclaration(genType
+                                       .getPackageName()));
+                       writer.write(NL);
+
+                       List<String> importLines = GeneratorUtil.createImportLines(imports);
+                       for (String line : importLines) {
+                               writer.write(line + NL);
+                       }
+                       writer.write(NL);
+                       writer.write(GeneratorUtil.createIfcDeclaration(genType, "",
+                                       imports));
+                       writer.write(NL);
+
+                       writer.write(generateEnums(enums));
+                       writer.write(generateConstants(constants, currentPkg));
+                       writer.write(generateMethods(methods, currentPkg));
+
+                       writer.write(RCB);
+               }
+               return writer;
+       }
 
 }
index 3295becba6bbb27a78f1cbc5dd7ed7e8c3f4926e..5dd011be32afe6849716b6279d0facd12673101a 100644 (file)
@@ -49,7 +49,7 @@ public class ClassCodeGeneratorTest {
         final List<Type> genTypes = bindingGen.generateTypes(context);
 
         assertTrue(genTypes != null);
-        assertEquals(7, genTypes.size());
+        assertEquals(8, genTypes.size());
 
         int genTypesCount = 0;
         int genTOsCount = 0;
@@ -100,7 +100,7 @@ public class ClassCodeGeneratorTest {
             }
         }
 
-        assertEquals(5, genTypesCount);
+        assertEquals(6, genTypesCount);
         assertEquals(2, genTOsCount);
     }
 
@@ -134,4 +134,28 @@ public class ClassCodeGeneratorTest {
             e.printStackTrace();
         }
     }
+
+    @Test
+    public void toStringTest() {
+        final GeneratedTOBuilder toBuilder = new GeneratedTOBuilderImpl(
+                "simple.pack", "DefCtor");
+
+        GeneratedPropertyBuilder propBuilder = toBuilder.addProperty("foo");
+        propBuilder.addReturnType(Types.typeForClass(String.class));
+        propBuilder.setReadOnly(false);
+        toBuilder.addToStringProperty(propBuilder);
+
+        propBuilder = toBuilder.addProperty("bar");
+        propBuilder.addReturnType(Types.typeForClass(Integer.class));
+        propBuilder.setReadOnly(false);
+        toBuilder.addToStringProperty(propBuilder);
+        final GeneratedTransferObject genTO = toBuilder.toInstance();
+        final ClassCodeGenerator clsGen = new ClassCodeGenerator();
+        try {
+            final Writer writer = clsGen.generate(genTO);
+            assertNotNull(writer);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
 }
index bf539eb8fe43eb3149352501a10df2cec95cb385..db42d32fe6e7415f0ee90084c869fb06db9856c1 100644 (file)
@@ -29,6 +29,7 @@ import org.junit.Test;
 import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
 import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
 import org.opendaylight.controller.sal.binding.generator.impl.BindingGeneratorImpl;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
 import org.opendaylight.controller.sal.binding.model.api.Type;
@@ -117,6 +118,7 @@ public class GeneratorJavaFileTest {
         final List<Type> types = bindingGenerator.generateTypes(context);
         final Set<GeneratedType> typesToGenerate = new HashSet<GeneratedType>();
         final Set<GeneratedTransferObject> tosToGenerate = new HashSet<GeneratedTransferObject>();
+        final Set<Enumeration> enumerationToGenerate = new HashSet<Enumeration>();
         for (Type type : types) {
             if (type instanceof GeneratedType
                     && !(type instanceof GeneratedTransferObject)) {
@@ -126,10 +128,13 @@ public class GeneratorJavaFileTest {
             if (type instanceof GeneratedTransferObject) {
                 tosToGenerate.add((GeneratedTransferObject) type);
             }
+            if (type instanceof Enumeration) {
+               enumerationToGenerate.add((Enumeration) type);                  
+            }
         }
 
         final GeneratorJavaFile generator = new GeneratorJavaFile(
-                typesToGenerate, tosToGenerate);
+                typesToGenerate, tosToGenerate, enumerationToGenerate);
         generator.generateToFile(new File(GENERATOR_OUTPUT_PATH));
 
         JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
index 7ed1f9950383076e01dd7eda51e468ba2e7d1798..8bdf32706bef854692088ea601e2a3c2afe15e86 100644 (file)
@@ -138,4 +138,34 @@ module abstract-topology {
             }
         }
     }
-}
\ No newline at end of file
+    
+    identity crypto-base {
+        description "crypto-base description";
+    }
+    
+    identity crypto-alg {
+        base crypto-base;
+        description "crypto-alg description";
+    }
+    
+    grouping target {
+        container nodes {
+            leaf source {
+                type int8;
+            }
+            leaf target {
+                type int16;
+            }
+        }
+        leaf id {
+            type string;
+        }
+    }
+    
+    leaf idreftest {
+        type identityref {
+            base crypto-alg;
+        }
+    }
+    
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/GeneratedTransferIdentityObject.java b/opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/GeneratedTransferIdentityObject.java
new file mode 100644 (file)
index 0000000..80bed83
--- /dev/null
@@ -0,0 +1,6 @@
+package org.opendaylight.controller.sal.binding.model.api;
+
+public interface GeneratedTransferIdentityObject extends
+        GeneratedTransferObject {
+
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/WildcardType.java b/opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/WildcardType.java
new file mode 100644 (file)
index 0000000..ad08c2f
--- /dev/null
@@ -0,0 +1,5 @@
+package org.opendaylight.controller.sal.binding.model.api;
+
+public interface WildcardType extends Type  {
+
+}
index c01425407d0248e9b38039004cbddef179adb6cc..fc3495e184565f052f5b8a21a3f6577f1bac5e0f 100644 (file)
@@ -13,9 +13,9 @@ import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject
 
  */
 public interface GeneratedTOBuilder extends GeneratedTypeBuilder {
-    
+
     public boolean addExtendsType(final GeneratedTransferObject genTransObj);
-    
+
     public GeneratedPropertyBuilder addProperty(final String name);
 
     public boolean addEqualsIdentity(final GeneratedPropertyBuilder property);
@@ -26,4 +26,7 @@ public interface GeneratedTOBuilder extends GeneratedTypeBuilder {
 
     @Override
     public GeneratedTransferObject toInstance();
+
+    public GeneratedTransferObject toIdentityInstance();
+
 }
index 1876c689c0e5a10b44f554f51905e4f9b4a6ad0f..f6b80bc66640e9b5f4a9ea9ff76e98bae77a81f5 100644 (file)
@@ -16,9 +16,11 @@ import java.util.Map;
 import java.util.Set;
 
 import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.project.MavenProject;
 import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
 import org.opendaylight.controller.sal.binding.generator.impl.BindingGeneratorImpl;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
+import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 import org.opendaylight.controller.sal.java.api.generator.GeneratorJavaFile;
@@ -26,32 +28,32 @@ import org.opendaylight.controller.yang.model.api.Module;
 import org.opendaylight.controller.yang.model.api.SchemaContext;
 import org.opendaylight.controller.yang2sources.spi.CodeGenerator;
 
-public class CodeGeneratorImpl implements CodeGenerator {
+public final class CodeGeneratorImpl implements CodeGenerator {
 
-    @Override
-    public Collection<File> generateSources(SchemaContext context,
-            File outputBaseDir, Set<Module> yangModules, File projectBaseDir)
-            throws IOException {
+       @Override
+       public Collection<File> generateSources(SchemaContext context,
+            File outputBaseDir, Set<Module> yangModules) throws IOException {
 
-        final BindingGenerator bindingGenerator = new BindingGeneratorImpl();
-        final List<Type> types = bindingGenerator.generateTypes(context);
-        final Set<GeneratedType> typesToGenerate = new HashSet<GeneratedType>();
-        final Set<GeneratedTransferObject> tosToGenerate = new HashSet<GeneratedTransferObject>();
-        for (Type type : types) {
-            if (type instanceof GeneratedTransferObject) {
-                tosToGenerate.add((GeneratedTransferObject) type);
-            } else if (type instanceof GeneratedType) {
-                typesToGenerate.add((GeneratedType) type);
-            }
+               final BindingGenerator bindingGenerator = new BindingGeneratorImpl();
+               final List<Type> types = bindingGenerator.generateTypes(context);
+               final Set<GeneratedType> typesToGenerate = new HashSet<>();
+               final Set<GeneratedTransferObject> tosToGenerate = new HashSet<>();
+               final Set<Enumeration> enumsToGenerate = new HashSet<>();
 
+               for (Type type : types) {
+                       if (type instanceof GeneratedTransferObject) {
+                               tosToGenerate.add((GeneratedTransferObject) type);
+                       } else if (type instanceof GeneratedType) {
+                               typesToGenerate.add((GeneratedType) type);
+                       } else if (type instanceof Enumeration) {
+                               enumsToGenerate.add((Enumeration) type);
+                       }
         }
 
         final GeneratorJavaFile generator = new GeneratorJavaFile(
-                typesToGenerate, tosToGenerate);
+                               typesToGenerate, tosToGenerate, enumsToGenerate);
 
-        return generator.generateToFile(outputBaseDir.getPath().startsWith(
-                projectBaseDir.getPath()) ? outputBaseDir : new File(
-                projectBaseDir, outputBaseDir.getPath()));
+        return generator.generateToFile(outputBaseDir);
     }
 
     @Override
@@ -65,4 +67,14 @@ public class CodeGeneratorImpl implements CodeGenerator {
         // no additional config utilized
     }
 
+    @Override
+    public void setResourceBaseDir(File resourceBaseDir) {
+        // no resource processing necessary
+    }
+
+    @Override
+    public void setMavenProject(MavenProject project) {
+        // no additional information needed
+       }
+
 }
index 8d846a13e60f3efa658eb56a08590c264edc5ed3..2e406da497131c66f059c6ae67caba46aa851505 100644 (file)
@@ -4,7 +4,7 @@
     <parent>
         <artifactId>yang</artifactId>
         <groupId>org.opendaylight.controller</groupId>
-        <version>0.5.1-SNAPSHOT</version>
+        <version>0.5.2-SNAPSHOT</version>
         <relativePath>../../yang/pom.xml</relativePath>
     </parent>
     <artifactId>yang-maven-plugin-it</artifactId>
index 9535468ed52fefedaa58fb0aca0860337aa9d74e..9532d4efc9f92a4fbabe32e6ab11b79665e81e37 100644 (file)
@@ -11,6 +11,7 @@ import static org.junit.Assert.*;
 import static org.junit.matchers.JUnitMatchers.*;
 
 import java.io.File;
+import java.net.URL;
 
 import org.apache.maven.it.VerificationException;
 import org.apache.maven.it.Verifier;
@@ -45,8 +46,14 @@ public class YangToSourcesPluginTestIT {
     @Test
     public void testAdditionalConfiguration() throws VerificationException {
         Verifier v = setUp("AdditionalConfig/", false);
-        v.verifyTextInLog("[INFO] yang-to-sources: Additional configuration picked up for : org.opendaylight.controller.yang2sources.spi.CodeGeneratorTestImpl: {nm1=abcd=a.b.c.d, nm2=abcd2=a.b.c.d.2}");
-        v.verifyTextInLog("[INFO] yang-to-sources: Additional configuration picked up for : org.opendaylight.controller.yang2sources.spi.CodeGeneratorTestImpl: {c1=config}");
+        v.verifyTextInLog("[DEBUG] yang-to-sources: Additional configuration picked up for : org.opendaylight.controller.yang2sources.spi.CodeGeneratorTestImpl: {nm1=abcd=a.b.c.d, nm2=abcd2=a.b.c.d.2}");
+        v.verifyTextInLog("[DEBUG] yang-to-sources: Additional configuration picked up for : org.opendaylight.controller.yang2sources.spi.CodeGeneratorTestImpl: {c1=config}");
+        v.verifyTextInLog(File.separator
+                + "files marked as resources: META-INF" + File.separator
+                + "yang");
+        v.verifyTextInLog("target"
+                + File.separator
+                + "generated-resources marked as resources for generator: org.opendaylight.controller.yang2sources.spi.CodeGeneratorTestImpl");
     }
 
     @Test
@@ -102,10 +109,13 @@ public class YangToSourcesPluginTestIT {
 
     static Verifier setUp(String project, boolean ignoreF)
             throws VerificationException {
-        Verifier verifier = new Verifier(new File("src/test/resources/"
-                + project).getAbsolutePath());
+        final URL path = YangToSourcesPluginTestIT.class.getResource("/"
+                + project + "pom.xml");
+        File parent = new File(path.getPath());
+        Verifier verifier = new Verifier(parent.getParent());
         if (ignoreF)
             verifier.addCliOption("-fn");
+        verifier.setMavenDebug(true);
         verifier.executeGoal("generate-sources");
         return verifier;
     }
@@ -118,8 +128,8 @@ public class YangToSourcesPluginTestIT {
 
     @Test
     public void testFindResourceOnCp() throws VerificationException {
-        Verifier v1 = new Verifier(
-                new File("src/test/resources/GenerateTest1/").getAbsolutePath());
+        Verifier v1 = new Verifier(new File(getClass().getResource(
+                "/GenerateTest1/pom.xml").getPath()).getParent());
         v1.executeGoal("clean");
         v1.executeGoal("package");
         v1.assertFilePresent("target/classes/META-INF/yang/testfile1.yang");
@@ -134,5 +144,4 @@ public class YangToSourcesPluginTestIT {
         v2.assertFileNotPresent("target/classes/META-INF/yang/testfile2.yang");
         v2.assertFileNotPresent("target/classes/META-INF/yang/testfile3.yang");
     }
-
 }
index b7baa743388986fcac742805d54f0ff256b09f3c..3ac7ec6eee95f4f2a766a12f461c97a12a283f47 100644 (file)
@@ -10,7 +10,7 @@
         <dependency>
             <groupId>org.opendaylight.controller</groupId>
             <artifactId>yang-maven-plugin-spi</artifactId>
-            <version>0.5.1-SNAPSHOT</version>
+            <version>0.5.2-SNAPSHOT</version>
         </dependency>
     </dependencies>
 
@@ -19,7 +19,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
@@ -37,6 +37,7 @@
                                         <nm1>abcd=a.b.c.d</nm1>
                                         <nm2>abcd2=a.b.c.d.2</nm2>
                                     </additionalConfiguration>
+                                    <resourceBaseDir>/target/resourcesGenerated</resourceBaseDir>
                                 </generator>
                                 <generator>
                                     <codeGeneratorClass>
@@ -55,7 +56,7 @@
                     <dependency>
                         <groupId>org.opendaylight.controller</groupId>
                         <artifactId>yang-maven-plugin-spi</artifactId>
-                        <version>0.5.1-SNAPSHOT</version>
+                        <version>0.5.2-SNAPSHOT</version>
                         <type>test-jar</type>
                     </dependency>
                 </dependencies>
index ce9389f64b9d197079aaa9f9aaf6f04d3c981c18..a397cf75123e1a974c9abbd45142397c689275cc 100644 (file)
@@ -10,7 +10,7 @@
         <dependency>
             <groupId>org.opendaylight.controller</groupId>
             <artifactId>yang-maven-plugin-spi</artifactId>
-            <version>0.5.1-SNAPSHOT</version>
+            <version>0.5.2-SNAPSHOT</version>
         </dependency>
     </dependencies>
 
@@ -19,7 +19,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
@@ -43,7 +43,7 @@
                     <dependency>
                         <groupId>org.opendaylight.controller</groupId>
                         <artifactId>yang-maven-plugin-spi</artifactId>
-                        <version>0.5.1-SNAPSHOT</version>
+                        <version>0.5.2-SNAPSHOT</version>
                         <type>test-jar</type>
                     </dependency>
                 </dependencies>
index e1591b573399bf538b0849256f95ede52d5a236c..07b69878a9e7aa6cd70803d4808278c81a2dc1e9 100644 (file)
@@ -11,7 +11,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
@@ -35,7 +35,7 @@
                     <dependency>
                         <groupId>org.opendaylight.controller</groupId>
                         <artifactId>yang-maven-plugin-spi</artifactId>
-                        <version>0.5.1-SNAPSHOT</version>
+                        <version>0.5.2-SNAPSHOT</version>
                         <type>test-jar</type>
                     </dependency>
                 </dependencies>
index b608637e6be8bb13f2c32331226b732e4981a187..e094aed92a8bac3e66021989c8c289cf5539fb99 100644 (file)
@@ -11,7 +11,7 @@
         <dependency>
             <groupId>org.opendaylight.controller</groupId>
             <artifactId>generator-test1</artifactId>
-            <version>0.5.1-SNAPSHOT</version>
+            <version>0.5.2-SNAPSHOT</version>
             <scope>system</scope>
             <systemPath>${project.basedir}/../GenerateTest1/target/generator-test1-0.5.1-SNAPSHOT.jar</systemPath>
         </dependency>
@@ -22,7 +22,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
                                     </outputBaseDir>
                                 </generator>
                             </codeGenerators>
-                            <resourceProviders>
-                                <provider>
-                                    <resourceProviderClass>
-                                        org.opendaylight.controller.yang2sources.spi.ResourceProviderTestImpl
-                                    </resourceProviderClass>
-                                    <outputBaseDir>
-                                        outDir/
-                                    </outputBaseDir>
-                                </provider>
-                            </resourceProviders>
                         </configuration>
                     </execution>
                 </executions>
@@ -59,7 +49,7 @@
                     <dependency>
                         <groupId>org.opendaylight.controller</groupId>
                         <artifactId>yang-maven-plugin-spi</artifactId>
-                        <version>0.5.1-SNAPSHOT</version>
+                        <version>0.5.2-SNAPSHOT</version>
                         <type>test-jar</type>
                     </dependency>
                 </dependencies>
index c64a857c1e408e26a4b627e6cbde080897920d04..dd98fea4cd3589a9e240dbceb92198a685fe5edc 100644 (file)
@@ -13,7 +13,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
@@ -40,7 +40,7 @@
                     <dependency>
                         <groupId>org.opendaylight.controller</groupId>
                         <artifactId>yang-maven-plugin-spi</artifactId>
-                        <version>0.5.1-SNAPSHOT</version>
+                        <version>0.5.2-SNAPSHOT</version>
                         <type>test-jar</type>
                     </dependency>
                 </dependencies>
index 1b73c76bb7ede04f97cb2336b8af1937257acf9a..aa0db753d7c58595c127e5db9cb2cbea045af7d3 100644 (file)
@@ -12,7 +12,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
@@ -49,7 +49,7 @@
                     <dependency>
                         <groupId>org.opendaylight.controller</groupId>
                         <artifactId>yang-maven-plugin-spi</artifactId>
-                        <version>0.5.1-SNAPSHOT</version>
+                        <version>0.5.2-SNAPSHOT</version>
                         <type>test-jar</type>
                     </dependency>
                 </dependencies>
index 9a43e893b5fb049e4eb25192d5732581418cadc6..8333b02ffc6d970508910dfa7cc8bef955bc5129 100644 (file)
@@ -11,7 +11,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
@@ -39,7 +39,7 @@
                     <dependency>
                         <groupId>org.opendaylight.controller</groupId>
                         <artifactId>yang-maven-plugin-spi</artifactId>
-                        <version>0.5.1-SNAPSHOT</version>
+                        <version>0.5.2-SNAPSHOT</version>
                         <type>test-jar</type>
                     </dependency>
                 </dependencies>
index 54bace053c57808918bb5ed9e9c29612ca9b0829..eea103cf4eb4e675a9053eac0735fdec5298dc22 100644 (file)
@@ -12,7 +12,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
@@ -36,7 +36,7 @@
                     <dependency>
                         <groupId>org.opendaylight.controller</groupId>
                         <artifactId>yang-maven-plugin-spi</artifactId>
-                        <version>0.5.1-SNAPSHOT</version>
+                        <version>0.5.2-SNAPSHOT</version>
                         <type>test-jar</type>
                     </dependency>
                 </dependencies>
index b2eeb6f66ad73e5eac7454aa37c201fd9044eca3..54056d5ca47459c96ee72b2fa0a5e482009c8600 100644 (file)
@@ -12,7 +12,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
@@ -39,7 +39,7 @@
                     <dependency>
                         <groupId>org.opendaylight.controller</groupId>
                         <artifactId>yang-maven-plugin-spi</artifactId>
-                        <version>0.5.1-SNAPSHOT</version>
+                        <version>0.5.2-SNAPSHOT</version>
                         <type>test-jar</type>
                     </dependency>
                 </dependencies>
index 96a75b969caa606bd4e41c5a8c85c22fc3d327ee..65ea6aa68e947e4c749aaf369d2af5ac20e895b1 100644 (file)
@@ -12,7 +12,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
@@ -47,7 +47,7 @@
                     <dependency>
                         <groupId>org.opendaylight.controller</groupId>
                         <artifactId>yang-maven-plugin-spi</artifactId>
-                        <version>0.5.1-SNAPSHOT</version>
+                        <version>0.5.2-SNAPSHOT</version>
                         <type>test-jar</type>
                     </dependency>
                 </dependencies>
index 09df6ab23ddc4834a15d26208a5d4ba24857319d..08c0e7b3ca67e055007f13ce75915a7f6692f401 100644 (file)
@@ -12,7 +12,7 @@
             <plugin>
                 <groupId>org.opendaylight.controller</groupId>
                 <artifactId>yang-maven-plugin</artifactId>
-                <version>0.5.1-SNAPSHOT</version>
+                <version>0.5.2-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
index 5afd588541382de8584324e028cd9f1a6d222ebb..297b8b49dee4014a7b96fd76ab8f38a3d4cca278 100644 (file)
@@ -4,7 +4,7 @@
     <parent>
         <artifactId>yang</artifactId>
         <groupId>org.opendaylight.controller</groupId>
-        <version>0.5.1-SNAPSHOT</version>
+        <version>0.5.2-SNAPSHOT</version>
         <relativePath>../../yang/pom.xml</relativePath>
     </parent>
 
index aaf7080a6234c8e6a4155b42ec8dc20d3c7cc58f..0df9a6345ee9384b316f3d71093fa19a9796a658 100644 (file)
@@ -42,7 +42,10 @@ public abstract class ConfigArg {
     public static final class CodeGeneratorArg extends ConfigArg {
         private static final String CODE_GEN_DEFAULT_DIR = "target"
                 + File.separator + "generated-sources";
+        private static final String CODE_GEN_DEFAULT_RESOURCE_DIR = "target"
+                + File.separator + "generated-resources";
         private String codeGeneratorClass;
+        private File resourceBaseDir = new File(CODE_GEN_DEFAULT_RESOURCE_DIR);
 
         private Map<String, String> additionalConfiguration = Maps.newHashMap();
 
@@ -59,6 +62,13 @@ public abstract class ConfigArg {
             this.codeGeneratorClass = codeGeneratorClass;
         }
 
+        public CodeGeneratorArg(String codeGeneratorClass,
+                String outputBaseDir, String resourceBaseDir) {
+            super(outputBaseDir);
+            this.codeGeneratorClass = codeGeneratorClass;
+            this.resourceBaseDir = new File(resourceBaseDir);
+        }
+
         @Override
         public void check() {
             Preconditions.checkNotNull(codeGeneratorClass,
@@ -69,6 +79,14 @@ public abstract class ConfigArg {
             return codeGeneratorClass;
         }
 
+        public File getResourceBaseDir(MavenProject project) {
+            if (resourceBaseDir.isAbsolute()) {
+                return resourceBaseDir;
+            } else {
+                return new File(project.getBasedir(), resourceBaseDir.getPath());
+            }
+        }
+
         public Map<String, String> getAdditionalConfiguration() {
             return additionalConfiguration;
         }
index 653c0bff6d5b6c1fca52c9ff891df60be1385ba2..e3b0b31215bef2a6deac7457d152d19ec81d1115 100644 (file)
@@ -7,21 +7,31 @@
  */
 package org.opendaylight.controller.yang2sources.plugin;
 
+import java.io.Closeable;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
+import java.io.FilenameFilter;
+import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Enumeration;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
 
 import org.apache.commons.io.FileUtils;
 import org.apache.maven.artifact.Artifact;
+import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.plugin.logging.Log;
 import org.apache.maven.project.MavenProject;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
 
-import com.google.common.base.Function;
-import com.google.common.collect.Collections2;
+import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 
@@ -81,23 +91,6 @@ final class Util {
         }
     }
 
-    static String[] listFilesAsArrayOfPaths(File rootDir)
-            throws FileNotFoundException {
-        String[] filesArray = new String[] {};
-        Collection<File> yangFiles = listFiles(rootDir);
-
-        // If collection is empty, return empty array [] rather then [null]
-        // array, that is created by default
-        return yangFiles.isEmpty() ? filesArray : Collections2.transform(
-                yangFiles, new Function<File, String>() {
-
-                    @Override
-                    public String apply(File input) {
-                        return input.getPath();
-                    }
-                }).toArray(filesArray);
-    }
-
     private static void toCache(final File rootDir,
             final Collection<File> yangFiles) {
         cache.put(rootDir, yangFiles);
@@ -137,7 +130,7 @@ final class Util {
         return String.format("%s %s", logPrefix, innerMessage);
     }
 
-    public static List<File> getClassPath(MavenProject project) {
+    static List<File> getClassPath(MavenProject project) {
         List<File> dependencies = Lists.newArrayList();
         for (Artifact element : project.getArtifacts()) {
             File asFile = element.getFile();
@@ -155,13 +148,117 @@ final class Util {
                 : false;
     }
 
-    public static boolean acceptedFilter(String name, List<String> filter) {
-        for (String f : filter) {
-            if (name.endsWith(f)) {
-                return true;
+    static <T> T checkNotNull(T obj, String paramName) {
+        return Preconditions.checkNotNull(obj, "Parameter " + paramName
+                + " is null");
+    }
+
+    final static class YangsInZipsResult implements Closeable {
+        final List<InputStream> yangStreams;
+        private final List<Closeable> zipInputStreams;
+
+        private YangsInZipsResult(List<InputStream> yangStreams,
+                List<Closeable> zipInputStreams) {
+            this.yangStreams = yangStreams;
+            this.zipInputStreams = zipInputStreams;
+        }
+
+        @Override
+        public void close() throws IOException {
+            for (InputStream is : yangStreams) {
+                is.close();
+            }
+            for (Closeable is : zipInputStreams) {
+                is.close();
             }
         }
-        return false;
+    }
+
+    static YangsInZipsResult findYangFilesInDependenciesAsStream(Log log,
+            MavenProject project)
+            throws MojoFailureException {
+        List<InputStream> yangsFromDependencies = new ArrayList<>();
+        List<Closeable> zips = new ArrayList<>();
+        try {
+            List<File> filesOnCp = Util.getClassPath(project);
+            log.info(Util.message(
+                    "Searching for yang files in following dependencies: %s",
+                    YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
+
+            for (File file : filesOnCp) {
+                List<String> foundFilesForReporting = new ArrayList<>();
+                // is it jar file or directory?
+                if (file.isDirectory()) {
+                    File yangDir = new File(file,
+                            YangToSourcesProcessor.META_INF_YANG_STRING);
+                    if (yangDir.exists() && yangDir.isDirectory()) {
+                        File[] yangFiles = yangDir
+                                .listFiles(new FilenameFilter() {
+                                    @Override
+                                    public boolean accept(File dir, String name) {
+                                        return name.endsWith(".yang")
+                                                && new File(dir, name).isFile();
+                                    }
+                                });
+                        for (File yangFile : yangFiles) {
+                            yangsFromDependencies.add(new NamedFileInputStream(
+                                    yangFile));
+                        }
+                    }
+
+                } else {
+                    ZipFile zip = new ZipFile(file);
+                    zips.add(zip);
+
+                    Enumeration<? extends ZipEntry> entries = zip.entries();
+                    while (entries.hasMoreElements()) {
+                        ZipEntry entry = entries.nextElement();
+                        String entryName = entry.getName();
+
+                        if (entryName
+                                .startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)) {
+                            if (entry.isDirectory() == false
+                                    && entryName.endsWith(".yang")) {
+                                foundFilesForReporting.add(entryName);
+                                // This will be closed after all strams are
+                                // parsed.
+                                InputStream entryStream = zip
+                                        .getInputStream(entry);
+                                yangsFromDependencies.add(entryStream);
+                            }
+                        }
+                    }
+                }
+                if (foundFilesForReporting.size() > 0) {
+                    log.info(Util.message("Found %d yang files in %s: %s",
+                            YangToSourcesProcessor.LOG_PREFIX,
+                            foundFilesForReporting.size(), file,
+                            foundFilesForReporting));
+                }
+
+            }
+        } catch (Exception e) {
+            throw new MojoFailureException(e.getMessage(), e);
+        }
+        return new YangsInZipsResult(yangsFromDependencies, zips);
+    }
+
+    final static class ContextHolder {
+        private final SchemaContext context;
+        private final Set<Module> yangModules;
+
+        ContextHolder(SchemaContext context, Set<Module> yangModules) {
+            this.context = context;
+            this.yangModules = yangModules;
+        }
+
+        SchemaContext getContext() {
+            return context;
+        }
+
+        Set<Module> getYangModules() {
+            return yangModules;
+        }
     }
 
 }
index 7dbd8568240b802d0c105a309eaca270ab5d1eae..6e43b306cd44d82b1cdcaa32b5b54c976fc41a71 100644 (file)
@@ -64,41 +64,58 @@ public final class YangToSourcesMojo extends AbstractMojo {
     @Parameter(property = "inspectDependencies", required = true, readonly = true)
     private boolean inspectDependencies;
 
+    private YangToSourcesProcessor yangToSourcesProcessor;
+
     public YangToSourcesMojo() {
 
     }
 
     @VisibleForTesting
-    YangToSourcesMojo(CodeGeneratorArg[] codeGeneratorArgs,
-            String yangFilesRootDir) {
-        this.codeGenerators = codeGeneratorArgs;
-        this.yangFilesRootDir = yangFilesRootDir;
+    YangToSourcesMojo(YangToSourcesProcessor processor) {
+        this.yangToSourcesProcessor = processor;
     }
 
     @Override
     public void execute() throws MojoExecutionException, MojoFailureException {
+        if (yangToSourcesProcessor == null) {
+            List<CodeGeneratorArg> codeGeneratorArgs = processCodeGenerators(codeGenerators);
+
+            // defaults to ${basedir}/src/main/yang
+            File yangFilesRootFile = processYangFilesRootDir(yangFilesRootDir,
+                    project.getBasedir());
+
+            yangToSourcesProcessor = new YangToSourcesProcessor(getLog(),
+                    yangFilesRootFile, codeGeneratorArgs, project,
+                    inspectDependencies);
+        }
+        yangToSourcesProcessor.execute();
+    }
+
+    private static List<CodeGeneratorArg> processCodeGenerators(
+            CodeGeneratorArg[] codeGenerators) {
         List<CodeGeneratorArg> codeGeneratorArgs;
         if (codeGenerators == null) {
             codeGeneratorArgs = Collections.emptyList();
         } else {
             codeGeneratorArgs = Arrays.asList(codeGenerators);
         }
+        return codeGeneratorArgs;
+    }
 
-        // defaults to ${basedir}/src/main/yang
+    private static File processYangFilesRootDir(String yangFilesRootDir,
+            File baseDir) {
         File yangFilesRootFile;
         if (yangFilesRootDir == null) {
-            yangFilesRootFile = new File(project.getBasedir(), "src"
-                    + File.separator + "main" + File.separator + "yang");
+            yangFilesRootFile = new File(baseDir, "src" + File.separator
+                    + "main" + File.separator + "yang");
         } else {
             File file = new File(yangFilesRootDir);
             if (file.isAbsolute()) {
                 yangFilesRootFile = file;
             } else {
-                yangFilesRootFile = new File(project.getBasedir(),
-                        file.getPath());
+                yangFilesRootFile = new File(baseDir, file.getPath());
             }
         }
-        new YangToSourcesProcessor(getLog(), yangFilesRootFile,
-                codeGeneratorArgs, project, inspectDependencies).execute();
+        return yangFilesRootFile;
     }
 }
index be92af0126cb07aed0027a831287767091ad1c25..a7b7f429ccbffbd9bf4f4593094989446914105f 100644 (file)
@@ -9,19 +9,15 @@ package org.opendaylight.controller.yang2sources.plugin;
 
 import java.io.Closeable;
 import java.io.File;
-import java.io.FilenameFilter;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.Enumeration;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
 
 import org.apache.maven.model.Resource;
 import org.apache.maven.plugin.MojoExecutionException;
@@ -33,46 +29,52 @@ import org.opendaylight.controller.yang.model.api.Module;
 import org.opendaylight.controller.yang.model.api.SchemaContext;
 import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
 import org.opendaylight.controller.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
-import org.opendaylight.controller.yang2sources.plugin.Util.NamedFileInputStream;
+import org.opendaylight.controller.yang2sources.plugin.Util.ContextHolder;
+import org.opendaylight.controller.yang2sources.plugin.Util.YangsInZipsResult;
 import org.opendaylight.controller.yang2sources.spi.CodeGenerator;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.Maps;
 
 class YangToSourcesProcessor {
-    private static final String LOG_PREFIX = "yang-to-sources:";
-    private static final String META_INF_YANG_STRING = "META-INF"
-            + File.separator + "yang";
-    private static final File META_INF_YANG_DIR = new File(META_INF_YANG_STRING);
+    static final String LOG_PREFIX = "yang-to-sources:";
+    static final String META_INF_YANG_STRING = "META-INF" + File.separator
+            + "yang";
+    static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
+    static final File META_INF_YANG_DIR = new File(META_INF_YANG_STRING);
 
     private final Log log;
     private final File yangFilesRootDir;
     private final List<CodeGeneratorArg> codeGenerators;
     private final MavenProject project;
     private final boolean inspectDependencies;
+    private YangProvider yangProvider;
 
+    @VisibleForTesting
     YangToSourcesProcessor(Log log, File yangFilesRootDir,
-            List<CodeGeneratorArg> codeGenerators, MavenProject project,
-            boolean inspectDependencies) {
-        this.log = checkNotNull(log, "log");
-        this.yangFilesRootDir = checkNotNull(yangFilesRootDir,
+                           List<CodeGeneratorArg> codeGenerators, MavenProject project,
+                           boolean inspectDependencies, YangProvider yangProvider) {
+        this.log = Util.checkNotNull(log, "log");
+        this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir,
                 "yangFilesRootDir");
-        this.codeGenerators = Collections.unmodifiableList(checkNotNull(
+        this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(
                 codeGenerators, "codeGenerators"));
-        this.project = checkNotNull(project, "project");
+        this.project = Util.checkNotNull(project, "project");
         this.inspectDependencies = inspectDependencies;
+        this.yangProvider = yangProvider;
     }
 
-    private static <T> T checkNotNull(T obj, String paramName) {
-        if (obj == null)
-            throw new NullPointerException("Parameter '" + paramName
-                    + "' is null");
-        return obj;
+    YangToSourcesProcessor(Log log, File yangFilesRootDir,
+                           List<CodeGeneratorArg> codeGenerators, MavenProject project,
+                           boolean inspectDependencies) {
+        this(log, yangFilesRootDir, codeGenerators, project,
+                inspectDependencies, new YangProvider());
     }
 
     public void execute() throws MojoExecutionException, MojoFailureException {
         ContextHolder context = processYang();
         generateSources(context);
-        addYangsToMETA_INF();
+        yangProvider.addYangsToMETA_INF(log, project, yangFilesRootDir);
     }
 
     private ContextHolder processYang() throws MojoExecutionException {
@@ -88,7 +90,8 @@ class YangToSourcesProcessor {
             Set<Module> projectYangModules;
             try {
                 if (inspectDependencies) {
-                    YangsInZipsResult dependentYangResult = findYangFilesInDependenciesAsStream();
+                    YangsInZipsResult dependentYangResult = Util
+                            .findYangFilesInDependenciesAsStream(log, project);
                     Closeable dependentYangResult1 = dependentYangResult;
                     closeables.add(dependentYangResult1);
                     all.addAll(dependentYangResult.yangStreams);
@@ -124,20 +127,38 @@ class YangToSourcesProcessor {
         }
     }
 
-    private void addYangsToMETA_INF() throws MojoFailureException {
-        Resource res = new Resource();
+    static class YangProvider {
 
-        File targetYangDir = new File(project.getBasedir(), "target"
-                + File.separator + "yang");
-        res.setDirectory(targetYangDir.getPath());
+        private static final String yangResourceDir = "target" + File.separator
+                + "yang";
 
-        res.setTargetPath(META_INF_YANG_DIR.getPath());
-        try {
-            FileUtils.copyDirectory(yangFilesRootDir, targetYangDir);
-        } catch (IOException e) {
-            throw new MojoFailureException(e.getMessage(), e);
+        void addYangsToMETA_INF(Log log, MavenProject project,
+                                File yangFilesRootDir) throws MojoFailureException {
+            File targetYangDir = new File(project.getBasedir(), yangResourceDir);
+
+            try {
+                FileUtils.copyDirectory(yangFilesRootDir, targetYangDir);
+            } catch (IOException e) {
+                String message = "Unable to copy yang files into resource folder";
+                log.warn(message, e);
+                throw new MojoFailureException(message, e);
+            }
+
+            setResource(targetYangDir, META_INF_YANG_DIR.getPath(), project);
+
+            log.debug(Util.message(
+                    "Yang files from: %s marked as resources: %s", LOG_PREFIX,
+                    yangFilesRootDir, META_INF_YANG_DIR.getPath()));
+        }
+
+        private static void setResource(File targetYangDir, String targetPath,
+                                        MavenProject project) {
+            Resource res = new Resource();
+            res.setDirectory(targetYangDir.getPath());
+            if (targetPath != null)
+                res.setTargetPath(targetPath);
+            project.addResource(res);
         }
-        project.addResource(res);
     }
 
     /**
@@ -178,7 +199,7 @@ class YangToSourcesProcessor {
      * Instantiate generator from class and call required method
      */
     private void generateSourcesWithOneGenerator(ContextHolder context,
-            CodeGeneratorArg codeGeneratorCfg) throws ClassNotFoundException,
+                                                 CodeGeneratorArg codeGeneratorCfg) throws ClassNotFoundException,
             InstantiationException, IllegalAccessException, IOException {
 
         codeGeneratorCfg.check();
@@ -192,122 +213,30 @@ class YangToSourcesProcessor {
 
         log.info(Util.message("Sources will be generated to %s", LOG_PREFIX,
                 outputDir));
-        log.info(Util.message("Project root dir is %s", LOG_PREFIX,
+        log.debug(Util.message("Project root dir is %s", LOG_PREFIX,
                 project.getBasedir()));
-        log.info(Util.message(
+        log.debug(Util.message(
                 "Additional configuration picked up for : %s: %s", LOG_PREFIX,
                 codeGeneratorCfg.getCodeGeneratorClass(),
                 codeGeneratorCfg.getAdditionalConfiguration()));
+
         project.addCompileSourceRoot(outputDir.getAbsolutePath());
         g.setLog(log);
+        g.setMavenProject(project);
         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
-        Collection<File> generated = g.generateSources(context.getContext(),
-                outputDir, context.getYangModules(), project.getBasedir());
-        log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX,
-                codeGeneratorCfg.getCodeGeneratorClass(), generated));
-    }
-
-    private class YangsInZipsResult implements Closeable {
-        private final List<InputStream> yangStreams;
-        private final List<Closeable> zipInputStreams;
+        File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
 
-        private YangsInZipsResult(List<InputStream> yangStreams,
-                List<Closeable> zipInputStreams) {
-            this.yangStreams = yangStreams;
-            this.zipInputStreams = zipInputStreams;
-        }
-
-        @Override
-        public void close() throws IOException {
-            for (InputStream is : yangStreams) {
-                is.close();
-            }
-            for (Closeable is : zipInputStreams) {
-                is.close();
-            }
-        }
-    }
+        YangProvider.setResource(resourceBaseDir, null, project);
+        g.setResourceBaseDir(resourceBaseDir);
+        log.debug(Util.message(
+                "Folder: %s marked as resources for generator: %s", LOG_PREFIX,
+                resourceBaseDir, codeGeneratorCfg.getCodeGeneratorClass()));
 
-    private YangsInZipsResult findYangFilesInDependenciesAsStream()
-            throws MojoFailureException {
-        List<InputStream> yangsFromDependencies = new ArrayList<>();
-        List<Closeable> zips = new ArrayList<>();
-        try {
-            List<File> filesOnCp = Util.getClassPath(project);
-            log.info(Util.message(
-                    "Searching for yang files in following dependencies: %s",
-                    LOG_PREFIX, filesOnCp));
-
-            for (File file : filesOnCp) {
-                List<String> foundFilesForReporting = new ArrayList<>();
-                // is it jar file or directory?
-                if (file.isDirectory()) {
-                    File yangDir = new File(file, META_INF_YANG_STRING);
-                    if (yangDir.exists() && yangDir.isDirectory()) {
-                        File[] yangFiles = yangDir
-                                .listFiles(new FilenameFilter() {
-                                    @Override
-                                    public boolean accept(File dir, String name) {
-                                        return name.endsWith(".yang")
-                                                && new File(dir, name).isFile();
-                                    }
-                                });
-                        for (File yangFile : yangFiles) {
-                            yangsFromDependencies.add(new NamedFileInputStream(
-                                    yangFile));
-                        }
-                    }
-
-                } else {
-                    ZipFile zip = new ZipFile(file);
-                    zips.add(zip);
-
-                    Enumeration<? extends ZipEntry> entries = zip.entries();
-                    while (entries.hasMoreElements()) {
-                        ZipEntry entry = entries.nextElement();
-                        String entryName = entry.getName();
-
-                        if (entryName.startsWith(META_INF_YANG_STRING)) {
-                            if (entry.isDirectory() == false
-                                    && entryName.endsWith(".yang")) {
-                                foundFilesForReporting.add(entryName);
-                                // This will be closed after all strams are
-                                // parsed.
-                                InputStream entryStream = zip
-                                        .getInputStream(entry);
-                                yangsFromDependencies.add(entryStream);
-                            }
-                        }
-                    }
-                }
-                if (foundFilesForReporting.size() > 0) {
-                    log.info(Util.message("Found %d yang files in %s: %s",
-                            LOG_PREFIX, foundFilesForReporting.size(), file,
-                            foundFilesForReporting));
-                }
+        Collection<File> generated = g.generateSources(context.getContext(),
+                outputDir, context.getYangModules());
 
-            }
-        } catch (Exception e) {
-            throw new MojoFailureException(e.getMessage(), e);
-        }
-        return new YangsInZipsResult(yangsFromDependencies, zips);
+        log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX,
+                codeGeneratorCfg.getCodeGeneratorClass(), generated));
     }
 
-    private class ContextHolder {
-        private final SchemaContext context;
-        private final Set<Module> yangModules;
-
-        private ContextHolder(SchemaContext context, Set<Module> yangModules) {
-            this.context = context;
-            this.yangModules = yangModules;
-        }
-
-        public SchemaContext getContext() {
-            return context;
-        }
-
-        public Set<Module> getYangModules() {
-            return yangModules;
-        }
-    }
 }
index 1bfe9d4d0c01e0522fb48799d38c2a947cdc1a07..14e9d34b2aeec672c4f3ff15b26ec2a57b8bd5d0 100644 (file)
@@ -7,9 +7,11 @@
  */
 package org.opendaylight.controller.yang2sources.plugin;
 
-import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.Is.*;
 import static org.junit.Assert.*;
-import static org.mockito.Mockito.doReturn;
+import static org.junit.matchers.JUnitMatchers.*;
+import static org.mockito.Matchers.*;
+import static org.mockito.Mockito.*;
 
 import java.io.File;
 import java.io.IOException;
@@ -17,16 +19,17 @@ import java.util.Collection;
 import java.util.Map;
 import java.util.Set;
 
+import org.apache.maven.plugin.MojoFailureException;
 import org.apache.maven.plugin.logging.Log;
 import org.apache.maven.project.MavenProject;
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.opendaylight.controller.yang.model.api.Module;
 import org.opendaylight.controller.yang.model.api.SchemaContext;
 import org.opendaylight.controller.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
+import org.opendaylight.controller.yang2sources.plugin.YangToSourcesProcessor.YangProvider;
 import org.opendaylight.controller.yang2sources.spi.CodeGenerator;
 
 import com.google.common.collect.Lists;
@@ -40,27 +43,37 @@ public class GenerateSourcesTest {
     private MavenProject project;
 
     @Before
-    public void setUp() {
+    public void setUp() throws MojoFailureException {
         MockitoAnnotations.initMocks(this);
 
-        yang = new File(getClass().getResource("/mock.yang").getFile())
+        yang = new File(getClass().getResource("/yang/mock.yang").getFile())
                 .getParent();
         outDir = new File("/outputDir");
-        mojo = new YangToSourcesMojo(
-                new CodeGeneratorArg[] { new CodeGeneratorArg(
-                        GeneratorMock.class.getName(), "outputDir") }, yang);
+        YangProvider mock = mock(YangProvider.class);
+        doNothing().when(mock).addYangsToMETA_INF(any(Log.class),
+                any(MavenProject.class), any(File.class));
+
+        YangToSourcesProcessor processor = new YangToSourcesProcessor(
+                mock(Log.class), new File(yang),
+                Lists.newArrayList(new CodeGeneratorArg(GeneratorMock.class
+                        .getName(), "outputDir")), project, false,
+                mock);
+        mojo = new YangToSourcesMojo(processor);
         doReturn(new File("")).when(project).getBasedir();
         mojo.project = project;
     }
 
-    @Ignore
     @Test
     public void test() throws Exception {
         mojo.execute();
         assertThat(GeneratorMock.called, is(1));
         assertThat(GeneratorMock.outputDir, is(outDir));
+        assertThat(GeneratorMock.project, is(project));
         assertNotNull(GeneratorMock.log);
         assertTrue(GeneratorMock.additionalCfg.isEmpty());
+        assertThat(GeneratorMock.resourceBaseDir.toString(),
+                containsString("target" + File.separator
+                        + "generated-resources"));
     }
 
     public static class GeneratorMock implements CodeGenerator {
@@ -69,11 +82,13 @@ public class GenerateSourcesTest {
         private static File outputDir;
         private static Log log;
         private static Map<String, String> additionalCfg;
+        private static File resourceBaseDir;
+        private static MavenProject project;
 
         @Override
         public Collection<File> generateSources(SchemaContext context,
-                File outputBaseDir, Set<Module> currentModules,
-                File projectBaseDir) throws IOException {
+                File outputBaseDir, Set<Module> currentModules)
+                throws IOException {
             called++;
             outputDir = outputBaseDir;
             return Lists.newArrayList();
@@ -81,13 +96,24 @@ public class GenerateSourcesTest {
 
         @Override
         public void setLog(Log log) {
-            this.log = log;
+            GeneratorMock.log = log;
         }
 
         @Override
         public void setAdditionalConfig(
                 Map<String, String> additionalConfiguration) {
-            this.additionalCfg = additionalConfiguration;
+            GeneratorMock.additionalCfg = additionalConfiguration;
+        }
+
+        @Override
+        public void setResourceBaseDir(File resourceBaseDir) {
+            GeneratorMock.resourceBaseDir = resourceBaseDir;
+
+        }
+
+        @Override
+        public void setMavenProject(MavenProject project) {
+            GeneratorMock.project = project;
         }
     }
 
index 96a4d57a00d97f3a8ec9e36b0bccd84e13c551f0..240825409fcc8459209c1d3a407aea4a0acd6e1a 100644 (file)
@@ -7,19 +7,20 @@
  */
 package org.opendaylight.controller.yang2sources.plugin;
 
-import org.junit.Test;
+import static org.junit.Assert.*;
 
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Collection;
 
-import static org.junit.Assert.assertTrue;
+import org.junit.Test;
 
 public class UtilTest {
 
     @Test
     public void testCache() throws FileNotFoundException {
-        String yang = new File(getClass().getResource("/mock.yang").getFile())
+        String yang = new File(getClass().getResource("/yang/mock.yang")
+                .getFile())
                 .getParent();
         Collection<File> files = Util.listFiles(new File(yang));
         Collection<File> files2 = Util.listFiles(new File(yang));
index 9c4475cd40b966f3ab4ba3596c464d8bddbafac4..bb6de3f3c70936bf91904aa4958e30ca7a7cda8b 100644 (file)
@@ -4,7 +4,7 @@
     <parent>
         <artifactId>yang</artifactId>
         <groupId>org.opendaylight.controller</groupId>
-        <version>0.5.1-SNAPSHOT</version>
+        <version>0.5.2-SNAPSHOT</version>
         <relativePath>../../yang/pom.xml</relativePath>
     </parent>
     <artifactId>yang-maven-plugin-spi</artifactId>
             <artifactId>maven-plugin-api</artifactId>
             <version>3.0.5</version>
         </dependency>
+        <dependency>
+            <groupId>org.apache.maven</groupId>
+            <artifactId>maven-core</artifactId>
+            <version>3.0.5</version>
+        </dependency>
     </dependencies>
 
     <build>
index df33d4c5919e81070c8947d2d30b01182fd85a3a..09dcd3e8e9ca2cafc18d5745bcafb6016c64eedb 100644 (file)
@@ -14,6 +14,7 @@ import java.util.Map;
 import java.util.Set;
 
 import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.project.MavenProject;
 import org.opendaylight.controller.yang.model.api.Module;
 import org.opendaylight.controller.yang.model.api.SchemaContext;
 
@@ -39,10 +40,36 @@ public interface CodeGenerator {
      * @throws IOException
      */
     Collection<File> generateSources(SchemaContext context, File outputBaseDir,
-            Set<Module> currentModules, File projectBaseDir)
-            throws IOException;
+            Set<Module> currentModules) throws IOException;
 
+    /**
+     * Utilize maven logging if necessary
+     *
+     * @param log
+     */
     void setLog(Log log);
 
+    /**
+     * Provided map contains all configuration that was set in pom for code
+     * generator in additionalConfiguration tag
+     *
+     * @param additionalConfiguration
+     */
     void setAdditionalConfig(Map<String, String> additionalConfiguration);
+
+    /**
+     * Provided folder is marked as resources and its content will be packaged
+     * in resulting jar. Feel free to add necessary resources
+     *
+     * @param resourceBaseDir
+     */
+    void setResourceBaseDir(File resourceBaseDir);
+
+    /**
+     * Provided maven project object. Any additional information about current
+     * maven project can be accessed from it.
+     *
+     * @param resourceBaseDir
+     */
+    void setMavenProject(MavenProject project);
 }
index 172a2f25b67dcd03ed540bda966593e68bd0d367..3103042f9970c4d2d24ab606f709322f8daa85e4 100644 (file)
@@ -13,27 +13,55 @@ import java.util.Map;
 import java.util.Set;
 
 import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.project.MavenProject;
 import org.opendaylight.controller.yang.model.api.Module;
 import org.opendaylight.controller.yang.model.api.SchemaContext;
 
 public class CodeGeneratorTestImpl implements CodeGenerator {
 
+    private Log log;
+
     @Override
     public Collection<File> generateSources(SchemaContext context,
-            File outputBaseDir, Set<Module> currentModuleBuilders,
-            File projectMainDir) {
-        // no-op
+            File outputBaseDir, Set<Module> currentModuleBuilders) {
+        if (log != null) {
+            log.debug(getClass().getCanonicalName()
+                    + " generateSources:context: " + context);
+            log.debug(getClass().getCanonicalName()
+                    + " generateSources:outputBaseDir: " + outputBaseDir);
+            log.debug(getClass().getCanonicalName()
+                    + " generateSources:currentModuleBuilders: "
+                    + currentModuleBuilders);
+
+        }
         return null;
     }
 
     @Override
     public void setLog(Log log) {
-        // no-op
+        this.log = log;
     }
 
     @Override
     public void setAdditionalConfig(Map<String, String> additionalConfiguration) {
-        // no-op
+        if (log != null)
+            log.debug(getClass().getCanonicalName() + " additionalConfig: "
+                    + additionalConfiguration);
+    }
+
+
+    @Override
+    public void setResourceBaseDir(File resourceBaseDir) {
+        if (log != null)
+            log.debug(getClass().getCanonicalName() + " resourceBaseDir: "
+                    + resourceBaseDir);
+    }
+
+    @Override
+    public void setMavenProject(MavenProject project) {
+        if (log != null)
+            log.debug(getClass().getCanonicalName() + " maven project: "
+                    + project);
     }
 
 }
index 9edca3cd228b5cfd8caeead7dcd2b01a8d1376dd..eb30ea3b3b7b4c5b60966561e4bce6a429554471 100644 (file)
@@ -17,7 +17,7 @@
     <properties>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
         <!-- version of YANG tools dependencies -->
-        <yang.version>0.5.1-SNAPSHOT</yang.version>
+        <yang.version>0.5.2-SNAPSHOT</yang.version>
     </properties>
 
     <modules>
index 357e6bab0bbc0715bb7fd10a41c38997128d4217..600e87d2679c8e2ad0cf3e2eb2481327631f21ca 100644 (file)
@@ -11,7 +11,6 @@ module controller-network {
        
 
        
-       
        typedef topology-id {
                type string;
        }
diff --git a/opendaylight/sal/yang-prototype/code-generator/samples/modeling-sample/pom.xml b/opendaylight/sal/yang-prototype/code-generator/samples/modeling-sample/pom.xml
new file mode 100644 (file)
index 0000000..260303e
--- /dev/null
@@ -0,0 +1,116 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+       <modelVersion>4.0.0</modelVersion>
+       <parent>
+               <artifactId>binding-generator</artifactId>
+               <groupId>org.opendaylight.controller</groupId>
+               <version>0.5.1-SNAPSHOT</version>
+       </parent>
+       <artifactId>modeling-sample</artifactId>
+
+       <build>
+               <plugins>
+                       <plugin>
+                               <groupId>org.opendaylight.controller</groupId>
+                               <artifactId>yang-maven-plugin</artifactId>
+                               <version>0.5.1-SNAPSHOT</version>
+                               <executions>
+                                       <execution>
+                                               <goals>
+                                                       <goal>generate-sources</goal>
+                                               </goals>
+                                               <configuration>
+                                                       <yangFilesRootDir>src/main/yang</yangFilesRootDir>
+                                                       <codeGenerators>
+                                                               <generator>
+                                                                       <codeGeneratorClass>
+                                                                               org.opendaylight.controller.maven.sal.api.gen.plugin.CodeGeneratorImpl
+                                                                       </codeGeneratorClass>
+                                                                       <outputBaseDir>
+                                                                               target/generated-sources/sal
+                                                                       </outputBaseDir>
+                                                               </generator>
+                                                       </codeGenerators>
+                                                       <inspectDependencies>false</inspectDependencies>
+                                               </configuration>
+                                       </execution>
+                               </executions>
+
+                               <dependencies>
+                                       <dependency>
+                                               <groupId>org.opendaylight.controller</groupId>
+                                               <artifactId>maven-sal-api-gen-plugin</artifactId>
+                                               <version>0.5.1-SNAPSHOT</version>
+                                               <type>jar</type>
+                                       </dependency>
+                               </dependencies>
+                       </plugin>
+                       <plugin>
+                               <groupId>org.codehaus.mojo</groupId>
+                               <artifactId>build-helper-maven-plugin</artifactId>
+                               <version>1.7</version>
+                               <executions>
+                                       <execution>
+                                               <phase>generate-sources</phase>
+                                               <goals>
+                                                       <goal>add-source</goal>
+                                               </goals>
+                                               <configuration>
+                                                       <sources>
+                                                               <source>target/generated-sources/sal</source>
+                                                       </sources>
+                                               </configuration>
+                                       </execution>
+                               </executions>
+                       </plugin>
+               </plugins>
+               <pluginManagement>
+                       <plugins>
+                               <!--This plugin's configuration is used to store Eclipse m2e settings 
+                                       only. It has no influence on the Maven build itself. -->
+                               <plugin>
+                                       <groupId>org.eclipse.m2e</groupId>
+                                       <artifactId>lifecycle-mapping</artifactId>
+                                       <version>1.0.0</version>
+                                       <configuration>
+                                               <lifecycleMappingMetadata>
+                                                       <pluginExecutions>
+                                                               <pluginExecution>
+                                                                       <pluginExecutionFilter>
+                                                                               <groupId>
+                                                                                       org.opendaylight.controller
+                                                                               </groupId>
+                                                                               <artifactId>
+                                                                                       yang-maven-plugin
+                                                                               </artifactId>
+                                                                               <versionRange>
+                                                                                       [0.5,)
+                                                                               </versionRange>
+                                                                               <goals>
+                                                                                       <goal>
+                                                                                               generate-sources
+                                                                                       </goal>
+                                                                               </goals>
+                                                                       </pluginExecutionFilter>
+                                                                       <action>
+                                                                               <ignore></ignore>
+                                                                       </action>
+                                                               </pluginExecution>
+                                                       </pluginExecutions>
+                                               </lifecycleMappingMetadata>
+                                       </configuration>
+                               </plugin>
+                       </plugins>
+               </pluginManagement>
+       </build>
+       <dependencies>
+               <dependency>
+                       <groupId>org.opendaylight.controller</groupId>
+                       <artifactId>yang-binding</artifactId>
+               </dependency>
+               <dependency>
+                       <groupId>org.opendaylight.controller</groupId>
+                       <artifactId>yang-common</artifactId>
+               </dependency>
+       </dependencies>
+</project>
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/samples/modeling-sample/src/main/yang/sample.yang b/opendaylight/sal/yang-prototype/code-generator/samples/modeling-sample/src/main/yang/sample.yang
new file mode 100644 (file)
index 0000000..3ecdc0a
--- /dev/null
@@ -0,0 +1,62 @@
+module sample {
+    yang-version 1;
+    namespace "sample";
+    prefix "s";
+
+    revision 2013-06-13 {
+       description "Initial demo";
+    }
+    
+
+
+    // Simple Type definition
+    
+    typedef foo-name {
+        type string;
+    }
+    
+    // Storage / data structure
+    
+    container topologies {
+        list topology {
+            leaf foo-name {
+                type string;
+            }
+        }
+    }
+    
+    
+    // Notification / Event
+    
+    notification packet-in {
+        leaf node {
+            type string;
+        }
+        leaf port {
+            type uint16;
+        }
+        leaf content {
+            type binary;
+        }
+    }
+    
+    // RPC
+    
+    rpc packet-out {
+        input {
+            leaf node {
+                type string;
+            }
+            leaf port {
+                type uint16;
+            }
+            leaf content {
+                type binary;
+            }
+        }
+        output {
+            
+        }
+    }    
+
+}
\ No newline at end of file
index 547d83adc8ed617db4d421e3835f1911b5bc5b39..53ca93140676641d935bb4ab8081e66b88ddbc30 100644 (file)
@@ -3,7 +3,7 @@
   <parent>
     <groupId>org.opendaylight.controller</groupId>
     <artifactId>yang</artifactId>
-    <version>0.5.1-SNAPSHOT</version>
+    <version>0.5.2-SNAPSHOT</version>
     <relativePath>../../yang/pom.xml</relativePath>
   </parent>
   <artifactId>yang-model-parser-api</artifactId>
index 16a746905e0fc2d5f192b05ee404aad18aa5ee44..b83d63f9b08f576c977a082164a6558c3cfd507c 100644 (file)
@@ -4,7 +4,7 @@
        <parent>\r
                <groupId>org.opendaylight.controller</groupId>\r
                <artifactId>yang</artifactId>\r
-               <version>0.5.1-SNAPSHOT</version>\r
+               <version>0.5.2-SNAPSHOT</version>\r
                <relativePath>../../yang/pom.xml</relativePath>\r
        </parent>\r
        <artifactId>yang-model-parser-impl</artifactId>\r
index 1c4a4acde47907545a63001102c251357be8cd03..c295c0eafdc824f68b04249f463cbc4630a42c10 100644 (file)
@@ -19,9 +19,13 @@ import org.opendaylight.controller.yang.parser.util.RefineHolder;
  */
 public interface UsesNodeBuilder extends Builder {
 
-    String getGroupingPathString();
+    String getGroupingName();
 
-    SchemaPath getGroupingPath();
+    void setGroupingPath(SchemaPath groupingPath);
+
+    SchemaPath getPath();
+
+    void setPath(SchemaPath path);
 
     Set<AugmentationSchemaBuilder> getAugmentations();
 
index e5ba8b17ccfe1f872070e491cf9c6396d8623557..775751a166ef7d2c58a9565d3cd9bb1bef5692c4 100644 (file)
@@ -68,6 +68,11 @@ public final class AugmentationSchemaBuilderImpl implements AugmentationSchemaBu
         return childNodes;
     }
 
+    @Override
+    public Set<GroupingBuilder> getGroupings() {
+        return groupings;
+    }
+
     @Override
     public void addGrouping(GroupingBuilder grouping) {
         groupings.add(grouping);
index ba9609b4db7f03eea305ae6b64bda80bc66b5fba..ec9c35c1bd37c14f97cc93994174bfb10c7f384d 100644 (file)
@@ -290,6 +290,7 @@ public final class LeafSchemaNodeBuilder extends AbstractTypeAwareBuilder
             }
         }
 
+        @Override
         public String getDefault() {
             return defaultStr;
         }
@@ -298,6 +299,7 @@ public final class LeafSchemaNodeBuilder extends AbstractTypeAwareBuilder
             this.defaultStr = defaultStr;
         }
 
+        @Override
         public String getUnits() {
             return unitsStr;
         }
index 6940e91e382247b384157f715d02fe4f948411fb..fa307972d49c7be12e57a12f7d9a9901881075b5 100644 (file)
@@ -71,7 +71,6 @@ public class ModuleBuilder implements Builder {
     private final Map<List<String>, GroupingBuilder> addedGroupings = new HashMap<List<String>, GroupingBuilder>();
     private final List<AugmentationSchemaBuilder> addedAugments = new ArrayList<AugmentationSchemaBuilder>();
     private final Map<List<String>, UsesNodeBuilder> addedUsesNodes = new HashMap<List<String>, UsesNodeBuilder>();
-    //private final Map<List<String>, RefineHolder> addedRefines = new HashMap<List<String>, RefineHolder>();
     private final Map<List<String>, RpcDefinitionBuilder> addedRpcs = new HashMap<List<String>, RpcDefinitionBuilder>();
     private final Set<NotificationBuilder> addedNotifications = new HashSet<NotificationBuilder>();
     private final Set<IdentitySchemaNodeBuilder> addedIdentities = new HashSet<IdentitySchemaNodeBuilder>();
@@ -177,6 +176,14 @@ public class ModuleBuilder implements Builder {
         actualPath.pop();
     }
 
+    public Builder getActualNode() {
+        if (actualPath.isEmpty()) {
+            return null;
+        } else {
+            return actualPath.get(0);
+        }
+    }
+
     public Builder getModuleNode(final List<String> path) {
         return childNodes.get(path);
     }
@@ -233,6 +240,17 @@ public class ModuleBuilder implements Builder {
         return typedefs;
     }
 
+    public Set<GroupingBuilder> getModuleGroupings() {
+        final Set<GroupingBuilder> groupings = new HashSet<GroupingBuilder>();
+        for (Map.Entry<List<String>, GroupingBuilder> entry : addedGroupings
+                .entrySet()) {
+            if (entry.getKey().size() == 2) {
+                groupings.add(entry.getValue());
+            }
+        }
+        return groupings;
+    }
+
     public String getName() {
         return name;
     }
@@ -756,6 +774,11 @@ public class ModuleBuilder implements Builder {
         return builder;
     }
 
+    @Override
+    public String toString() {
+        return ModuleBuilder.class.getSimpleName() + "[" + name + "]";
+    }
+
     private final class ModuleImpl implements Module {
         private URI namespace;
         private final String name;
@@ -1101,8 +1124,7 @@ public class ModuleBuilder implements Builder {
                 if (parent instanceof AugmentationSchemaBuilder) {
                     nodeBuilder.setAugmenting(true);
                 }
-                ((DataNodeContainerBuilder) parent)
-                        .addChildNode(nodeBuilder);
+                ((DataNodeContainerBuilder) parent).addChildNode(nodeBuilder);
             } else if (parent instanceof ChoiceBuilder) {
                 ((ChoiceBuilder) parent).addChildNode(nodeBuilder);
             } else {
index 5b9638eb63dc715a7b58a6b810fe6095810fa938..6cbcec1054a1b58256fe4cec1e6731cce7ef0d41 100644 (file)
@@ -103,6 +103,10 @@ public final class RpcDefinitionBuilder implements SchemaNodeBuilder,
         addedTypedefs.add(type);
     }
 
+    public Set<GroupingBuilder> getGroupings() {
+        return addedGroupings;
+    }
+
     public void addGrouping(GroupingBuilder grouping) {
         addedGroupings.add(grouping);
     }
index d60dbbb615c71449bd74adfb3e9f3c391b2eb027..a8628eae72dab5e38af177b8a0942f50e867e8a9 100644 (file)
@@ -32,6 +32,7 @@ public final class TypeDefinitionBuilderImpl extends AbstractTypeAwareBuilder
     private SchemaPath schemaPath;
 
     private final List<UnknownSchemaNodeBuilder> addedUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();
+    private List<UnknownSchemaNode> unknownNodes;
     private List<RangeConstraint> ranges = Collections.emptyList();
     private List<LengthConstraint> lengths = Collections.emptyList();
     private List<PatternConstraint> patterns = Collections.emptyList();
@@ -73,9 +74,11 @@ public final class TypeDefinitionBuilderImpl extends AbstractTypeAwareBuilder
         typeBuilder.fractionDigits(fractionDigits);
 
         // UNKNOWN NODES
-        final List<UnknownSchemaNode> unknownNodes = new ArrayList<UnknownSchemaNode>();
-        for (UnknownSchemaNodeBuilder b : addedUnknownNodes) {
-            unknownNodes.add(b.build());
+        if (unknownNodes == null) {
+            unknownNodes = new ArrayList<UnknownSchemaNode>();
+            for (UnknownSchemaNodeBuilder b : addedUnknownNodes) {
+                unknownNodes.add(b.build());
+            }
         }
         typeBuilder.unknownSchemaNodes(unknownNodes);
         result = typeBuilder.build();
@@ -164,6 +167,10 @@ public final class TypeDefinitionBuilderImpl extends AbstractTypeAwareBuilder
         addedUnknownNodes.add(unknownNode);
     }
 
+    public void setUnknownNodes(List<UnknownSchemaNode> unknownNodes) {
+        this.unknownNodes = unknownNodes;
+    }
+
     @Override
     public List<RangeConstraint> getRanges() {
         return ranges;
index dba747db1dd9bad3aa31a3d265279119d8434b85..850938161bf4c25cc30fd5d7e7270d0056d9f596 100644 (file)
@@ -15,7 +15,6 @@ import java.util.List;
 import java.util.Map;\r
 import java.util.Set;\r
 \r
-import org.opendaylight.controller.yang.common.QName;\r
 import org.opendaylight.controller.yang.model.api.AugmentationSchema;\r
 import org.opendaylight.controller.yang.model.api.SchemaNode;\r
 import org.opendaylight.controller.yang.model.api.SchemaPath;\r
@@ -27,25 +26,25 @@ import org.opendaylight.controller.yang.parser.util.RefineHolder;
 \r
 public final class UsesNodeBuilderImpl implements UsesNodeBuilder {\r
     private boolean isBuilt;\r
-    private final UsesNodeImpl instance;\r
+    private UsesNodeImpl instance;\r
     private final int line;\r
-    private final String groupingPathStr;\r
-    private final SchemaPath groupingPath;\r
+    private SchemaPath schemaPath;\r
+    private final String groupingName;\r
+    private SchemaPath groupingPath;\r
     private boolean augmenting;\r
     private final Set<AugmentationSchemaBuilder> addedAugments = new HashSet<AugmentationSchemaBuilder>();\r
     private List<SchemaNodeBuilder> refineBuilders = new ArrayList<SchemaNodeBuilder>();\r
     private List<RefineHolder> refines = new ArrayList<RefineHolder>();\r
 \r
-    public UsesNodeBuilderImpl(final String groupingPathStr, final int line) {\r
-        this.groupingPathStr = groupingPathStr;\r
-        this.groupingPath = parseUsesPath(groupingPathStr);\r
+    public UsesNodeBuilderImpl(final String groupingName, final int line) {\r
+        this.groupingName = groupingName;\r
         this.line = line;\r
-        instance = new UsesNodeImpl(groupingPath);\r
     }\r
 \r
     @Override\r
     public UsesNode build() {\r
         if (!isBuilt) {\r
+            instance = new UsesNodeImpl(groupingPath);\r
             instance.setAugmenting(augmenting);\r
 \r
             // AUGMENTATIONS\r
@@ -74,13 +73,23 @@ public final class UsesNodeBuilderImpl implements UsesNodeBuilder {
     }\r
 \r
     @Override\r
-    public String getGroupingPathString() {\r
-        return groupingPathStr;\r
+    public void setGroupingPath(SchemaPath groupingPath) {\r
+        this.groupingPath = groupingPath;\r
     }\r
 \r
     @Override\r
-    public SchemaPath getGroupingPath() {\r
-        return groupingPath;\r
+    public SchemaPath getPath() {\r
+        return schemaPath;\r
+    }\r
+\r
+    @Override\r
+    public void setPath(SchemaPath path) {\r
+        this.schemaPath = path;\r
+    }\r
+\r
+    @Override\r
+    public String getGroupingName() {\r
+        return groupingName;\r
     }\r
 \r
     @Override\r
@@ -123,23 +132,6 @@ public final class UsesNodeBuilderImpl implements UsesNodeBuilder {
         refines.add(refine);\r
     }\r
 \r
-    private SchemaPath parseUsesPath(final String groupingPathStr) {\r
-        final String[] splittedPath = groupingPathStr.split("/");\r
-        final List<QName> path = new ArrayList<QName>();\r
-        QName name;\r
-        for (String pathElement : splittedPath) {\r
-            final String[] splittedElement = pathElement.split(":");\r
-            if (splittedElement.length == 1) {\r
-                name = new QName(null, null, null, splittedElement[0]);\r
-            } else {\r
-                name = new QName(null, null, splittedElement[0],\r
-                        splittedElement[1]);\r
-            }\r
-            path.add(name);\r
-        }\r
-        final boolean absolute = groupingPathStr.startsWith("/");\r
-        return new SchemaPath(path, absolute);\r
-    }\r
 \r
     private final class UsesNodeImpl implements UsesNode {\r
         private final SchemaPath groupingPath;\r
index 401189b1d1efbb11a79801c9837fb1053f1f226d..94437170f4be3c8ef91ae774debd26cb1d4f8963 100644 (file)
@@ -41,15 +41,11 @@ import org.opendaylight.controller.yang.model.api.TypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.BinaryTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.DecimalTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.IntegerTypeDefinition;
-import org.opendaylight.controller.yang.model.api.type.LengthConstraint;
-import org.opendaylight.controller.yang.model.api.type.PatternConstraint;
-import org.opendaylight.controller.yang.model.api.type.RangeConstraint;
 import org.opendaylight.controller.yang.model.api.type.StringTypeDefinition;
 import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
 import org.opendaylight.controller.yang.model.util.ExtendedType;
 import org.opendaylight.controller.yang.model.util.IdentityrefType;
 import org.opendaylight.controller.yang.model.util.UnknownType;
-import org.opendaylight.controller.yang.model.util.YangTypesConverter;
 import org.opendaylight.controller.yang.parser.builder.api.AugmentationSchemaBuilder;
 import org.opendaylight.controller.yang.parser.builder.api.AugmentationTargetBuilder;
 import org.opendaylight.controller.yang.parser.builder.api.Builder;
@@ -232,6 +228,7 @@ public final class YangParserImpl implements YangModelParser {
             final YangLexer lexer = new YangLexer(input);
             final CommonTokenStream tokens = new CommonTokenStream(lexer);
             final YangParser parser = new YangParser(tokens);
+
             result = parser.yang();
         } catch (IOException e) {
             logger.warn("Exception while reading yang file: " + yangStream, e);
@@ -297,222 +294,116 @@ public final class YangParserImpl implements YangModelParser {
         if (!dirtyNodes.isEmpty()) {
             for (Map.Entry<List<String>, TypeAwareBuilder> entry : dirtyNodes
                     .entrySet()) {
-
                 final TypeAwareBuilder nodeToResolve = entry.getValue();
-                // different handling for union types
+
                 if (nodeToResolve instanceof UnionTypeBuilder) {
-                    final UnionTypeBuilder union = (UnionTypeBuilder) nodeToResolve;
-                    final List<TypeDefinition<?>> unionTypes = union.getTypes();
-                    final List<UnknownType> toRemove = new ArrayList<UnknownType>();
-                    for (TypeDefinition<?> td : unionTypes) {
-                        if (td instanceof UnknownType) {
-                            final UnknownType unknownType = (UnknownType) td;
-                            final TypeDefinitionBuilder resolvedType = resolveTypeUnion(
-                                    nodeToResolve, unknownType, modules, module);
-                            union.setTypedef(resolvedType);
-                            toRemove.add(unknownType);
-                        }
-                    }
-                    unionTypes.removeAll(toRemove);
+                    // special handling for union types
+                    resolveTypeUnion((UnionTypeBuilder) nodeToResolve, modules,
+                            module);
                 } else if (nodeToResolve.getTypedef() instanceof IdentityrefTypeBuilder) {
-                    // different handling for identityref types
+                    // special handling for identityref types
                     IdentityrefTypeBuilder idref = (IdentityrefTypeBuilder) nodeToResolve
                             .getTypedef();
                     nodeToResolve.setType(new IdentityrefType(findFullQName(
                             modules, module, idref), idref.getPath()));
                 } else {
-                    final TypeDefinitionBuilder resolvedType = resolveType(
-                            nodeToResolve, modules, module);
-                    nodeToResolve.setTypedef(resolvedType);
+                    resolveType(nodeToResolve, modules, module);
                 }
             }
         }
     }
 
-    private TypeDefinitionBuilder resolveType(
-            final TypeAwareBuilder nodeToResolve,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder builder) {
-        final TypeConstraints constraints = new TypeConstraints();
-
-        final TypeDefinitionBuilder targetTypeBuilder = getTypeDefinitionBuilderFromDirtyNode(
-                nodeToResolve, modules, builder);
-        final TypeConstraints tConstraints = findConstraints(nodeToResolve,
-                constraints, modules, builder);
-        targetTypeBuilder.setRanges(tConstraints.getRange());
-        targetTypeBuilder.setLengths(tConstraints.getLength());
-        targetTypeBuilder.setPatterns(tConstraints.getPatterns());
-        targetTypeBuilder.setFractionDigits(tConstraints.getFractionDigits());
-
-        return targetTypeBuilder;
-    }
-
-    private TypeDefinitionBuilder resolveTypeUnion(
-            final TypeAwareBuilder typeToResolve,
-            final UnknownType unknownType,
+    private void resolveType(final TypeAwareBuilder nodeToResolve,
             final Map<String, TreeMap<Date, ModuleBuilder>> modules,
             final ModuleBuilder builder) {
-        final TypeConstraints constraints = new TypeConstraints();
-
-        final TypeDefinitionBuilder targetTypeBuilder = getUnionBuilder(
-                typeToResolve, unknownType, modules, builder);
-        final TypeConstraints tConstraints = findConstraints(typeToResolve,
-                constraints, modules, builder);
-        targetTypeBuilder.setRanges(tConstraints.getRange());
-        targetTypeBuilder.setLengths(tConstraints.getLength());
-        targetTypeBuilder.setPatterns(tConstraints.getPatterns());
-        targetTypeBuilder.setFractionDigits(tConstraints.getFractionDigits());
-
-        return targetTypeBuilder;
-    }
-
-    private TypeDefinitionBuilder getTypeDefinitionBuilderFromDirtyNode(
-            final TypeAwareBuilder nodeToResolve,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module) {
-
-        final UnknownType unknownType = (UnknownType) nodeToResolve.getType();
-        final QName unknownTypeQName = unknownType.getQName();
-
-        // search for module which contains referenced typedef
+        TypeDefinitionBuilder resolvedType = null;
+        final int line = nodeToResolve.getLine();
+        final TypeDefinition<?> typedefType = nodeToResolve.getType();
+        final QName unknownTypeQName = typedefType.getBaseType().getQName();
         final ModuleBuilder dependentModule = findDependentModule(modules,
-                module, unknownTypeQName.getPrefix(), nodeToResolve.getLine());
+                builder, unknownTypeQName.getPrefix(), line);
 
-        final TypeDefinitionBuilder lookedUpBuilder = findTypeDefinitionBuilder(
+        final TypeDefinitionBuilder targetTypeBuilder = findTypeDefinitionBuilder(
                 nodeToResolve.getPath(), dependentModule,
-                unknownTypeQName.getLocalName(), module.getName(),
-                nodeToResolve.getLine());
-
-        final TypeDefinitionBuilder lookedUpBuilderCopy = copyTypedefBuilder(
-                lookedUpBuilder, nodeToResolve instanceof TypeDefinitionBuilder);
-        final TypeDefinitionBuilder resolvedCopy = resolveCopiedBuilder(
-                lookedUpBuilderCopy, modules, dependentModule);
-        return resolvedCopy;
-    }
+                unknownTypeQName.getLocalName(), builder.getName(), line);
 
-    private TypeDefinitionBuilder getUnionBuilder(
-            final TypeAwareBuilder nodeToResolve,
-            final UnknownType unknownType,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module) {
-
-        final TypeDefinition<?> baseTypeToResolve = nodeToResolve.getType();
-        if (baseTypeToResolve != null
-                && !(baseTypeToResolve instanceof UnknownType)) {
-            return (TypeDefinitionBuilder) nodeToResolve;
-        }
-
-        final QName unknownTypeQName = unknownType.getQName();
-        // search for module which contains referenced typedef
-        final ModuleBuilder dependentModule = findDependentModule(modules,
-                module, unknownTypeQName.getPrefix(), nodeToResolve.getLine());
-        final TypeDefinitionBuilder lookedUpBuilder = findTypeDefinitionBuilder(
-                nodeToResolve.getPath(), dependentModule,
-                unknownTypeQName.getLocalName(), module.getName(),
-                nodeToResolve.getLine());
-
-        final TypeDefinitionBuilder lookedUpBuilderCopy = copyTypedefBuilder(
-                lookedUpBuilder, nodeToResolve instanceof TypeDefinitionBuilder);
-        final TypeDefinitionBuilder resolvedCopy = resolveCopiedBuilder(
-                lookedUpBuilderCopy, modules, dependentModule);
-        return resolvedCopy;
-    }
-
-    private TypeDefinitionBuilder copyTypedefBuilder(
-            final TypeDefinitionBuilder old, final boolean seekByTypedefBuilder) {
-        if (old instanceof UnionTypeBuilder) {
-            final UnionTypeBuilder oldUnion = (UnionTypeBuilder) old;
-            final UnionTypeBuilder newUnion = new UnionTypeBuilder(
-                    old.getLine());
-            for (TypeDefinition<?> td : oldUnion.getTypes()) {
-                newUnion.setType(td);
-            }
-            for (TypeDefinitionBuilder tdb : oldUnion.getTypedefs()) {
-                newUnion.setTypedef(copyTypedefBuilder(tdb, true));
-            }
-            newUnion.setPath(old.getPath());
-            return newUnion;
-        }
-
-        final QName oldName = old.getQName();
-        final QName newName = new QName(oldName.getNamespace(),
-                oldName.getRevision(), oldName.getPrefix(),
-                oldName.getLocalName());
-        final TypeDefinitionBuilder tdb = new TypeDefinitionBuilderImpl(
-                newName, old.getLine());
-
-        tdb.setRanges(old.getRanges());
-        tdb.setLengths(old.getLengths());
-        tdb.setPatterns(old.getPatterns());
-        tdb.setFractionDigits(old.getFractionDigits());
-        tdb.setPath(old.getPath());
-
-        final TypeDefinition<?> oldType = old.getType();
-        if (oldType == null) {
-            tdb.setTypedef(old.getTypedef());
+        if (typedefType instanceof ExtendedType) {
+            final ExtendedType extType = (ExtendedType) typedefType;
+            final TypeDefinitionBuilder newType = extendedTypeWithNewBaseType(
+                    nodeToResolve, targetTypeBuilder, extType, modules, builder);
+            resolvedType = newType;
         } else {
-            tdb.setType(oldType);
-        }
-
-        if (!seekByTypedefBuilder) {
-            tdb.setDescription(old.getDescription());
-            tdb.setReference(old.getReference());
-            tdb.setStatus(old.getStatus());
-            tdb.setDefaultValue(old.getDefaultValue());
-            tdb.setUnits(old.getUnits());
+            resolvedType = targetTypeBuilder;
         }
-        return tdb;
+        nodeToResolve.setTypedef(resolvedType);
     }
 
-    private TypeDefinitionBuilder resolveCopiedBuilder(
-            final TypeDefinitionBuilder copy,
+    private void resolveTypeUnion(final UnionTypeBuilder union,
             final Map<String, TreeMap<Date, ModuleBuilder>> modules,
             final ModuleBuilder builder) {
 
-        if (copy instanceof UnionTypeBuilder) {
-            final UnionTypeBuilder union = (UnionTypeBuilder) copy;
-            final List<TypeDefinition<?>> unionTypes = union.getTypes();
-            final List<UnknownType> toRemove = new ArrayList<UnknownType>();
-            for (TypeDefinition<?> td : unionTypes) {
-                if (td instanceof UnknownType) {
-                    final UnknownType unknownType = (UnknownType) td;
-                    final TypeDefinitionBuilder resolvedType = resolveTypeUnion(
-                            union, unknownType, modules, builder);
-                    union.setTypedef(resolvedType);
-                    toRemove.add(unknownType);
+        final List<TypeDefinition<?>> unionTypes = union.getTypes();
+        final List<TypeDefinition<?>> toRemove = new ArrayList<TypeDefinition<?>>();
+        for (TypeDefinition<?> unionType : unionTypes) {
+            if (unionType instanceof UnknownType) {
+                final UnknownType ut = (UnknownType) unionType;
+                final ModuleBuilder dependentModule = findDependentModule(
+                        modules, builder, ut.getQName().getPrefix(),
+                        union.getLine());
+                final TypeDefinitionBuilder resolvedType = findTypeDefinitionBuilder(
+                        union.getPath(), dependentModule, ut.getQName()
+                                .getLocalName(), builder.getName(),
+                        union.getLine());
+                union.setTypedef(resolvedType);
+                toRemove.add(ut);
+            } else if (unionType instanceof ExtendedType) {
+                final ExtendedType extType = (ExtendedType) unionType;
+                TypeDefinition<?> extTypeBase = extType.getBaseType();
+                if (extTypeBase instanceof UnknownType) {
+                    final UnknownType ut = (UnknownType) extTypeBase;
+                    final ModuleBuilder dependentModule = findDependentModule(
+                            modules, builder, ut.getQName().getPrefix(),
+                            union.getLine());
+                    final TypeDefinitionBuilder targetTypeBuilder = findTypeDefinitionBuilder(
+                            union.getPath(), dependentModule, ut.getQName()
+                                    .getLocalName(), builder.getName(),
+                            union.getLine());
+
+                    final TypeDefinitionBuilder newType = extendedTypeWithNewBaseType(
+                            targetTypeBuilder, targetTypeBuilder, extType,
+                            modules, builder);
+
+                    union.setTypedef(newType);
+                    toRemove.add(extType);
                 }
             }
-            unionTypes.removeAll(toRemove);
-
-            return union;
         }
+        unionTypes.removeAll(toRemove);
+    }
 
-        final TypeDefinition<?> base = copy.getType();
-        final TypeDefinitionBuilder baseTdb = copy.getTypedef();
-        if (base != null && !(base instanceof UnknownType)) {
-            return copy;
-        } else if (base instanceof UnknownType) {
-            final UnknownType unknownType = (UnknownType) base;
-            final QName unknownTypeQName = unknownType.getQName();
-            final String unknownTypePrefix = unknownTypeQName.getPrefix();
-            final ModuleBuilder dependentModule = findDependentModule(modules,
-                    builder, unknownTypePrefix, copy.getLine());
-            final TypeDefinitionBuilder utBuilder = getTypeDefinitionBuilderFromDirtyNode(
-                    copy, modules, dependentModule);
-            copy.setTypedef(utBuilder);
-            return copy;
-        } else if (base == null && baseTdb != null) {
-            // make a copy of baseTypeDef and call again
-            final TypeDefinitionBuilder baseTdbCopy = copyTypedefBuilder(
-                    baseTdb, true);
-            final TypeDefinitionBuilder baseTdbCopyResolved = resolveCopiedBuilder(
-                    baseTdbCopy, modules, builder);
-            copy.setTypedef(baseTdbCopyResolved);
-            return copy;
-        } else {
-            throw new YangParseException(copy.getLine(),
-                    "Failed to resolve type " + copy.getQName().getLocalName());
-        }
+    private TypeDefinitionBuilder extendedTypeWithNewBaseType(
+            final TypeAwareBuilder nodeToResolve,
+            final TypeDefinitionBuilder newBaseType,
+            final ExtendedType oldExtendedType,
+            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            final ModuleBuilder builder) {
+        final TypeConstraints constraints = findConstraints(nodeToResolve,
+                new TypeConstraints(), modules, builder);
+        final TypeDefinitionBuilderImpl newType = new TypeDefinitionBuilderImpl(
+                oldExtendedType.getQName(), nodeToResolve.getLine());
+        newType.setTypedef(newBaseType);
+        newType.setPath(oldExtendedType.getPath());
+        newType.setDescription(oldExtendedType.getDescription());
+        newType.setReference(oldExtendedType.getReference());
+        newType.setStatus(oldExtendedType.getStatus());
+        newType.setLengths(constraints.getLength());
+        newType.setPatterns(constraints.getPatterns());
+        newType.setRanges(constraints.getRange());
+        newType.setFractionDigits(constraints.getFractionDigits());
+        newType.setUnits(oldExtendedType.getUnits());
+        newType.setDefaultValue(oldExtendedType.getDefaultValue());
+        newType.setUnknownNodes(oldExtendedType.getUnknownSchemaNodes());
+        return newType;
     }
 
     private TypeConstraints findConstraints(
@@ -520,77 +411,63 @@ public final class YangParserImpl implements YangModelParser {
             final TypeConstraints constraints,
             final Map<String, TreeMap<Date, ModuleBuilder>> modules,
             final ModuleBuilder builder) {
+
         // union type cannot be restricted
         if (nodeToResolve instanceof UnionTypeBuilder) {
             return constraints;
         }
 
-        // if referenced type is UnknownType again, search recursively with
-        // current constraints
-        final TypeDefinition<?> referencedType = nodeToResolve.getType();
-        List<RangeConstraint> ranges = Collections.emptyList();
-        List<LengthConstraint> lengths = Collections.emptyList();
-        List<PatternConstraint> patterns = Collections.emptyList();
-        Integer fractionDigits = null;
-        if (referencedType == null) {
-            final TypeDefinitionBuilder tdb = nodeToResolve.getTypedef();
-            ranges = tdb.getRanges();
-            constraints.addRanges(ranges);
-            lengths = tdb.getLengths();
-            constraints.addLengths(lengths);
-            patterns = tdb.getPatterns();
-            constraints.addPatterns(patterns);
-            fractionDigits = tdb.getFractionDigits();
-            constraints.setFractionDigits(fractionDigits);
-            return constraints;
-        } else if (referencedType instanceof ExtendedType) {
-            final ExtendedType ext = (ExtendedType) referencedType;
-            ranges = ext.getRanges();
-            constraints.addRanges(ranges);
-            lengths = ext.getLengths();
-            constraints.addLengths(lengths);
-            patterns = ext.getPatterns();
-            constraints.addPatterns(patterns);
-            fractionDigits = ext.getFractionDigits();
-            constraints.setFractionDigits(fractionDigits);
-            if(YangTypesConverter.isBaseYangType(ext.getBaseType().getQName().getLocalName())) {
-                mergeConstraints(ext.getBaseType(), constraints);
-                return constraints;
+        if (nodeToResolve instanceof TypeDefinitionBuilder) {
+            TypeDefinitionBuilder typedefToResolve = (TypeDefinitionBuilder) nodeToResolve;
+            constraints.addFractionDigits(typedefToResolve.getFractionDigits());
+            constraints.addLengths(typedefToResolve.getLengths());
+            constraints.addPatterns(typedefToResolve.getPatterns());
+            constraints.addRanges(typedefToResolve.getRanges());
+        }
+
+        TypeDefinition<?> type = nodeToResolve.getType();
+        if (type == null) {
+            return findConstraints(nodeToResolve.getTypedef(), constraints,
+                    modules, builder);
+        } else {
+            if (type instanceof UnknownType) {
+                ModuleBuilder dependentModule = findDependentModule(modules,
+                        builder, type.getQName().getPrefix(),
+                        nodeToResolve.getLine());
+                TypeDefinitionBuilder tdb = findTypeDefinitionBuilder(
+                        nodeToResolve.getPath(), dependentModule, type
+                                .getQName().getLocalName(), builder.getName(),
+                        nodeToResolve.getLine());
+                return findConstraints(tdb, constraints, modules,
+                        dependentModule);
+            } else if (type instanceof ExtendedType) {
+                ExtendedType extType = (ExtendedType) type;
+                constraints.addFractionDigits(extType.getFractionDigits());
+                constraints.addLengths(extType.getLengths());
+                constraints.addPatterns(extType.getPatterns());
+                constraints.addRanges(extType.getRanges());
+
+                TypeDefinition<?> base = extType.getBaseType();
+                if (base instanceof UnknownType) {
+                    ModuleBuilder dependentModule = findDependentModule(
+                            modules, builder, base.getQName().getPrefix(),
+                            nodeToResolve.getLine());
+                    TypeDefinitionBuilder tdb = findTypeDefinitionBuilder(
+                            nodeToResolve.getPath(), dependentModule, base
+                                    .getQName().getLocalName(),
+                            builder.getName(), nodeToResolve.getLine());
+                    return findConstraints(tdb, constraints, modules,
+                            dependentModule);
+                } else {
+                    // it has to be base yang type
+                    mergeConstraints(type, constraints);
+                    return constraints;
+                }
             } else {
-                return findConstraints(
-                        findTypeDefinitionBuilder(nodeToResolve.getPath(), builder,
-                                ext.getQName().getLocalName(), builder.getName(),
-                                nodeToResolve.getLine()), constraints, modules,
-                        builder);
-            }
-        } else if (referencedType instanceof UnknownType) {
-            final UnknownType unknown = (UnknownType) referencedType;
-            ranges = unknown.getRangeStatements();
-            constraints.addRanges(ranges);
-            lengths = unknown.getLengthStatements();
-            constraints.addLengths(lengths);
-            patterns = unknown.getPatterns();
-            constraints.addPatterns(patterns);
-            fractionDigits = unknown.getFractionDigits();
-            constraints.setFractionDigits(fractionDigits);
-
-            String unknownTypePrefix = unknown.getQName().getPrefix();
-            if (unknownTypePrefix == null || "".equals(unknownTypePrefix)) {
-                unknownTypePrefix = builder.getPrefix();
+                // it is base yang type
+                mergeConstraints(type, constraints);
+                return constraints;
             }
-            final ModuleBuilder dependentModule = findDependentModule(modules,
-                    builder, unknown.getQName().getPrefix(),
-                    nodeToResolve.getLine());
-            final TypeDefinitionBuilder utBuilder = findTypeDefinitionBuilder(
-                    nodeToResolve.getPath(), dependentModule, unknown
-                            .getQName().getLocalName(), builder.getName(),
-                    nodeToResolve.getLine());
-            return findConstraints(utBuilder, constraints, modules,
-                    dependentModule);
-        } else {
-            // HANDLE BASE YANG TYPE
-            mergeConstraints(referencedType, constraints);
-            return constraints;
         }
     }
 
@@ -677,7 +554,7 @@ public final class YangParserImpl implements YangModelParser {
             constraints.addRanges(((DecimalTypeDefinition) referencedType)
                     .getRangeStatements());
             constraints
-                    .setFractionDigits(((DecimalTypeDefinition) referencedType)
+                    .addFractionDigits(((DecimalTypeDefinition) referencedType)
                             .getFractionDigits());
         } else if (referencedType instanceof IntegerTypeDefinition) {
             constraints.addRanges(((IntegerTypeDefinition) referencedType)
@@ -884,15 +761,15 @@ public final class YangParserImpl implements YangModelParser {
                 .getUsesNodes();
         for (Map.Entry<List<String>, UsesNodeBuilder> entry : moduleUses
                 .entrySet()) {
-            final List<String> key = entry.getKey();
             final UsesNodeBuilder usesNode = entry.getValue();
             final int line = usesNode.getLine();
 
-            final String groupingName = key.get(key.size() - 1);
+            GroupingBuilder targetGrouping = getTargetGrouping(usesNode, modules, module);
+            usesNode.setGroupingPath(targetGrouping.getPath());
 
             for (RefineHolder refine : usesNode.getRefines()) {
                 SchemaNodeBuilder refineTarget = getRefineNodeBuilderCopy(
-                        groupingName, refine, modules, module);
+                        targetGrouping, refine, modules, module);
                 ParserUtils.checkRefine(refineTarget, refine);
                 ParserUtils.refineDefault(refineTarget, refine, line);
                 if (refineTarget instanceof LeafSchemaNodeBuilder) {
@@ -928,6 +805,82 @@ public final class YangParserImpl implements YangModelParser {
         }
     }
 
+    private GroupingBuilder getTargetGrouping(
+            final UsesNodeBuilder usesBuilder,
+            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            final ModuleBuilder module) {
+        final int line = usesBuilder.getLine();
+        String groupingString = usesBuilder.getGroupingName();
+        String groupingPrefix;
+        String groupingName;
+
+        if(groupingString.contains(":")) {
+            String[] splitted = groupingString.split(":");
+            if(splitted.length != 2 || groupingString.contains("/")) {
+                throw new YangParseException(module.getName(), line, "Invalid name of target grouping");
+            }
+            groupingPrefix = splitted[0];
+            groupingName = splitted[1];
+        } else {
+            groupingPrefix = module.getPrefix();
+            groupingName = groupingString;
+        }
+
+        ModuleBuilder dependentModule = null;
+        if(groupingPrefix.equals(module.getPrefix())) {
+            dependentModule = module;
+        } else {
+            dependentModule = findDependentModule(modules, module, groupingPrefix, line);
+        }
+
+
+        List<QName> path = usesBuilder.getPath().getPath();
+        GroupingBuilder result = null;
+        Set<GroupingBuilder> groupings = dependentModule.getModuleGroupings();
+        result = findGrouping(groupings, groupingName);
+
+        if (result == null) {
+            Builder currentNode = null;
+            final List<String> currentPath = new ArrayList<String>();
+            currentPath.add(dependentModule.getName());
+
+            for (int i = 0; i < path.size(); i++) {
+                QName qname = path.get(i);
+                currentPath.add(qname.getLocalName());
+                currentNode = dependentModule.getModuleNode(currentPath);
+
+                if (currentNode instanceof RpcDefinitionBuilder) {
+                    groupings = ((RpcDefinitionBuilder) currentNode).getGroupings();
+                } else if (currentNode instanceof DataNodeContainerBuilder) {
+                    groupings = ((DataNodeContainerBuilder) currentNode).getGroupings();
+                } else {
+                    groupings = Collections.emptySet();
+                }
+
+                result = findGrouping(groupings, groupingName);
+                if (result != null) {
+                    break;
+                }
+            }
+        }
+
+        if (result != null) {
+            return result;
+        }
+        throw new YangParseException(module.getName(), line,
+                "Referenced grouping '" + groupingName + "' not found.");
+    }
+
+    private GroupingBuilder findGrouping(Set<GroupingBuilder> groupings,
+            String name) {
+        for (GroupingBuilder grouping : groupings) {
+            if (grouping.getQName().getLocalName().equals(name)) {
+                return grouping;
+            }
+        }
+        return null;
+    }
+
     /**
      * Find original builder of node to refine and return copy of this builder.
      * <p>
@@ -948,11 +901,11 @@ public final class YangParserImpl implements YangModelParser {
      *         otherwise
      */
     private SchemaNodeBuilder getRefineNodeBuilderCopy(
-            final String groupingPath, final RefineHolder refine,
+            final GroupingBuilder targetGrouping, final RefineHolder refine,
             final Map<String, TreeMap<Date, ModuleBuilder>> modules,
             final ModuleBuilder module) {
         Builder result = null;
-        final Builder lookedUpBuilder = findRefineTargetBuilder(groupingPath,
+        final Builder lookedUpBuilder = findRefineTargetBuilder(targetGrouping,
                 refine, modules, module);
         if (lookedUpBuilder instanceof LeafSchemaNodeBuilder) {
             result = ParserUtils
@@ -999,28 +952,11 @@ public final class YangParserImpl implements YangModelParser {
      * @return Builder object of refine node if it is present in grouping, null
      *         otherwise
      */
-    private Builder findRefineTargetBuilder(final String groupingPath,
+    private Builder findRefineTargetBuilder(final GroupingBuilder builder,
             final RefineHolder refine,
             final Map<String, TreeMap<Date, ModuleBuilder>> modules,
             final ModuleBuilder module) {
         final String refineNodeName = refine.getName();
-        final SchemaPath path = ParserUtils.parseUsesPath(groupingPath);
-        final List<String> builderPath = new ArrayList<String>();
-        String prefix = null;
-        for (QName qname : path.getPath()) {
-            builderPath.add(qname.getLocalName());
-            prefix = qname.getPrefix();
-        }
-        if (prefix == null) {
-            prefix = module.getPrefix();
-        }
-
-        final ModuleBuilder dependentModule = findDependentModule(modules,
-                module, prefix, refine.getLine());
-        builderPath.add(0, dependentModule.getName());
-        final GroupingBuilder builder = dependentModule
-                .getGrouping(builderPath);
-
         Builder result = builder.getChildNode(refineNodeName);
         if (result == null) {
             Set<GroupingBuilder> grps = builder.getGroupings();
index d7394e62291db2ca98e6be896cc551a4b800e08e..1c01cd4a82b56cdbc016ed0e3f0c23eec5b833d8 100644 (file)
@@ -342,7 +342,6 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
                 if ("union".equals(typeName)) {
                     List<String> typePath = new ArrayList<String>(actualPath);
                     typePath.add(typeName);
-
                     SchemaPath p = createActualSchemaPath(typePath, namespace,
                             revision, yangModelPrefix);
                     UnionTypeBuilder unionBuilder = moduleBuilder.addUnionType(
@@ -357,12 +356,15 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
                             line);
                 } else {
                     type = parseTypeBody(typeName, typeBody, actualPath,
-                            namespace, revision, yangModelPrefix);
+                            namespace, revision, yangModelPrefix,
+                            moduleBuilder.getActualNode());
                     moduleBuilder.setType(type, actualPath);
                 }
             }
         } else {
-            type = parseUnknownTypeBody(typeQName, typeBody);
+            type = parseUnknownTypeBody(typeQName, typeBody, actualPath,
+                    namespace, revision, yangModelPrefix,
+                    moduleBuilder.getActualNode(), moduleBuilder);
             // mark parent node of this type statement as dirty
             moduleBuilder.addDirtyNode(actualPath);
             moduleBuilder.setType(type, actualPath);
@@ -408,15 +410,15 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
         GroupingBuilder builder = moduleBuilder.addGrouping(groupQName,
                 actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
-        updatePath("grouping");
         updatePath(groupName);
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
+                yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
     }
 
     @Override
     public void exitGrouping_stmt(YangParser.Grouping_stmtContext ctx) {
         String actContainer = actualPath.pop();
-        actContainer += "-" + actualPath.pop();
         logger.debug("exiting " + actContainer);
         moduleBuilder.exitNode();
     }
@@ -493,8 +495,11 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
         final String groupingPathStr = stringFromNode(ctx);
         UsesNodeBuilder builder = moduleBuilder.addUsesNode(groupingPathStr,
                 actualPath, ctx.getStart().getLine());
+
         moduleBuilder.enterNode(builder);
         updatePath(groupingPathStr);
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
+                yangModelPrefix));
     }
 
     @Override
index e95a162de763811d1d9ead81d32df43aeb599827..d38bc5e7adf22f74f6678e9614d38e2872a8099d 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.controller.yang.parser.util;
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import org.opendaylight.controller.yang.common.QName;
 import org.opendaylight.controller.yang.model.api.ModuleImport;
@@ -27,6 +28,9 @@ import org.opendaylight.controller.yang.model.api.type.IdentityrefTypeDefinition
 import org.opendaylight.controller.yang.model.api.type.InstanceIdentifierTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.IntegerTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.LeafrefTypeDefinition;
+import org.opendaylight.controller.yang.model.api.type.LengthConstraint;
+import org.opendaylight.controller.yang.model.api.type.PatternConstraint;
+import org.opendaylight.controller.yang.model.api.type.RangeConstraint;
 import org.opendaylight.controller.yang.model.api.type.StringTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.UnionTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.UnsignedIntegerTypeDefinition;
@@ -36,6 +40,7 @@ import org.opendaylight.controller.yang.model.util.BooleanType;
 import org.opendaylight.controller.yang.model.util.Decimal64;
 import org.opendaylight.controller.yang.model.util.EmptyType;
 import org.opendaylight.controller.yang.model.util.EnumerationType;
+import org.opendaylight.controller.yang.model.util.ExtendedType;
 import org.opendaylight.controller.yang.model.util.IdentityrefType;
 import org.opendaylight.controller.yang.model.util.InstanceIdentifier;
 import org.opendaylight.controller.yang.model.util.Int16;
@@ -75,7 +80,7 @@ public final class ParserUtils {
 
     /**
      * Get module import referenced by given prefix.
-     *
+     * 
      * @param builder
      *            module to search
      * @param prefix
@@ -96,7 +101,7 @@ public final class ParserUtils {
 
     /**
      * Parse uses path.
-     *
+     * 
      * @param usesPath
      *            as String
      * @return SchemaPath from given String
@@ -123,7 +128,7 @@ public final class ParserUtils {
 
     /**
      * Add all augment's child nodes to given target.
-     *
+     * 
      * @param augment
      * @param target
      */
@@ -132,54 +137,139 @@ public final class ParserUtils {
             final DataNodeContainerBuilder target) {
         for (DataSchemaNodeBuilder builder : augment.getChildNodes()) {
             builder.setAugmenting(true);
-            correctAugmentChildPath(augment, target.getPath());
+            correctAugmentChildPath(builder, target.getPath());
             target.addChildNode(builder);
         }
     }
 
     public static void fillAugmentTarget(
-            final AugmentationSchemaBuilder augment,
-            final ChoiceBuilder target) {
+            final AugmentationSchemaBuilder augment, final ChoiceBuilder target) {
         for (DataSchemaNodeBuilder builder : augment.getChildNodes()) {
             builder.setAugmenting(true);
-            correctAugmentChildPath(augment, target.getPath());
+            correctAugmentChildPath(builder, target.getPath());
             target.addChildNode(builder);
         }
     }
 
-    private static void correctAugmentChildPath(final DataNodeContainerBuilder node,
+    private static void correctAugmentChildPath(
+            final DataSchemaNodeBuilder childNode,
             final SchemaPath parentSchemaPath) {
-        for (DataSchemaNodeBuilder builder : node.getChildNodes()) {
-
-            // add correct path
-            List<QName> targetNodePath = new ArrayList<QName>(
-                    parentSchemaPath.getPath());
-            targetNodePath.add(builder.getQName());
-            builder.setPath(new SchemaPath(targetNodePath, true));
 
-            if (builder instanceof DataNodeContainerBuilder) {
-                DataNodeContainerBuilder cnb = (DataNodeContainerBuilder) builder;
-                correctAugmentChildPath(cnb, builder.getPath());
+        // set correct path
+        List<QName> targetNodePath = new ArrayList<QName>(
+                parentSchemaPath.getPath());
+        targetNodePath.add(childNode.getQName());
+        childNode.setPath(new SchemaPath(targetNodePath, true));
+
+        // set correct path for all child nodes
+        if (childNode instanceof DataNodeContainerBuilder) {
+            DataNodeContainerBuilder dataNodeContainer = (DataNodeContainerBuilder) childNode;
+            for (DataSchemaNodeBuilder child : dataNodeContainer
+                    .getChildNodes()) {
+                correctAugmentChildPath(child, childNode.getPath());
             }
+        }
 
-            // if child can contains type, correct path for this type too
-            if (builder instanceof TypeAwareBuilder) {
-                TypeAwareBuilder nodeBuilder = (TypeAwareBuilder) builder;
-                QName nodeBuilderQName = nodeBuilder.getQName();
-                TypeDefinition<?> nodeBuilderType = nodeBuilder.getType();
-                if (nodeBuilderType != null) {
-                    TypeDefinition<?> newType = createCorrectTypeDefinition(
-                            parentSchemaPath, nodeBuilderQName, nodeBuilderType);
-                    nodeBuilder.setType(newType);
-                } else {
-                    TypeDefinitionBuilder nodeBuilderTypedef = nodeBuilder
-                            .getTypedef();
-                    SchemaPath newSchemaPath = createNewSchemaPath(
-                            nodeBuilderTypedef.getPath(), nodeBuilderQName,
-                            nodeBuilderTypedef.getQName());
-                    nodeBuilderTypedef.setPath(newSchemaPath);
+        // if node can contains type, correct path for this type too
+        if (childNode instanceof TypeAwareBuilder) {
+            TypeAwareBuilder nodeBuilder = (TypeAwareBuilder) childNode;
+            correctTypeAwareNodePath(nodeBuilder, parentSchemaPath);
+        }
+    }
+
+    /**
+     * Repair schema path of node type.
+     * 
+     * @param node
+     *            node which contains type statement
+     * @param parentSchemaPath
+     *            schema path of parent node
+     */
+    private static void correctTypeAwareNodePath(
+            TypeAwareBuilder node, SchemaPath parentSchemaPath) {
+        final QName nodeBuilderQName = node.getQName();
+        final TypeDefinition<?> nodeType = node.getType();
+
+        Integer fd = null;
+        List<LengthConstraint> lengths = null;
+        List<PatternConstraint> patterns = null;
+        List<RangeConstraint> ranges = null;
+
+        if (nodeType != null) {
+            if (nodeType instanceof ExtendedType) {
+                ExtendedType et = (ExtendedType) nodeType;
+                if (nodeType
+                        .getQName()
+                        .getLocalName()
+                        .equals(nodeType.getBaseType().getQName()
+                                .getLocalName())) {
+                    fd = et.getFractionDigits();
+                    lengths = et.getLengths();
+                    patterns = et.getPatterns();
+                    ranges = et.getRanges();
+                    if (!hasConstraints(fd, lengths, patterns, ranges)) {
+                        return;
+                    }
                 }
             }
+            TypeDefinition<?> newType = createCorrectTypeDefinition(
+                    parentSchemaPath, nodeBuilderQName, nodeType);
+            node.setType(newType);
+        } else {
+            TypeDefinitionBuilder nodeBuilderTypedef = node.getTypedef();
+
+            fd = nodeBuilderTypedef.getFractionDigits();
+            lengths = nodeBuilderTypedef.getLengths();
+            patterns = nodeBuilderTypedef.getPatterns();
+            ranges = nodeBuilderTypedef.getRanges();
+
+            String tdbTypeName = nodeBuilderTypedef.getQName().getLocalName();
+            String baseTypeName = null;
+            if (nodeBuilderTypedef.getType() == null) {
+                baseTypeName = nodeBuilderTypedef.getTypedef().getQName()
+                        .getLocalName();
+            } else {
+                baseTypeName = nodeBuilderTypedef.getType().getQName()
+                        .getLocalName();
+            }
+            if (!(tdbTypeName.equals(baseTypeName))) {
+                return;
+            }
+
+            if (!hasConstraints(fd, lengths, patterns, ranges)) {
+                return;
+            }
+
+            SchemaPath newSchemaPath = createNewSchemaPath(
+                    nodeBuilderTypedef.getPath(), nodeBuilderQName,
+                    nodeBuilderTypedef.getQName());
+            nodeBuilderTypedef.setPath(newSchemaPath);
+        }
+    }
+
+    /**
+     * Check if there are some constraints.
+     * 
+     * @param fd
+     *            fraction digits
+     * @param lengths
+     *            length constraints
+     * @param patterns
+     *            pattern constraints
+     * @param ranges
+     *            range constraints
+     * @return true, if any of constraints are present, false otherwise
+     */
+    private static boolean hasConstraints(final Integer fd,
+            final List<LengthConstraint> lengths,
+            final List<PatternConstraint> patterns,
+            final List<RangeConstraint> ranges) {
+        if (fd == null && (lengths == null || lengths.isEmpty())
+                && (patterns == null || patterns.isEmpty())
+                && (ranges == null || ranges.isEmpty())) {
+            return false;
+        } else {
+            return true;
         }
     }
 
@@ -209,7 +299,8 @@ public final class ParserUtils {
                 DecimalTypeDefinition decimalType = (DecimalTypeDefinition) nodeType;
                 newSchemaPath = createNewSchemaPath(parentSchemaPath,
                         nodeQName, decimalType.getQName());
-                result = new Decimal64(newSchemaPath, decimalType.getFractionDigits());
+                result = new Decimal64(newSchemaPath,
+                        decimalType.getFractionDigits());
             } else if (nodeType instanceof EmptyTypeDefinition) {
                 newSchemaPath = createNewSchemaPath(parentSchemaPath,
                         nodeQName, nodeType.getQName());
@@ -253,11 +344,33 @@ public final class ParserUtils {
                 newSchemaPath = createNewSchemaPath(parentSchemaPath,
                         nodeQName, unionType.getQName());
                 return new UnionType(newSchemaPath, unionType.getTypes());
+            } else if (nodeType instanceof ExtendedType) {
+                ExtendedType extType = (ExtendedType) nodeType;
+                newSchemaPath = createNewSchemaPath(parentSchemaPath,
+                        nodeQName, extType.getQName());
+                result = createNewExtendedType(newSchemaPath, extType);
             }
         }
         return result;
     }
 
+    private static TypeDefinition<?> createNewExtendedType(
+            SchemaPath newSchemaPath, ExtendedType oldExtendedType) {
+        QName qname = oldExtendedType.getQName();
+        TypeDefinition<?> baseType = oldExtendedType.getBaseType();
+        String desc = oldExtendedType.getDescription();
+        String ref = oldExtendedType.getReference();
+        ExtendedType.Builder builder = new ExtendedType.Builder(qname,
+                baseType, desc, ref, newSchemaPath);
+        builder.status(oldExtendedType.getStatus());
+        builder.lengths(oldExtendedType.getLengths());
+        builder.patterns(oldExtendedType.getPatterns());
+        builder.ranges(oldExtendedType.getRanges());
+        builder.fractionDigits(oldExtendedType.getFractionDigits());
+        builder.unknownSchemaNodes(oldExtendedType.getUnknownSchemaNodes());
+        return builder.build();
+    }
+
     private static TypeDefinition<?> createNewStringType(SchemaPath schemaPath,
             QName nodeQName, StringTypeDefinition nodeType) {
         List<QName> path = schemaPath.getPath();
@@ -537,9 +650,9 @@ public final class ParserUtils {
      * <li>reference</li>
      * <li>config</li>
      * </ul>
-     *
+     * 
      * These parameters may be refined for any node.
-     *
+     * 
      * @param node
      *            node to refine
      * @param refine
@@ -794,7 +907,7 @@ public final class ParserUtils {
 
     public static UsesNodeBuilder copyUsesNodeBuilder(UsesNodeBuilder old) {
         final UsesNodeBuilder copy = new UsesNodeBuilderImpl(
-                old.getGroupingPathString(), old.getLine());
+                old.getGroupingName(), old.getLine());
         for (AugmentationSchemaBuilder augment : old.getAugmentations()) {
             copy.addAugment(augment);
         }
index 18e4c31ab93856826251748abde40e73e30bf33e..670c1d573c9b46de1df4f3085b39716a63695818 100644 (file)
@@ -23,14 +23,14 @@ public final class TypeConstraints {
     private final List<List<RangeConstraint>> ranges = new ArrayList<List<RangeConstraint>>();
     private final List<List<LengthConstraint>> lengths = new ArrayList<List<LengthConstraint>>();
     private final List<PatternConstraint> patterns = new ArrayList<PatternConstraint>();
-    private Integer fractionDigits;
+    private final List<Integer> fractionDigits = new ArrayList<Integer>();
 
     List<List<RangeConstraint>> getAllRanges() {
         return ranges;
     }
 
     public List<RangeConstraint> getRange() {
-        if(ranges.isEmpty()) {
+        if (ranges.isEmpty()) {
             return Collections.emptyList();
         }
 
@@ -108,7 +108,7 @@ public final class TypeConstraints {
     }
 
     public List<LengthConstraint> getLength() {
-        if(lengths.isEmpty()) {
+        if (lengths.isEmpty()) {
             return Collections.emptyList();
         }
 
@@ -190,13 +190,14 @@ public final class TypeConstraints {
     }
 
     public Integer getFractionDigits() {
-        return fractionDigits;
+        if (fractionDigits.isEmpty()) {
+            return null;
+        }
+        return fractionDigits.get(0);
     }
 
-    public void setFractionDigits(final Integer fractionDigits) {
-        if (this.fractionDigits == null) {
-            this.fractionDigits = fractionDigits;
-        }
+    public void addFractionDigits(final Integer fractionDigits) {
+        this.fractionDigits.add(fractionDigits);
     }
 
 }
index f58ee740cfe4a274840098716be91a430265e70d..1e55b2444919fd67f5f46dd2114e8610e3d9e07f 100644 (file)
@@ -76,13 +76,17 @@ import org.opendaylight.controller.yang.model.api.SchemaPath;
 import org.opendaylight.controller.yang.model.api.Status;
 import org.opendaylight.controller.yang.model.api.TypeDefinition;
 import org.opendaylight.controller.yang.model.api.UnknownSchemaNode;
+import org.opendaylight.controller.yang.model.api.type.BinaryTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition.Bit;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
+import org.opendaylight.controller.yang.model.api.type.IntegerTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.LengthConstraint;
 import org.opendaylight.controller.yang.model.api.type.PatternConstraint;
 import org.opendaylight.controller.yang.model.api.type.RangeConstraint;
+import org.opendaylight.controller.yang.model.api.type.StringTypeDefinition;
+import org.opendaylight.controller.yang.model.api.type.UnsignedIntegerTypeDefinition;
 import org.opendaylight.controller.yang.model.util.BaseConstraints;
 import org.opendaylight.controller.yang.model.util.BaseTypes;
 import org.opendaylight.controller.yang.model.util.BinaryType;
@@ -103,8 +107,12 @@ import org.opendaylight.controller.yang.model.util.Uint32;
 import org.opendaylight.controller.yang.model.util.Uint64;
 import org.opendaylight.controller.yang.model.util.Uint8;
 import org.opendaylight.controller.yang.model.util.UnknownType;
+import org.opendaylight.controller.yang.parser.builder.api.Builder;
 import org.opendaylight.controller.yang.parser.builder.api.SchemaNodeBuilder;
+import org.opendaylight.controller.yang.parser.builder.api.TypeDefinitionBuilder;
 import org.opendaylight.controller.yang.parser.builder.impl.ConstraintsBuilder;
+import org.opendaylight.controller.yang.parser.builder.impl.ModuleBuilder;
+import org.opendaylight.controller.yang.parser.builder.impl.UnionTypeBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -964,19 +972,48 @@ public final class YangModelBuilderUtil {
      * @return UnknownType object with constraints from parsed type body
      */
     public static TypeDefinition<?> parseUnknownTypeBody(QName typedefQName,
-            Type_body_stmtsContext ctx) {
+            Type_body_stmtsContext ctx, final List<String> actualPath,
+            final URI namespace, final Date revision, final String prefix,
+            Builder parent, ModuleBuilder moduleBuilder) {
+        String typeName = typedefQName.getLocalName();
+
         UnknownType.Builder unknownType = new UnknownType.Builder(typedefQName);
+
         if (ctx != null) {
             List<RangeConstraint> rangeStatements = getRangeConstraints(ctx);
             List<LengthConstraint> lengthStatements = getLengthConstraints(ctx);
             List<PatternConstraint> patternStatements = getPatternConstraint(ctx);
             Integer fractionDigits = getFractionDigits(ctx);
 
-            unknownType.rangeStatements(rangeStatements);
-            unknownType.lengthStatements(lengthStatements);
-            unknownType.patterns(patternStatements);
-            unknownType.fractionDigits(fractionDigits);
+            if (parent instanceof TypeDefinitionBuilder) {
+                TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
+                typedef.setRanges(rangeStatements);
+                typedef.setLengths(lengthStatements);
+                typedef.setPatterns(patternStatements);
+                typedef.setFractionDigits(fractionDigits);
+                return unknownType.build();
+            } else {
+                TypeDefinition<?> baseType = unknownType.build();
+                TypeDefinition<?> result = null;
+                QName qname = new QName(namespace, revision, prefix, typeName);
+                ExtendedType.Builder typeBuilder = null;
+
+                SchemaPath schemaPath = createTypeSchemaPath(actualPath,
+                        namespace, revision, prefix, typeName, false, false);
+                typeBuilder = new ExtendedType.Builder(qname, baseType, "", "",
+                        schemaPath);
+
+                typeBuilder.ranges(rangeStatements);
+                typeBuilder.lengths(lengthStatements);
+                typeBuilder.patterns(patternStatements);
+                typeBuilder.fractionDigits(fractionDigits);
+
+                result = typeBuilder.build();
+
+                return result;
+            }
         }
+
         return unknownType.build();
     }
 
@@ -1000,7 +1037,7 @@ public final class YangModelBuilderUtil {
     public static TypeDefinition<?> parseTypeBody(final String typeName,
             final Type_body_stmtsContext typeBody,
             final List<String> actualPath, final URI namespace,
-            final Date revision, final String prefix) {
+            final Date revision, final String prefix, Builder parent) {
         TypeDefinition<?> baseType = null;
 
         List<RangeConstraint> rangeStatements = getRangeConstraints(typeBody);
@@ -1010,40 +1047,56 @@ public final class YangModelBuilderUtil {
         List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(
                 typeBody, actualPath, namespace, revision, prefix);
 
+        TypeConstraints constraints = new TypeConstraints();
+        constraints.addFractionDigits(fractionDigits);
+        constraints.addLengths(lengthStatements);
+        constraints.addPatterns(patternStatements);
+        constraints.addRanges(rangeStatements);
+
         SchemaPath baseTypePathFinal = createTypeSchemaPath(actualPath,
                 namespace, revision, prefix, typeName, true, true);
-        SchemaPath baseTypePath = createTypeSchemaPath(actualPath,
-                namespace, revision, prefix, typeName, true, false);
+        SchemaPath baseTypePath = createTypeSchemaPath(actualPath, namespace,
+                revision, prefix, typeName, true, false);
 
         if ("decimal64".equals(typeName)) {
             if (rangeStatements.isEmpty()) {
                 return new Decimal64(baseTypePathFinal, fractionDigits);
             }
-            baseType = new Decimal64(baseTypePath, fractionDigits);
+            Decimal64 decimalType = new Decimal64(baseTypePath, fractionDigits);
+            constraints.addRanges(decimalType.getRangeStatements());
+            baseType = decimalType;
         } else if (typeName.startsWith("int")) {
+            IntegerTypeDefinition intType = null;
             if ("int8".equals(typeName)) {
-                baseType = new Int8(baseTypePath);
+                intType = new Int8(baseTypePath);
             } else if ("int16".equals(typeName)) {
-                baseType = new Int16(baseTypePath);
+                intType = new Int16(baseTypePath);
             } else if ("int32".equals(typeName)) {
-                baseType = new Int32(baseTypePath);
+                intType = new Int32(baseTypePath);
             } else if ("int64".equals(typeName)) {
-                baseType = new Int64(baseTypePath);
+                intType = new Int64(baseTypePath);
             }
+            constraints.addRanges(intType.getRangeStatements());
+            baseType = intType;
         } else if (typeName.startsWith("uint")) {
+            UnsignedIntegerTypeDefinition uintType = null;
             if ("uint8".equals(typeName)) {
-                baseType = new Uint8(baseTypePath);
+                uintType = new Uint8(baseTypePath);
             } else if ("uint16".equals(typeName)) {
-                baseType = new Uint16(baseTypePath);
+                uintType = new Uint16(baseTypePath);
             } else if ("uint32".equals(typeName)) {
-                baseType = new Uint32(baseTypePath);
+                uintType = new Uint32(baseTypePath);
             } else if ("uint64".equals(typeName)) {
-                baseType = new Uint64(baseTypePath);
+                uintType = new Uint64(baseTypePath);
             }
+            constraints.addRanges(uintType.getRangeStatements());
+            baseType = uintType;
         } else if ("enumeration".equals(typeName)) {
             return new EnumerationType(baseTypePathFinal, enumConstants);
         } else if ("string".equals(typeName)) {
-            baseType = new StringType(baseTypePath);
+            StringTypeDefinition stringType = new StringType(baseTypePath);
+            constraints.addLengths(stringType.getLengthStatements());
+            baseType = stringType;
         } else if ("bits".equals(typeName)) {
             return new BitsType(baseTypePathFinal, getBits(typeBody,
                     actualPath, namespace, revision, prefix));
@@ -1054,13 +1107,25 @@ public final class YangModelBuilderUtil {
                     absolute);
             return new Leafref(baseTypePathFinal, xpath);
         } else if ("binary".equals(typeName)) {
-            baseType = new BinaryType(baseTypePath);
+            BinaryTypeDefinition binaryType = new BinaryType(baseTypePath);
+            constraints.addLengths(binaryType.getLengthConstraints());
+            baseType = binaryType;
         } else if ("instance-identifier".equals(typeName)) {
             boolean requireInstance = isRequireInstance(typeBody);
             baseType = new InstanceIdentifier(baseTypePath, null,
                     requireInstance);
         }
 
+        if (parent instanceof TypeDefinitionBuilder
+                && !(parent instanceof UnionTypeBuilder)) {
+            TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
+            typedef.setRanges(constraints.getRange());
+            typedef.setLengths(constraints.getLength());
+            typedef.setPatterns(constraints.getPatterns());
+            typedef.setFractionDigits(constraints.getFractionDigits());
+            return baseType;
+        }
+
         TypeDefinition<?> result = null;
         QName qname = new QName(namespace, revision, prefix, typeName);
         ExtendedType.Builder typeBuilder = null;
@@ -1070,10 +1135,10 @@ public final class YangModelBuilderUtil {
         typeBuilder = new ExtendedType.Builder(qname, baseType, "", "",
                 schemaPath);
 
-        typeBuilder.ranges(rangeStatements);
-        typeBuilder.lengths(lengthStatements);
-        typeBuilder.patterns(patternStatements);
-        typeBuilder.fractionDigits(fractionDigits);
+        typeBuilder.ranges(constraints.getRange());
+        typeBuilder.lengths(constraints.getLength());
+        typeBuilder.patterns(constraints.getPatterns());
+        typeBuilder.fractionDigits(constraints.getFractionDigits());
 
         result = typeBuilder.build();
         return result;
index d14c54219e0fd5e1c1d9f3cdae3b0512f8dd654c..26c2c61b98a783aae48517b6cb5c259db85c8bb0 100644 (file)
@@ -49,13 +49,9 @@ final class TestUtils {
         return parser.parseYangModels(testFiles);
     }
 
-    public static Set<Module> loadModules(String... pathToYangFile) throws IOException {
-        YangModelParser parser = new YangParserImpl();
-        List<InputStream> input = new ArrayList<InputStream>();
-        for(String path : pathToYangFile) {
-            input.add(TestUtils.class.getResourceAsStream(path));
-        }
-        Set<Module> modules = new HashSet<Module>(
+    public static Set<Module> loadModules(List<InputStream> input) throws IOException {
+        final YangModelParser parser = new YangParserImpl();
+        final Set<Module> modules = new HashSet<Module>(
                 parser.parseYangModelsFromStreams(input));
         for(InputStream stream : input) {
             stream.close();
@@ -63,11 +59,11 @@ final class TestUtils {
         return modules;
     }
 
-    public static Module loadModule(String pathToYangFile) throws IOException {
-        YangModelParser parser = new YangParserImpl();
-        InputStream stream = TestUtils.class.getResourceAsStream(pathToYangFile);
-        List<InputStream> input = Collections.singletonList(stream);
-        Set<Module> modules = new HashSet<Module>(
+    public static Module loadModule(final InputStream stream) throws
+            IOException {
+        final YangModelParser parser = new YangParserImpl();
+        final List<InputStream> input = Collections.singletonList(stream);
+        final Set<Module> modules = new HashSet<Module>(
                 parser.parseYangModelsFromStreams(input));
         stream.close();
         return modules.iterator().next();
index 461cc4b5c28522d675851bb417563f2baaa91830..2c910ce3f69affe70d54adce8222a9f82ee4aeac 100644 (file)
@@ -26,6 +26,7 @@ import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition.Bit;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
 import org.opendaylight.controller.yang.model.api.type.LengthConstraint;
 import org.opendaylight.controller.yang.model.api.type.PatternConstraint;
+import org.opendaylight.controller.yang.model.api.type.StringTypeDefinition;
 import org.opendaylight.controller.yang.model.util.BitsType;
 import org.opendaylight.controller.yang.model.util.EnumerationType;
 import org.opendaylight.controller.yang.model.util.ExtendedType;
@@ -38,7 +39,8 @@ public class TypesResolutionTest {
 
     @Before
     public void init() throws FileNotFoundException {
-        testedModules = TestUtils.loadModules("src/test/resources/types");
+        testedModules = TestUtils.loadModules(getClass().getResource
+                ("/types").getPath());
     }
 
     @Test
@@ -122,16 +124,19 @@ public class TypesResolutionTest {
         List<TypeDefinition<?>> unionTypes = baseType.getTypes();
 
         ExtendedType ipv4 = (ExtendedType) unionTypes.get(0);
-        ExtendedType ipv4Base = (ExtendedType) ipv4.getBaseType();
+        assertTrue(ipv4.getBaseType() instanceof StringTypeDefinition);
         String expectedPattern = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}"
                 + "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
                 + "(%[\\p{N}\\p{L}]+)?";
-        assertEquals(expectedPattern, ipv4Base.getPatterns().get(0)
+        assertEquals(expectedPattern, ipv4.getPatterns().get(0)
                 .getRegularExpression());
 
+        TypeDefinition<?> ipv4Address = TestUtils.findTypedef(typedefs, "ipv4-address");
+        assertEquals(ipv4Address, ipv4);
+
         ExtendedType ipv6 = (ExtendedType) unionTypes.get(1);
-        ExtendedType ipv6Base = (ExtendedType) ipv6.getBaseType();
-        List<PatternConstraint> ipv6Patterns = ipv6Base.getPatterns();
+        assertTrue(ipv6.getBaseType() instanceof StringTypeDefinition);
+        List<PatternConstraint> ipv6Patterns = ipv6.getPatterns();
         expectedPattern = "((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}"
                 + "((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|"
                 + "(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}"
@@ -140,6 +145,9 @@ public class TypesResolutionTest {
         assertEquals(expectedPattern, ipv6Patterns.get(0)
                 .getRegularExpression());
 
+        TypeDefinition<?> ipv6Address = TestUtils.findTypedef(typedefs, "ipv6-address");
+        assertEquals(ipv6Address, ipv6);
+
         expectedPattern = "(([^:]+:){6}(([^:]+:[^:]+)|(.*\\..*)))|"
                 + "((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)" + "(%.+)?";
         assertEquals(expectedPattern, ipv6Patterns.get(1)
@@ -150,18 +158,18 @@ public class TypesResolutionTest {
     public void testDomainName() {
         Module tested = TestUtils.findModule(testedModules, "ietf-inet-types");
         Set<TypeDefinition<?>> typedefs = tested.getTypeDefinitions();
-        TypeDefinition<?> type = TestUtils.findTypedef(typedefs, "domain-name");
-        ExtendedType baseType = (ExtendedType) type.getBaseType();
-        List<PatternConstraint> patterns = baseType.getPatterns();
+        ExtendedType type = (ExtendedType)TestUtils.findTypedef(typedefs, "domain-name");
+        assertTrue(type.getBaseType() instanceof StringTypeDefinition);
+        List<PatternConstraint> patterns = type.getPatterns();
         assertEquals(1, patterns.size());
         String expectedPattern = "((([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.)*"
                 + "([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.?)"
                 + "|\\.";
         assertEquals(expectedPattern, patterns.get(0).getRegularExpression());
 
-        List<LengthConstraint> lengths = baseType.getLengths();
+        List<LengthConstraint> lengths = type.getLengths();
         assertEquals(1, lengths.size());
-        LengthConstraint length = baseType.getLengths().get(0);
+        LengthConstraint length = type.getLengths().get(0);
         assertEquals(1L, length.getMin());
         assertEquals(253L, length.getMax());
     }
@@ -173,7 +181,8 @@ public class TypesResolutionTest {
         LeafSchemaNode leaf = (LeafSchemaNode) tested
                 .getDataChildByName("inst-id-leaf1");
         ExtendedType leafType = (ExtendedType) leaf.getType();
-        InstanceIdentifier leafTypeBase = (InstanceIdentifier)leafType.getBaseType();
+        InstanceIdentifier leafTypeBase = (InstanceIdentifier) leafType
+                .getBaseType();
         assertFalse(leafTypeBase.requireInstance());
     }
 
@@ -300,6 +309,11 @@ public class TypesResolutionTest {
         ExtendedType testedType = (ExtendedType) TestUtils.findTypedef(
                 typedefs, "object-identifier-128");
 
+        List<PatternConstraint> patterns = testedType.getPatterns();
+        assertEquals(1, patterns.size());
+        PatternConstraint pattern = patterns.get(0);
+        assertEquals("\\d*(\\.\\d*){1,127}", pattern.getRegularExpression());
+
         QName testedTypeQName = testedType.getQName();
         assertEquals(URI.create("urn:ietf:params:xml:ns:yang:ietf-yang-types"),
                 testedTypeQName.getNamespace());
@@ -309,15 +323,13 @@ public class TypesResolutionTest {
         assertEquals("object-identifier-128", testedTypeQName.getLocalName());
 
         ExtendedType testedTypeBase = (ExtendedType) testedType.getBaseType();
+        patterns = testedTypeBase.getPatterns();
+        assertEquals(1, patterns.size());
 
-        List<PatternConstraint> patterns = testedTypeBase.getPatterns();
-        assertEquals(2, patterns.size());
-        PatternConstraint pattern1 = patterns.get(0);
-        assertEquals("\\d*(\\.\\d*){1,127}", pattern1.getRegularExpression());
-        PatternConstraint pattern2 = patterns.get(1);
+        pattern = patterns.get(0);
         assertEquals(
                 "(([0-1](\\.[1-3]?[0-9]))|(2\\.(0|([1-9]\\d*))))(\\.(0|([1-9]\\d*)))*",
-                pattern2.getRegularExpression());
+                pattern.getRegularExpression());
 
         QName testedTypeBaseQName = testedTypeBase.getQName();
         assertEquals(URI.create("urn:ietf:params:xml:ns:yang:ietf-yang-types"),
index be44c6ff98f991df55acfaa1188eb5f10559fbb6..35bfb1bebf449290cd97e58eb1af567bc637b35f 100644 (file)
@@ -9,7 +9,11 @@ package org.opendaylight.controller.yang.parser.impl;
 
 import static org.junit.Assert.*;
 
+import java.io.FileInputStream;
 import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
 
 import org.junit.Test;
 import org.opendaylight.controller.yang.parser.util.YangParseException;
@@ -20,8 +24,11 @@ public class YangParserNegativeTest {
     @Test
     public void testInvalidImport() throws IOException {
         try {
-            TestUtils.loadModule("/negative-scenario/testfile1.yang");
-            fail("ValidationException should by thrown");
+            try (InputStream stream = new FileInputStream(getClass().getResource
+                    ("/negative-scenario/testfile1.yang").getPath())) {
+                TestUtils.loadModule(stream);
+                fail("ValidationException should by thrown");
+            }
         } catch(YangValidationException e) {
             assertTrue(e.getMessage().contains("Not existing module imported"));
         }
@@ -30,8 +37,11 @@ public class YangParserNegativeTest {
     @Test
     public void testTypeNotFound() throws IOException {
         try {
-            TestUtils.loadModule("/negative-scenario/testfile2.yang");
-            fail("YangParseException should by thrown");
+            try (InputStream stream = new FileInputStream(getClass().getResource
+                    ("/negative-scenario/testfile2.yang").getPath())) {
+                TestUtils.loadModule(stream);
+                fail("YangParseException should by thrown");
+            }
         } catch(YangParseException e) {
             assertTrue(e.getMessage().contains("Error in module 'test2' on line 24: Referenced type 'int-ext' not found."));
         }
@@ -40,8 +50,19 @@ public class YangParserNegativeTest {
     @Test
     public void testInvalidAugmentTarget() throws IOException {
         try {
-            TestUtils.loadModules("/negative-scenario/testfile0.yang", "/negative-scenario/testfile3.yang");
-            fail("YangParseException should by thrown");
+            final List<InputStream> streams = new ArrayList<>(2);
+            try (InputStream testFile0 = new FileInputStream(getClass().getResource
+                    ("/negative-scenario/testfile0.yang").getPath())) {
+                streams.add(testFile0);
+                try (InputStream testFile3 = new FileInputStream(getClass().getResource
+                        ("/negative-scenario/testfile3.yang").getPath())) {
+                    streams.add(testFile3);
+                    assertEquals("Expected loaded files count is 2", 2,
+                            streams.size());
+                    TestUtils.loadModules(streams);
+                    fail("YangParseException should by thrown");
+                }
+            }
         } catch(YangParseException e) {
             assertTrue(e.getMessage().contains("Failed to resolve augments in module 'test3'."));
         }
@@ -50,8 +71,11 @@ public class YangParserNegativeTest {
     @Test
     public void testInvalidRefine() throws IOException {
         try {
-            TestUtils.loadModule("/negative-scenario/testfile4.yang");
-            fail("YangParseException should by thrown");
+            try (InputStream stream = new FileInputStream(getClass().getResource
+                    ("/negative-scenario/testfile4.yang").getPath())) {
+                TestUtils.loadModule(stream);
+                fail("YangParseException should by thrown");
+            }
         } catch(YangParseException e) {
             assertTrue(e.getMessage().contains("Can not refine 'presence' for 'node'."));
         }
index 23bb4a41d2f25fc16c501f06ed9d65b316206d53..ba31e51922a62c2d3fc6b352a2e3aa8110d3d216 100644 (file)
@@ -16,7 +16,6 @@ import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -64,13 +63,14 @@ import org.opendaylight.controller.yang.model.util.Uint32;
 import org.opendaylight.controller.yang.model.util.UnionType;
 
 public class YangParserTest {
-    private final DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
+    private final DateFormat simpleDateFormat = new SimpleDateFormat(
+            "yyyy-MM-dd");
 
     private Set<Module> modules;
 
     @Before
     public void init() throws FileNotFoundException {
-        modules = TestUtils.loadModules("src/test/resources/model");
+        modules = TestUtils.loadModules(getClass().getResource("/model").getPath());
         assertEquals(3, modules.size());
     }
 
@@ -209,7 +209,7 @@ public class YangParserTest {
         // leaf if-name
         LeafSchemaNode ifName = (LeafSchemaNode) test
                 .getDataChildByName("if-name");
-        Leafref ifNameType = (Leafref)ifName.getType();
+        Leafref ifNameType = (Leafref) ifName.getType();
         QName qname = ifNameType.getQName();
 
         URI baseYangTypeNS = URI.create("urn:ietf:params:xml:ns:yang:1");
@@ -219,9 +219,8 @@ public class YangParserTest {
         assertEquals("leafref", qname.getLocalName());
 
         // leaf name
-        LeafSchemaNode name = (LeafSchemaNode) test
-                .getDataChildByName("name");
-        StringType nameType = (StringType)name.getType();
+        LeafSchemaNode name = (LeafSchemaNode) test.getDataChildByName("name");
+        StringType nameType = (StringType) name.getType();
         QName nameQName = nameType.getQName();
 
         assertEquals(baseYangTypeNS, nameQName.getNamespace());
@@ -232,7 +231,7 @@ public class YangParserTest {
         // leaf count
         LeafSchemaNode count = (LeafSchemaNode) test
                 .getDataChildByName("count");
-        ExtendedType countType = (ExtendedType)count.getType();
+        ExtendedType countType = (ExtendedType) count.getType();
         QName countTypeQName = countType.getQName();
 
         URI expectedNS = URI.create("urn:simple.types.data.demo");
@@ -242,7 +241,7 @@ public class YangParserTest {
         assertEquals("t2", countTypeQName.getPrefix());
         assertEquals("int8", countTypeQName.getLocalName());
 
-        Int8 countTypeBase = (Int8)countType.getBaseType();
+        Int8 countTypeBase = (Int8) countType.getBaseType();
         QName countTypeBaseQName = countTypeBase.getQName();
 
         assertEquals(baseYangTypeNS, countTypeBaseQName.getNamespace());
@@ -341,17 +340,29 @@ public class YangParserTest {
     }
 
     @Test
-    public void testTypedefRangesResolving() {
+    public void testTypedefRangesResolving() throws ParseException {
         Module testModule = TestUtils.findModule(modules, "types1");
 
         LeafSchemaNode testleaf = (LeafSchemaNode) testModule
                 .getDataChildByName("testleaf");
         ExtendedType leafType = (ExtendedType) testleaf.getType();
-        assertEquals("my-type1", leafType.getQName().getLocalName());
-        assertEquals("t2", leafType.getQName().getPrefix());
+        QName leafTypeQName = leafType.getQName();
+        assertEquals("my-type1", leafTypeQName.getLocalName());
+        assertEquals("t1", leafTypeQName.getPrefix());
+        assertEquals(URI.create("urn:simple.container.demo"),
+                leafTypeQName.getNamespace());
+        Date expectedDate = simpleDateFormat.parse("2013-02-27");
+        assertEquals(expectedDate, leafTypeQName.getRevision());
+        assertEquals(1, leafType.getRanges().size());
+
         ExtendedType baseType = (ExtendedType) leafType.getBaseType();
-        assertEquals("my-base-int32-type", baseType.getQName().getLocalName());
-        assertEquals("t2", baseType.getQName().getPrefix());
+        QName baseTypeQName = baseType.getQName();
+        assertEquals("my-type1", baseTypeQName.getLocalName());
+        assertEquals("t2", baseTypeQName.getPrefix());
+        assertEquals(URI.create("urn:simple.types.data.demo"),
+                baseTypeQName.getNamespace());
+        assertEquals(expectedDate, baseTypeQName.getRevision());
+        assertEquals(2, baseType.getRanges().size());
 
         List<RangeConstraint> ranges = leafType.getRanges();
         assertEquals(1, ranges.size());
@@ -371,28 +382,21 @@ public class YangParserTest {
         assertEquals("my-string-type-ext", testleafTypeQName.getLocalName());
         assertEquals("t2", testleafTypeQName.getPrefix());
 
-        Set<String> expectedRegex = new HashSet<String>();
-        expectedRegex.add("[a-k]*");
-        expectedRegex.add("[b-u]*");
-        expectedRegex.add("[e-z]*");
-
-        Set<String> actualRegex = new HashSet<String>();
         List<PatternConstraint> patterns = testleafType.getPatterns();
-        assertEquals(3, patterns.size());
-        for (PatternConstraint pc : patterns) {
-            actualRegex.add(pc.getRegularExpression());
-        }
-        assertEquals(expectedRegex, actualRegex);
+        assertEquals(1, patterns.size());
+        PatternConstraint pattern = patterns.iterator().next();
+        assertEquals("[e-z]*", pattern.getRegularExpression());
 
-        TypeDefinition<?> baseType = testleafType.getBaseType();
+        ExtendedType baseType = (ExtendedType) testleafType.getBaseType();
         assertEquals("my-string-type2", baseType.getQName().getLocalName());
 
-        List<LengthConstraint> lengths = testleafType.getLengths();
-        assertEquals(1, lengths.size());
+        patterns = baseType.getPatterns();
+        assertEquals(1, patterns.size());
+        pattern = patterns.iterator().next();
+        assertEquals("[b-u]*", pattern.getRegularExpression());
 
-        LengthConstraint length = lengths.get(0);
-        assertEquals(5L, length.getMin());
-        assertEquals(10L, length.getMax());
+        List<LengthConstraint> lengths = testleafType.getLengths();
+        assertTrue(lengths.isEmpty());
     }
 
     @Test
@@ -424,14 +428,14 @@ public class YangParserTest {
         ExtendedType baseType = (ExtendedType) testleafType.getBaseType();
         assertEquals("my-base-int32-type", baseType.getQName().getLocalName());
 
-        ExtendedType int32Type = (ExtendedType) baseType.getBaseType();
-        Int32 int32TypeBase = (Int32)int32Type.getBaseType();
-        QName qname = int32TypeBase.getQName();
-        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"), qname.getNamespace());
+        Int32 int32Type = (Int32) baseType.getBaseType();
+        QName qname = int32Type.getQName();
+        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"),
+                qname.getNamespace());
         assertNull(qname.getRevision());
         assertEquals("", qname.getPrefix());
         assertEquals("int32", qname.getLocalName());
-        List<RangeConstraint> ranges = int32Type.getRanges();
+        List<RangeConstraint> ranges = baseType.getRanges();
         assertEquals(1, ranges.size());
         RangeConstraint range = ranges.get(0);
         assertEquals(2L, range.getMin());
@@ -447,8 +451,12 @@ public class YangParserTest {
         ExtendedType type = (ExtendedType) testleaf.getType();
         assertEquals(4, (int) type.getFractionDigits());
 
-        Decimal64 baseType = (Decimal64) type.getBaseType();
-        assertEquals(6, (int) baseType.getFractionDigits());
+        ExtendedType typeBase = (ExtendedType) type.getBaseType();
+        assertEquals("my-decimal-type", typeBase.getQName().getLocalName());
+        assertNull(typeBase.getFractionDigits());
+
+        Decimal64 decimal = (Decimal64) typeBase.getBaseType();
+        assertEquals(6, (int) decimal.getFractionDigits());
     }
 
     @Test
@@ -840,14 +848,20 @@ public class YangParserTest {
         Leafref ifcIdType = (Leafref) ifcId.getType();
         SchemaPath ifcIdTypeSchemaPath = ifcIdType.getPath();
         List<QName> ifcIdTypePath = ifcIdTypeSchemaPath.getPath();
-        QName q0 = new QName(new URI("urn:simple.types.data.demo"),
-                simpleDateFormat.parse("2013-02-27"), "data", "interfaces");
-        QName q1 = new QName(new URI("urn:simple.types.data.demo"),
-                simpleDateFormat.parse("2013-02-27"), "data", "ifEntry");
-        QName q2 = new QName(new URI("urn:simple.container.demo.test"),
-                simpleDateFormat.parse("2013-02-27"), "data", "augment-holder");
-        QName q3 = new QName(new URI("urn:simple.container.demo"),
-                simpleDateFormat.parse("2013-02-27"), "data", "interface-id");
+        
+        URI types1URI = URI.create("urn:simple.container.demo");
+        URI types2URI = URI.create("urn:simple.types.data.demo");
+        URI types3URI = URI.create("urn:simple.container.demo.test");
+        Date expectedDate = simpleDateFormat.parse("2013-02-27");
+        
+        QName q0 = new QName(types2URI,
+                expectedDate, "data", "interfaces");
+        QName q1 = new QName(types2URI,
+                expectedDate, "data", "ifEntry");
+        QName q2 = new QName(types3URI,
+                expectedDate, "data", "augment-holder");
+        QName q3 = new QName(types1URI,
+                expectedDate, "data", "interface-id");
         assertEquals(q0, ifcIdTypePath.get(0));
         assertEquals(q1, ifcIdTypePath.get(1));
         assertEquals(q2, ifcIdTypePath.get(2));
@@ -861,9 +875,18 @@ public class YangParserTest {
         assertEquals(q0, higherLayerTypePath.get(0));
         assertEquals(q1, higherLayerTypePath.get(1));
         assertEquals(q2, higherLayerTypePath.get(2));
-        q3 = new QName(new URI("urn:simple.container.demo"),
-                simpleDateFormat.parse("2013-02-27"), "data", "higher-layer-if");
+        q3 = new QName(types1URI,
+                expectedDate, "data", "higher-layer-if");
         assertEquals(q3, higherLayerTypePath.get(3));
+        
+        LeafSchemaNode myType = (LeafSchemaNode) augment
+                .getDataChildByName("my-type");
+        ExtendedType leafType = (ExtendedType)myType.getType();
+        
+        testModule = TestUtils.findModule(modules, "types2");
+        TypeDefinition<?> typedef = TestUtils.findTypedef(testModule.getTypeDefinitions(), "my-type1");
+        
+        assertEquals(typedef, leafType);
     }
 
     @Test
@@ -872,7 +895,8 @@ public class YangParserTest {
         Set<TypeDefinition<?>> types = test.getTypeDefinitions();
 
         // my-base-int32-type
-        ExtendedType int32Typedef = (ExtendedType)TestUtils.findTypedef(types, "my-base-int32-type");
+        ExtendedType int32Typedef = (ExtendedType) TestUtils.findTypedef(types,
+                "my-base-int32-type");
         QName int32TypedefQName = int32Typedef.getQName();
 
         URI expectedNS = URI.create("urn:simple.types.data.demo");
@@ -888,24 +912,10 @@ public class YangParserTest {
         assertEquals(int32TypedefQName, typePath.get(0));
 
         // my-base-int32-type/int32
-        ExtendedType int32Ext = (ExtendedType)int32Typedef.getBaseType();
-        QName int32ExtQName = int32Ext.getQName();
-
-        assertEquals(expectedNS, int32ExtQName.getNamespace());
-        assertEquals(expectedDate, int32ExtQName.getRevision());
-        assertEquals("t2", int32ExtQName.getPrefix());
-        assertEquals("int32", int32ExtQName.getLocalName());
-
-        SchemaPath int32ExtSchemaPath = int32Ext.getPath();
-        List<QName> int32ExtPath = int32ExtSchemaPath.getPath();
-        assertEquals(2, int32ExtPath.size());
-        assertEquals(int32TypedefQName, int32ExtPath.get(0));
-        assertEquals(int32ExtQName, int32ExtPath.get(1));
-
-        // my-base-int32-type/int32/int32
-        Int32 int32 = (Int32)int32Ext.getBaseType();
+        Int32 int32 = (Int32) int32Typedef.getBaseType();
         QName int32QName = int32.getQName();
-        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"), int32QName.getNamespace());
+        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"),
+                int32QName.getNamespace());
         assertNull(int32QName.getRevision());
         assertEquals("", int32QName.getPrefix());
         assertEquals("int32", int32QName.getLocalName());
@@ -914,7 +924,6 @@ public class YangParserTest {
         List<QName> int32Path = int32SchemaPath.getPath();
         assertEquals(3, int32Path.size());
         assertEquals(int32TypedefQName, int32Path.get(0));
-        assertEquals(int32ExtQName, int32Path.get(1));
         assertEquals(int32QName, int32Path.get(2));
     }
 
@@ -924,7 +933,8 @@ public class YangParserTest {
         Set<TypeDefinition<?>> types = test.getTypeDefinitions();
 
         // my-base-int32-type
-        ExtendedType myDecType = (ExtendedType)TestUtils.findTypedef(types, "my-decimal-type");
+        ExtendedType myDecType = (ExtendedType) TestUtils.findTypedef(types,
+                "my-decimal-type");
         QName myDecTypeQName = myDecType.getQName();
 
         URI expectedNS = URI.create("urn:simple.types.data.demo");
@@ -940,10 +950,11 @@ public class YangParserTest {
         assertEquals(myDecTypeQName, typePath.get(0));
 
         // my-base-int32-type/int32
-        Decimal64 dec64 = (Decimal64)myDecType.getBaseType();
+        Decimal64 dec64 = (Decimal64) myDecType.getBaseType();
         QName dec64QName = dec64.getQName();
 
-        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"), dec64QName.getNamespace());
+        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"),
+                dec64QName.getNamespace());
         assertNull(dec64QName.getRevision());
         assertEquals("", dec64QName.getPrefix());
         assertEquals("decimal64", dec64QName.getLocalName());
index 4ec69c18b229bb7bc4055bf7140b526c0378da2f..3dbfa780a3527641933e1dae3e77c237822bbe47 100644 (file)
@@ -123,6 +123,9 @@ module types1 {
                 path "/if:interfaces/if:interface/if:higher-layer-if";
             }
         }
+        leaf my-type {
+            type data:my-type1;
+        }
     }
     
     container mycont {
index e79e70028b6cdacdbd8ffc0130ad6a9669ab137c..4e15f8d47c632c43e11742a6d7a943162a4eac71 100644 (file)
@@ -6,7 +6,7 @@
                <artifactId>yang-prototype</artifactId>
                <version>0.5-SNAPSHOT</version>
        </parent>
-       <version>0.5.1-SNAPSHOT</version>
+       <version>0.5.2-SNAPSHOT</version>
        <artifactId>yang</artifactId>
        <packaging>pom</packaging>
 
index f7df24f53f9a69ecf3e709de1bdf608fe4eddf99..6362eb9accfab637b27f998f4c37674fab548399 100644 (file)
@@ -3,7 +3,7 @@
   <parent>\r
     <groupId>org.opendaylight.controller</groupId>\r
     <artifactId>yang</artifactId>\r
-    <version>0.5.1-SNAPSHOT</version>\r
+    <version>0.5.2-SNAPSHOT</version>\r
   </parent>\r
   <artifactId>yang-binding</artifactId>\r
 </project>
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/yang/yang-binding/src/main/java/org/opendaylight/controller/yang/binding/BaseIdentity.java b/opendaylight/sal/yang-prototype/yang/yang-binding/src/main/java/org/opendaylight/controller/yang/binding/BaseIdentity.java
new file mode 100644 (file)
index 0000000..004287a
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * 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.yang.binding;
+
+public abstract class BaseIdentity {
+    
+    protected BaseIdentity() {
+    }
+
+}
index 987b9b11a18a11ffb901a2adff7e8e764e8ebc3a..7f5538692567b6d2ef44383fd78567f4bed3d742 100644 (file)
@@ -3,7 +3,7 @@
   <parent>\r
     <groupId>org.opendaylight.controller</groupId>\r
     <artifactId>yang</artifactId>\r
-    <version>0.5.1-SNAPSHOT</version>\r
+    <version>0.5.2-SNAPSHOT</version>\r
   </parent>\r
   <artifactId>yang-common</artifactId>\r
   <dependencies>\r
index cdf867489388ba4d087d1345649e59bc112c1500..004a2a49523a5ad7dd643b9b48173dc777337e19 100644 (file)
@@ -36,7 +36,7 @@ import org.slf4j.LoggerFactory;
  * \r
  * \r
  */\r
-public class QName {\r
+public final class QName {\r
     protected static final Logger logger = LoggerFactory\r
         .getLogger(QName.class);\r
 \r
index 749c9c66f439eabddf25c5da6ad3798c02003132..02562172e89099ae8fbf8f80851f2f02708da2ae 100644 (file)
@@ -3,7 +3,7 @@
   <parent>\r
     <groupId>org.opendaylight.controller</groupId>\r
     <artifactId>yang</artifactId>\r
-    <version>0.5.1-SNAPSHOT</version>\r
+    <version>0.5.2-SNAPSHOT</version>\r
   </parent>\r
   <artifactId>yang-data-api</artifactId>\r
   \r
index 15b391f5b896146565a785fa8e459435dfb43be4..bce9e9134698189cec00228ac5a4cae4e05a7dc6 100644 (file)
@@ -3,7 +3,7 @@
   <parent>\r
     <groupId>org.opendaylight.controller</groupId>\r
     <artifactId>yang</artifactId>\r
-    <version>0.5.1-SNAPSHOT</version>\r
+    <version>0.5.2-SNAPSHOT</version>\r
   </parent>\r
   <artifactId>yang-data-util</artifactId>\r
   <dependencies>\r
index 3eabd7ff9f4aec09ddb4964f7b8fce95187347e3..fc601e32b442e5b9ae043815d513a22cad81078a 100644 (file)
@@ -3,7 +3,7 @@
   <parent>\r
     <groupId>org.opendaylight.controller</groupId>\r
     <artifactId>yang</artifactId>\r
-    <version>0.5.1-SNAPSHOT</version>\r
+    <version>0.5.2-SNAPSHOT</version>\r
   </parent>\r
   <artifactId>yang-model-api</artifactId>\r
   <dependencies>\r
index 3390837be919feae17cd0484802402b7fda0f0e9..d95b23957b15a7f2e4d181aff7144545aba5d0d6 100644 (file)
@@ -3,7 +3,7 @@
   <parent>\r
     <groupId>org.opendaylight.controller</groupId>\r
     <artifactId>yang</artifactId>\r
-    <version>0.5.1-SNAPSHOT</version>\r
+    <version>0.5.2-SNAPSHOT</version>\r
   </parent>\r
   <artifactId>yang-model-util</artifactId>\r
   <dependencies>\r
index df111acf0854603d453f1c1bd6cefb40a449d48c..7c26531f37efbddd520b31623539d011511719f7 100644 (file)
@@ -8,29 +8,30 @@ import java.util.Set;
 import org.opendaylight.controller.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.controller.yang.model.api.DataNodeContainer;
 import org.opendaylight.controller.yang.model.api.DataSchemaNode;
+import org.opendaylight.controller.yang.model.api.GroupingDefinition;
 import org.opendaylight.controller.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.controller.yang.model.api.LeafSchemaNode;
 import org.opendaylight.controller.yang.model.api.ListSchemaNode;
 
 public class DataNodeIterator implements Iterator<DataSchemaNode> {
-    
+
     private final DataNodeContainer container;
     private List<ListSchemaNode> allLists;
     private List<ContainerSchemaNode> allContainers;
     private List<LeafSchemaNode> allLeafs;
     private List<LeafListSchemaNode> allLeafLists;
     private List<DataSchemaNode> allChilds;
-    
+
     public DataNodeIterator(final DataNodeContainer container) {
         if (container == null) {
             throw new IllegalArgumentException("Data Node Container MUST be specified and cannot be NULL!");
         }
-        
+
         init();
         this.container = container;
         traverse(this.container);
     }
-    
+
     private void init() {
         this.allContainers = new ArrayList<ContainerSchemaNode>();
         this.allLists = new ArrayList<ListSchemaNode>();
@@ -38,28 +39,28 @@ public class DataNodeIterator implements Iterator<DataSchemaNode> {
         this.allLeafLists = new ArrayList<LeafListSchemaNode>();
         this.allChilds = new ArrayList<DataSchemaNode>();
     }
-    
+
     public List<ContainerSchemaNode> allContainers() {
         return allContainers;
     }
-    
+
     public List<ListSchemaNode> allLists() {
         return allLists;
     }
-    
+
     public List<LeafSchemaNode> allLeafs() {
         return allLeafs;
     }
-    
+
     public List<LeafListSchemaNode> allLeafLists() {
         return allLeafLists;
     }
-    
+
     private void traverse(final DataNodeContainer dataNode) {
         if (dataNode == null) {
             return;
         }
-        
+
         final Set<DataSchemaNode> childs = dataNode.getChildNodes();
         if (childs != null) {
             for (DataSchemaNode childNode : childs) {
@@ -83,15 +84,21 @@ public class DataNodeIterator implements Iterator<DataSchemaNode> {
                     allLeafLists.add(leafList);
                 }
             }
-            return;
+        }
+
+        final Set<GroupingDefinition> groupings = dataNode.getGroupings();
+        if(groupings != null) {
+            for(GroupingDefinition grouping : groupings) {
+                traverse(grouping);
+            }
         }
     }
-    
+
     @Override
     public boolean hasNext() {
         if (container.getChildNodes() != null) {
             Set<DataSchemaNode> childs = container.getChildNodes();
-            
+
             if ((childs != null) && !childs.isEmpty()) {
                 return childs.iterator().hasNext();
             }
index 86bde24d62d8131314f0f1d37b7e8ed61552f72e..e5ef2026f17e9bb200dec87cecad2d70baeed396 100644 (file)
@@ -194,126 +194,54 @@ public class ExtendedType implements TypeDefinition<TypeDefinition<?>> {
     }
 
     @Override
-    public int hashCode() {
-        final int prime = 31;
-        int result = 1;
-        result = prime * result
-                + ((baseType == null) ? 0 : baseType.hashCode());
-        result = prime * result
-                + ((defaultValue == null) ? 0 : defaultValue.hashCode());
-        result = prime * result
-                + ((description == null) ? 0 : description.hashCode());
-        result = prime
-                * result
-                + ((unknownSchemaNodes == null) ? 0 : unknownSchemaNodes
-                        .hashCode());
-        result = prime * result + ((path == null) ? 0 : path.hashCode());
-        result = prime * result
-                + ((reference == null) ? 0 : reference.hashCode());
-        result = prime * result + ((status == null) ? 0 : status.hashCode());
-        result = prime * result
-                + ((typeName == null) ? 0 : typeName.hashCode());
-        result = prime * result + ((units == null) ? 0 : units.hashCode());
-        return result;
-    }
-
-    @Override
-    public boolean equals(Object obj) {
-        if (this == obj) {
+    public boolean equals(Object o) {
+        if (this == o) {
             return true;
         }
-        if (obj == null) {
-            return false;
-        }
-        if (getClass() != obj.getClass()) {
-            return false;
-        }
-        ExtendedType other = (ExtendedType) obj;
-        if (baseType == null) {
-            if (other.baseType != null) {
-                return false;
-            }
-        } else if (!baseType.equals(other.baseType)) {
-            return false;
-        }
-        if (defaultValue == null) {
-            if (other.defaultValue != null) {
-                return false;
-            }
-        } else if (!defaultValue.equals(other.defaultValue)) {
-            return false;
-        }
-        if (description == null) {
-            if (other.description != null) {
-                return false;
-            }
-        } else if (!description.equals(other.description)) {
-            return false;
-        }
-        if (unknownSchemaNodes == null) {
-            if (other.unknownSchemaNodes != null) {
-                return false;
-            }
-        } else if (!unknownSchemaNodes.equals(other.unknownSchemaNodes)) {
+        if (!(o instanceof ExtendedType)) {
             return false;
         }
-        if (path == null) {
-            if (other.path != null) {
-                return false;
-            }
-        } else if (!path.equals(other.path)) {
-            return false;
-        }
-        if (reference == null) {
-            if (other.reference != null) {
-                return false;
-            }
-        } else if (!reference.equals(other.reference)) {
-            return false;
-        }
-        if (status != other.status) {
-            return false;
-        }
-        if (typeName == null) {
-            if (other.typeName != null) {
-                return false;
-            }
-        } else if (!typeName.equals(other.typeName)) {
+
+        ExtendedType that = (ExtendedType) o;
+        if (path != null ? !path.equals(that.path) : that.path != null) {
             return false;
         }
-        if (units == null) {
-            if (other.units != null) {
-                return false;
-            }
-        } else if (!units.equals(other.units)) {
+        if (typeName != null ? !typeName.equals(that.typeName) : that.typeName != null)
             return false;
-        }
+
         return true;
     }
 
+    @Override
+    public int hashCode() {
+        int result = typeName != null ? typeName.hashCode() : 0;
+        result = 31 * result + (path != null ? path.hashCode() : 0);
+        return result;
+    }
+
     @Override
     public String toString() {
-        StringBuilder builder2 = new StringBuilder();
-        builder2.append("ExtendedType [typeName=");
-        builder2.append(typeName);
-        builder2.append(", baseType=");
-        builder2.append(baseType);
-        builder2.append(", path=");
-        builder2.append(path);
-        builder2.append(", description=");
-        builder2.append(description);
-        builder2.append(", reference=");
-        builder2.append(reference);
-        builder2.append(", unknownSchemaNodes=");
-        builder2.append(unknownSchemaNodes);
-        builder2.append(", status=");
-        builder2.append(status);
-        builder2.append(", units=");
-        builder2.append(units);
-        builder2.append(", defaultValue=");
-        builder2.append(defaultValue);
-        builder2.append("]");
-        return builder2.toString();
+        StringBuilder builder = new StringBuilder();
+        builder.append("ExtendedType [typeName=");
+        builder.append(typeName);
+        builder.append(", baseType=");
+        builder.append(baseType);
+        builder.append(", path=");
+        builder.append(path);
+        builder.append(", description=");
+        builder.append(description);
+        builder.append(", reference=");
+        builder.append(reference);
+        builder.append(", unknownSchemaNodes=");
+        builder.append(unknownSchemaNodes);
+        builder.append(", status=");
+        builder.append(status);
+        builder.append(", units=");
+        builder.append(units);
+        builder.append(", defaultValue=");
+        builder.append(defaultValue);
+        builder.append("]");
+        return builder.toString();
     }
 
     public List<RangeConstraint> getRanges() {
index 2d6a78988752de136af601dd70ab40713cfa9a9e..13c2ba7cb55455800e763c754f53883d8e0986eb 100644 (file)
@@ -33,7 +33,7 @@ public final class SchemaContextUtil {
     public static DataSchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
         if (schemaPath != null) {
             final Module module = resolveModuleFromSchemaPath(context, schemaPath);
-            final Queue<QName> prefixedPath = new LinkedList<QName>(schemaPath.getPath());
+            final Queue<QName> prefixedPath = new LinkedList<>(schemaPath.getPath());
 
             if ((module != null) && (prefixedPath != null)) {
                 return findSchemaNodeForGivenPath(context, module, prefixedPath);
@@ -87,32 +87,35 @@ public final class SchemaContextUtil {
         return null;
     }
 
-    public static Module resolveModuleFromSchemaPath(final SchemaContext context, final SchemaPath schemaPath) {
+    private static Module resolveModuleFromSchemaPath(final SchemaContext
+        context, final SchemaPath schemaPath) {
         if ((schemaPath != null) && (schemaPath.getPath() != null)) {
-            List<QName> path = schemaPath.getPath();
-            final QName qname = path.get(path.size()-1);
+            final List<QName> path = schemaPath.getPath();
+            if (!path.isEmpty()) {
+                final QName qname = path.get(path.size() - 1);
 
-            if ((qname != null) && (qname.getNamespace() != null)) {
-                return context.findModuleByNamespace(qname.getNamespace());
+                if ((qname != null) && (qname.getNamespace() != null)) {
+                    return context.findModuleByNamespace(qname.getNamespace());
+                }
             }
         }
         return null;
     }
 
-    public static Module resolveModuleFromTypePath(final SchemaContext context, final TypeDefinition<?> type) {
+    public static Module findParentModuleForTypeDefinition(
+            final SchemaContext context, final TypeDefinition<?> type) {
         final SchemaPath schemaPath = type.getPath();
         if ((schemaPath != null) && (schemaPath.getPath() != null)) {
             if(type instanceof ExtendedType) {
                 List<QName> path = schemaPath.getPath();
-                final QName qname = path.get(path.size()-1);
+                final QName qname = path.get(path.size() - 1);
 
                 if ((qname != null) && (qname.getNamespace() != null)) {
                     return context.findModuleByNamespace(qname.getNamespace());
                 }
             } else {
-                LinkedList<QName> path = new LinkedList<QName>(schemaPath.getPath());
-                path.removeLast();
-                final QName qname = path.get(path.size()-1);
+                List<QName> path = schemaPath.getPath();
+                final QName qname = path.get(path.size() - 2);
 
                 if ((qname != null) && (qname.getNamespace() != null)) {
                     return context.findModuleByNamespace(qname.getNamespace());
@@ -142,7 +145,7 @@ public final class SchemaContextUtil {
                     "The Schema Path MUST contain at least ONE QName which defines namespace and Local name" +
                     "of path.");
         }
-        final QName qname = qnamedPath.get(0);
+        final QName qname = qnamedPath.get(qnamedPath.size() - 1);
         return context.findModuleByNamespace(qname.getNamespace());
     }
 
@@ -186,7 +189,7 @@ public final class SchemaContextUtil {
 
     private static Queue<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
             final String xpath) {
-        final Queue<QName> path = new LinkedList<QName>();
+        final Queue<QName> path = new LinkedList<>();
         if (xpath != null) {
             final String[] prefixedPath = xpath.split("/");
 
@@ -240,7 +243,7 @@ public final class SchemaContextUtil {
     private static Queue<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
             final RevisionAwareXPath relativeXPath,
             final SchemaPath leafrefSchemaPath) {
-        final Queue<QName> absolutePath = new LinkedList<QName>();
+        final Queue<QName> absolutePath = new LinkedList<>();
 
         if ((module != null) && (relativeXPath != null) && !relativeXPath.isAbsolute()
                 && (leafrefSchemaPath != null)) {
index 3cacab784663a66919a06ec0bdbb099c68ac709f..ff91e93f58c97e8b4bf234a8b1a601bb05094700 100644 (file)
@@ -19,36 +19,36 @@ import org.slf4j.LoggerFactory;
 
 /**
  * This class represents a configuration manager for the Load Balancer service.
- * This class is responsible for managing(store/update/delete) the load balancer 
+ * This class is responsible for managing(store/update/delete) the load balancer
  * configuration that it receives through REST APIs or from any other applications
  * present in the controller.
  *
  */
 public class ConfigManager implements IConfigManager{
-    
+
     /*
      * Logger instance
      */
     private static final Logger cmLogger = LoggerFactory.getLogger(ConfigManager.class);
-    
+
     /*
-     * All the available VIPs 
+     * All the available VIPs
      */
     private HashMap<String,VIP> vips = new HashMap<String,VIP>();
-    
+
     /*
      * All the available Pools
      */
     private HashMap<String,Pool> pools = new HashMap<String,Pool>();
-    
+
     public ConfigManager(){
     }
-    
+
     @Override
     public boolean vipExists(String name) {
         return this.vips.containsKey(name);
     }
-    
+
     @Override
     public boolean vipExists(VIP vip){
         if(vip.getName()==null){
@@ -64,80 +64,80 @@ public class ConfigManager implements IConfigManager{
         }
         return true;
     }
-    
+
     @Override
     public boolean vipExists(String name,String ip,String protocol,short protocolPort,String poolName){
-        
+
         VIP vip = new VIP(name,ip,protocol,protocolPort,poolName);
-        
+
         //Check VIP with the same name
-        
+
         if(!vips.containsKey(name)){
             //Check VIP with the same ip, protocol and protocolPort
             if(!vips.containsValue(vip)){
-                
+
                 //if you reach here, means this VIP don't exist
                 return false;
             }
         }
-        
+
         //Yeah, i have it.
-       return true;
+        return true;
     }
-    
+
     @Override
     public Set<VIP> getAllVIPs(){
         return new HashSet<VIP>(this.vips.values());
     }
-    
+
     public VIP getVIPWithPoolName(VIP vip){
         cmLogger.info("Search a VIP with name:{}",vip);
         for(VIP vipTemp: this.vips.values()){
             if(vipTemp.equals(vip)){
-                
+
                 cmLogger.info("Found VIP with pool detail : {}",vipTemp);
                 return vipTemp;
             }
         }
-        
+
         cmLogger.info("VIP with pool detail not found ");
         return null;
     }
-    
+
     @Override
     public VIP createVIP(String name,String ip,String protocol,short protocolPort,String poolName){
-        
+
         cmLogger.info("Create VIP with the following details :[ name : "+name
                                                                     +" ip : "+ip
                                                                     +" protocol : "+protocol
                                                                     +" protocol_port : "+protocolPort
                                                                     +" pool name : "+poolName);
-        
+
         VIP vip = new VIP(name,ip,protocol,protocolPort,poolName);
-        
+
         if(poolName !=null && !poolName.isEmpty()){
             if(pools.containsKey(poolName)){
                 pools.get(poolName).addVIP(vip);
             }
         }
-        
+
         vip.setStatus(LBConst.STATUS_ACTIVE);
         this.vips.put(name, vip);
-        
+
         cmLogger.info("New VIP created : "+vip.toString());
         return vip;
     }
-    
+
     @Override
     public String getVIPAttachedPool(String name) {
         return this.vips.get(name).getPoolName();
     }
-    
+
     @Override
     public VIP updateVIP(String name, String poolName){
-        
+
         cmLogger.info("Updating VIP : "+name+" pool name  to "+poolName);
-        
+
         if(vips.containsKey(name)){
             VIP vip = vips.get(name);
             if(vip.getPoolName() == null){
@@ -150,30 +150,30 @@ public class ConfigManager implements IConfigManager{
         cmLogger.error("VIP with name: "+name+" does not exist");
         return null;
     }
-    
+
     @Override
     public VIP deleteVIP(String name){
-        
+
         cmLogger.info("Deleting VIP : "+name);
-        
+
         VIP vip = vips.get(name);
-        
+
         String poolName = vip.getPoolName();
-        
+
         if(poolName != null){
             if(pools.containsKey(poolName)){
                 Pool pool = pools.get(poolName);
                 pool.removeVIP(vip.getName());
             }
         }
-        
+
         cmLogger.info("VIP removed : "+vip.toString());
-        
+
         vips.remove(vip.getName());
-        
+
         return vip;
     }
-    
+
     @Override
     public boolean memberExists(String name, String poolName) {
         if(this.pools.containsKey(poolName)){
@@ -182,89 +182,89 @@ public class ConfigManager implements IConfigManager{
         }
         return false;
     }
-    
+
     @Override
     public boolean memberExists(String name, String memberIP,String poolName){
         if(!this.pools.containsKey(poolName))
             return false;
-        
+
         return this.pools.get(poolName).poolMemberExists(new PoolMember(name, memberIP, poolName));
     }
-    
+
     @Override
     public PoolMember addPoolMember(String name, String memberIP, String poolName){
-        
+
         PoolMember pm = new PoolMember(name,memberIP,poolName);
-        
+
         cmLogger.info("Adding pool member : "+pm.toString());
-        
+
         pools.get(poolName).addMember(pm);
-        
+
         return pm;
     }
-    
+
     @Override
     public PoolMember removePoolMember(String name, String poolName){
-        
+
         cmLogger.info("Removing pool member : {} from pool {}",name, poolName);
-        
+
         Pool pool = pools.get(poolName);
-        
+
         PoolMember pm = pool.getMember(name);
-        
+
         pool.removeMember(name);
-        
+
         cmLogger.info("Pool member {} removed from {} ",name,poolName);
-        
+
         return pm;
     }
-    
+
     @Override
     public Set<Pool> getAllPools(){
         return new HashSet<Pool>(this.pools.values());
     }
-    
+
     @Override
     public boolean poolExists(String name) {
         return this.pools.containsKey(name);
     }
-    
+
     @Override
     public boolean poolExists(String name, String lbMethod){
-        
+
         return pools.containsValue(new Pool(name,lbMethod));
     }
-    
+
     @Override
     public Pool createPool(String name, String lbMethod){
-        
+
         Pool newPool = new Pool(name,lbMethod);
-        
+
         cmLogger.info("New pool created : " + newPool.toString());
-        
+
         pools.put(name, newPool);
-        
+
         return newPool;
     }
-    
+
     @Override
     public Pool deletePool(String poolName){
-        
+
         Pool pool = pools.get(poolName);
-        
+
         for(VIP vip:pool.getAllVip()){
-            
+
             vip.setPoolName(null);
-            
+
         }
-        
+
         cmLogger.info("Pool removed : "+pool.toString());
-        
+
         pools.remove(poolName);
-        
+
         return pool;
     }
-    
+
     @Override
     public Pool getPool( String poolName){
         if(pools.containsKey(poolName)){
@@ -272,16 +272,16 @@ public class ConfigManager implements IConfigManager{
         }
         return null;
     }
-    
+
     @Override
     public Set<PoolMember> getAllPoolMembers(String poolName) {
-        
+
         if(pools.containsKey(poolName)){
             return new HashSet<PoolMember>(pools.get(poolName).getAllMembers());
         }
         return null;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#toString()
      */
index df35b0ae1f7f4803b63473dccc200f7a588c6195..5e55b2a3dd3513d1b83956eefb83526a8d655369 100644 (file)
@@ -18,164 +18,164 @@ import org.opendaylight.controller.samples.loadbalancer.entities.VIP;
  *
  */
 public interface IConfigManager {
-    
+
     /**
      * Return all existing VIPs
      * @return Set of VIP's
      * if there is no VIP, it will return empty set.
      */
     public Set<VIP> getAllVIPs();
-    
+
     /**
      * Check if VIP with the 'name' exists
-     * @param name     Name of the VIP 
-     * @return true    if exists
-     *                         false   else
+     * @param name  Name of the VIP
+     * @return  true    if exists
+     *                  false   else
      */
     public boolean vipExists(String name);
 
     /**
-     * Check if VIP exists with the details 'VIP' 
-     * @param vip Search for this VIP 
-     * @return true    if exists
-     *                         false   else
+     * Check if VIP exists with the details 'VIP'
+     * @param vip Search for this VIP
+     * @return  true    if exists
+     *                  false   else
      */
     public boolean vipExists(VIP vip);
 
     /**
      * Check if VIP with the provided details exists
-     * @param name     Name of the VIP
-     * @param ip       IP of the VIP
-     * @param protocol IP Protocol of the VIP (TCP/UDP)
-     * @param protocolPort     Transport port of the VIP (e.g 5550)
-     * @param poolName Name of the pool attached with the VIP
-     * @return true    if exists
-     *                         false   else
+     * @param name  Name of the VIP
+     * @param ip    IP of the VIP
+     * @param protocol  IP Protocol of the VIP (TCP/UDP)
+     * @param protocolPort  Transport port of the VIP (e.g 5550)
+     * @param poolName  Name of the pool attached with the VIP
+     * @return  true    if exists
+     *                  false   else
      */
     public boolean vipExists(String name,String ip,String protocol,short protocolPort,String poolName);
-    
+
     /**
      * Add VIP to the configuration
-     * @param name     Name of the VIP
-     * @param ip       IP of the VIP
-     * @param protocol IP Protocol of the VIP (TCP/UDP)
-     * @param protocolPort     Transport port of the VIP
-     * @param poolName Name of the pool that VIP will use for load balancing its traffic
-     * @return Newly created VIP
+     * @param name  Name of the VIP
+     * @param ip    IP of the VIP
+     * @param protocol  IP Protocol of the VIP (TCP/UDP)
+     * @param protocolPort  Transport port of the VIP
+     * @param poolName  Name of the pool that VIP will use for load balancing its traffic
+     * @return  Newly created VIP
      */
     public VIP createVIP(String name,String ip,String protocol,short protocolPort,String poolName);
-    
+
     /**
      * Return pool attached to VIP
      * @param name Name of the VIP
-     * @return Name of the pool attached to VIP
-     *                         else null
+     * @return  Name of the pool attached to VIP
+     *                  else null
      */
     public String getVIPAttachedPool(String name);
     /**
      * Update pool name of the VIP.
-     * @param name     Name of the VIP
-     * @param poolName Attach this pool to VIP
-     * @return Updated VIP     If successful
-     *                         null                    If this VIP is already attached to any existing pool.
-     */                        
+     * @param name  Name of the VIP
+     * @param poolName  Attach this pool to VIP
+     * @return  Updated VIP     If successful
+     *                  null            If this VIP is already attached to any existing pool.
+     */
     public VIP updateVIP(String name, String poolName);
-    
+
     /**
      * Delete the VIP
-     * @param name     Delete VIP with this name
-     * @return Details of the deleted VIP
+     * @param name  Delete VIP with this name
+     * @return  Details of the deleted VIP
      */
     public VIP deleteVIP(String name);
 
     /**
-     * Check if pool member with the 'name' present in the pool with name 'poolName' 
-     * @param name     Name of the pool member 
-     * @param poolName Name of the pool, you want to search for pool member
-     * @return true    If exist
-     *                         false   else
+     * Check if pool member with the 'name' present in the pool with name 'poolName'
+     * @param name  Name of the pool member
+     * @param poolName  Name of the pool, you want to search for pool member
+     * @return  true    If exist
+     *                  false   else
      */
     public boolean memberExists(String name, String poolName);
 
     /**
      * Check if pool member with name 'name' and IP 'memberIP' exist in the pool 'poolName'
-     * @param name     Name of the pool member
-     * @param memberIP IP of the pool member
-     * @param poolName Name of the pool member you want to search
-     * @return true    If Exist
-     *                         false   else
+     * @param name  Name of the pool member
+     * @param memberIP  IP of the pool member
+     * @param poolName  Name of the pool member you want to search
+     * @return  true    If Exist
+     *                  false   else
      */
     public boolean memberExists(String name, String memberIP,String poolName);
-    
+
     /**
      * Return all  pool members of the pool 'poolName'
-     * @param poolName Name of the pool
-     * @return Set of all the pool members             if pool with the name present in the configuration
-     *                         null                                                    else
-     *                         
+     * @param poolName  Name of the pool
+     * @return  Set of all the pool members     if pool with the name present in the configuration
+     *                  null                            else
+     *
      */
     public Set<PoolMember> getAllPoolMembers(String poolName);
-    
+
     /**
      * Add new pool member to the configuration
-     * @param name     Name of the pool
-     * @param memberIP IP of the pool
-     * @param poolName Attach pool member to this pool
-     * @return Newly created pool member 
+     * @param name  Name of the pool
+     * @param memberIP  IP of the pool
+     * @param poolName  Attach pool member to this pool
+     * @return  Newly created pool member
      */
     public PoolMember addPoolMember(String name, String memberIP, String poolName);
-    
+
     /**
      * Remove pool member from the pool
-     * @param name     Name of the pool member
-     * @param poolName Name of the pool
-     * @return Details of the removed pool member 
+     * @param name  Name of the pool member
+     * @param poolName  Name of the pool
+     * @return  Details of the removed pool member
      */
     public PoolMember removePoolMember(String name, String poolName);
 
     /**
      * Return all the existing pools
-     * @return Set of Pools
+     * @return  Set of Pools
      */
     public Set<Pool> getAllPools();
-    
+
     /**
      * Return pool with input name
-     * @param poolName Name of the pool
-     * @return Details of the pool     if pool exist
-     *                         null                                    else
+     * @param poolName  Name of the pool
+     * @return  Details of the pool     if pool exist
+     *                  null                    else
      */
     public Pool getPool(String poolName);
-    
+
     /**
-     * Check if pool exists with the input name 
-     * @param name     Name of the pool
-     * @return true    If exists
-     *                         false   else
+     * Check if pool exists with the input name
+     * @param name  Name of the pool
+     * @return  true    If exists
+     *                  false   else
      */
     public boolean poolExists(String name);
 
     /**
      * Check if pool exists with the input name and loadbalancing method.
-     * @param name     Name of the pool 
-     * @param lbMethod Load balancing method name
-     * @return true    If exists
-     *                         false   else
+     * @param name  Name of the pool
+     * @param lbMethod  Load balancing method name
+     * @return  true    If exists
+     *                  false   else
      */
     public boolean poolExists(String name, String lbMethod);
-    
+
     /**
      * Create new pool with the provided details
-     * @param name     Name of the pool
-     * @param lbMethod Load balancing method this pool will use
-     * @return Details of the newly created pool
+     * @param name  Name of the pool
+     * @param lbMethod  Load balancing method this pool will use
+     * @return  Details of the newly created pool
      */
     public Pool createPool(String name, String lbMethod);
-    
+
     /**
      * Delete pool with the provided name
-     * @param poolName Name of the pool
-     * @return Details of the deleted pool
+     * @param poolName  Name of the pool
+     * @return  Details of the deleted pool
      */
     public Pool deletePool(String poolName);
 
index 7e93304de10b2294e060b72494febe943e93e683..bd6fb473c1adcaaa098eb7f1e76f624b0fb7f691 100644 (file)
@@ -12,22 +12,21 @@ package org.opendaylight.controller.samples.loadbalancer;
  *
  */
 public class LBConst {
-    
+
     public static final int FORWARD_DIRECTION_LB_FLOW = 0;
-    
+
     public static final int REVERSE_DIRECTION_LB_FLOW = 1;
-    
+
     public static final String ROUND_ROBIN_LB_METHOD = "roundrobin";
-    
+
     public static final String RANDOM_LB_METHOD = "random";
-    
+
     public static final String STATUS_ACTIVE="active";
-    
+
     public static final String STATUS_INACTIVE="inactive";
-    
+
     public static final String STATUS_PENDING="pending";
-    
+
     public static final String STATUS_ERROR="error";
-       
-}
 
+}
index c320250084150ddaac6f4337430b33eea8c9940f..aa195a34e9ceb9487291e4e9f020f8b1acec7244 100644 (file)
@@ -19,36 +19,36 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Class defines utilty methods that will be used by different components 
- * of the load balancer service 
+ * Class defines utilty methods that will be used by different components
+ * of the load balancer service
  *
  */
 public class LBUtil {
-    
+
     private static final Logger lbuLogger = LoggerFactory.getLogger(LBUtil.class);
-    
+
     public LBUtil(){}
-    
+
     /**
-     * Extract the details of the source machine that sent this packet 'inPkt'  
-     * @param inPkt    Packet that is received by the controller
-     * @return Details of the source machine in Client object.
+     * Extract the details of the source machine that sent this packet 'inPkt'
+     * @param inPkt Packet that is received by the controller
+     * @return  Details of the source machine in Client object.
      */
     public Client getClientFromPacket(IPv4 inPkt){
         lbuLogger.info("Find client information from packet : {}",inPkt.toString());
-        
+
         String ip = NetUtils.getInetAddress(inPkt.getSourceAddress()).getHostAddress();
-        
+
         String protocol = IPProtocols.getProtocolName(inPkt.getProtocol());
-        
+
         lbuLogger.info("client ip {} and protocl {}",ip,protocol);
-        
+
         Packet tpFrame= inPkt.getPayload();
-        
+
         lbuLogger.info("Get protocol layer {}",tpFrame.toString());
-        
+
         short port = 0;
-        
+
         if(protocol.equals(IPProtocols.TCP.toString())){
             TCP tcpFrame = (TCP)tpFrame;
             port = tcpFrame.getSourcePort();
@@ -56,47 +56,47 @@ public class LBUtil {
             UDP udpFrame = (UDP)tpFrame;
             port = udpFrame.getSourcePort();
         }
-        
+
         lbuLogger.info("Found port {}",port);
-        
+
         Client source = new Client(ip, protocol,port);
-        
+
         lbuLogger.info("Client information : {}",source.toString());
-        
+
         return source;
     }
-    
+
     /**
      * Extract the details of the destination machine where this packet 'inPkt' need
      * to be delivered
      * @param inPkt Packet that is received by controller for forwarding
-     * @return Details of the destination machine packet in VIP
+     * @return  Details of the destination machine packet in VIP
      */
     public VIP getVIPFromPacket(IPv4 inPkt){
-        
+
         lbuLogger.info("Find VIP information from packet : {}",inPkt.toString());
-        
+
         String ip = NetUtils.getInetAddress(inPkt.getDestinationAddress()).getHostAddress();
-        
+
         String protocol = IPProtocols.getProtocolName(inPkt.getProtocol());
-        
+
         Packet tpFrame= inPkt.getPayload();
-        
+
         short port = 0;
-        
+
         if(protocol.equals(IPProtocols.TCP.toString())){
             TCP tcpFrame = (TCP)tpFrame;
             port = tcpFrame.getDestinationPort();
         }else{
-            
+
             UDP udpFrame = (UDP)tpFrame;
             port = udpFrame.getDestinationPort();
         }
-        
+
         VIP dest = new VIP(null,ip, protocol,port,null);
-        
+
         lbuLogger.info("VIP information : {}",dest.toString());
-        
+
         return dest;
     }
 }
\ No newline at end of file
index 4d7cf4928a6b8684a162e49e29dc00e5e04a3bed..a16582d532dcf145b394c7ff73e86d39d7d7f845 100644 (file)
@@ -17,73 +17,73 @@ package org.opendaylight.controller.samples.loadbalancer.entities;
  * e.g TCP traffic from two different ports from the same host to a given VIP will be considered
  * as two different clients by this service. Similarly, traffic using two different protocols
  * (TCP, UDP) from the same host will be considered as two different clients.
- * 
+ *
  */
 public class Client {
-    
+
     /*
      * IP address of the client (source address)
      */
     private String ip;
-    
+
     /*
      * Network protocol of the traffic sent by client
      */
     private String protocol;
-    
+
     /*
      * Port used to send network traffic (source port)
      */
     private short port;
-    
+
     public Client(String ip, String protocol, short port){
         this.ip = ip;
         this.protocol = protocol;
         this.port = port;
     }
-    
+
     /**
      * @return the client IP
      */
     public String getIp() {
         return ip;
     }
-    
+
     /**
      * @param ip the IP to set
      */
     public void setIp(String ip) {
         this.ip = ip;
     }
-    
+
     /**
      * @return the client network protocol
      */
     public String getProtocol() {
         return protocol;
     }
-    
+
     /**
      * @param protocol the protocol to set
      */
     public void setProtocol(String protocol) {
         this.protocol = protocol;
     }
-    
+
     /**
      * @return the client port
      */
     public short getPort() {
         return port;
     }
-    
+
     /**
      * @param port the port to set
      */
     public void setPort(short port) {
         this.port = port;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#hashCode()
      */
@@ -96,7 +96,7 @@ public class Client {
         result = prime * result+ ((protocol == null) ? 0 : protocol.hashCode());
         return result;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#equals(java.lang.Object)
      */
@@ -131,7 +131,7 @@ public class Client {
         }
         return true;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#toString()
      */
index bbf31162aaf993ed6ea2fd09836e06559c9e8185..ae48a3a45118533785f5c3175a68df107d9c7c0a 100644 (file)
@@ -16,12 +16,12 @@ import javax.xml.bind.annotation.XmlRootElement;
 
 /**
  * This class represents the pool of hosts among which incoming traffic
- * will be load balanced. Each pool will load balance the traffic among its pool members 
- * based on the loadbalancing policy set for the pool. 
+ * will be load balanced. Each pool will load balance the traffic among its pool members
+ * based on the loadbalancing policy set for the pool.
  * Currently, the pool supports two load balancing policies:
  * 1. Round Robin Policy{@link org.opendaylight.controller.samples.loadbalancer.policies.RoundRobinLBPolicy}
  * 2. Random Policy {@link org.opendaylight.controller.samples.loadbalancer.policies.RandomLBPolicy}
- * 
+ *
  * NOTE: After creation of the pool, user can't update (change) its load balancing policy.
  * NOTE: Each Pool should have a unique name.
  */
@@ -29,124 +29,124 @@ import javax.xml.bind.annotation.XmlRootElement;
 @XmlRootElement(name="pool")
 @XmlAccessorType(XmlAccessType.NONE)
 public class Pool {
-    
+
     /*
      * Unique name of the pool
      */
     @XmlElement
     private String name;
-    
+
     /*
      * Associated load balancing policy
      */
     @XmlElement(name="lbmethod")
     private String lbMethod;
-    
+
     /*
      * Status of the pool (active/inactive)
      */
     @XmlElement
     private String status;
-    
+
     /*
      * List of all the VIPs using this pool for load balancing their traffic - more than
      * one VIP can be mapped to each pool.
      */
     @XmlElement
     private ArrayList<VIP> vips = new ArrayList<VIP>();
-    
+
     /*
      * List of all the pool members used for load balancing the traffic
      */
     @XmlElement
     private ArrayList<PoolMember> members = new ArrayList<PoolMember>();
-    
+
     /*
      * Private constructor used for JAXB mapping
      */
     @SuppressWarnings("unused")
     private Pool() {}
-    
+
     /**
      * Getter/ Setter methods
      */
-    
+
     public Pool(String name,
                     String lbMethod) {
         this.name = name;
         this.lbMethod = lbMethod;
     }
-    
+
     /**
      * @return the name
      */
     public String getName() {
         return name;
     }
-    
+
     /**
      * @param name the name to set
      */
     public void setName(String name) {
         this.name = name;
     }
-    
+
     /**
      * @return the lbMethod
      */
     public String getLbMethod() {
         return lbMethod;
     }
-    
+
     /**
      * @param lbMethod the lbMethod to set
      */
     public void setLbMethod(String lbMethod) {
         this.lbMethod = lbMethod;
     }
-    
+
     /**
      * @return the status
      */
     public String getStatus() {
         return status;
     }
-    
+
     /**
      * @param status the status to set
      */
     public void setStatus(String status) {
         this.status = status;
     }
-    
+
     /**
      * @return the vip
      */
     public ArrayList<VIP> getAllVip() {
         return vips;
     }
-    
+
     /**
      * @param vip the vip to set
      */
     public void setVips(ArrayList<VIP> vips) {
         this.vips = vips;
     }
-    
+
     /**
      * @return the members
      */
     public ArrayList<PoolMember> getAllMembers() {
         return members;
     }
-    
+
     /**
      * @param members the members to set
      */
     public void setMembers(ArrayList<PoolMember> members) {
         this.members = members;
     }
-    
+
     /**
      * Add new VIP to the VIP list
      * @param vip       new VIP to add
@@ -154,11 +154,11 @@ public class Pool {
     public void addVIP(VIP vip){
         this.vips.add(vip);
     }
-    
+
     /**
      * Remove VIP with given name from the VIP list of the pool
      * @param name      Name of the VIP
-     * @return true     If VIP was using this pool and removed
+     * @return  true     If VIP was using this pool and removed
      *          false   IF VIP is not using this pool
      */
     public boolean removeVIP(String name){
@@ -170,25 +170,25 @@ public class Pool {
         }
         return false;
     }
-    
+
     /**
      * Check if the given pool member is part of this pool
      * @param pm        Search for this pool member
-     * @return true     If pool member is attached to this pool
+     * @return  true     If pool member is attached to this pool
      *          false   else
      */
     public boolean poolMemberExists(PoolMember pm){
         return this.members.contains(pm);
     }
-    
+
     /**
      * Returns the pool member with the given name
      * @param name      Search for this pool member
-     * @return PoolMember       If pool member is attached to this pool
+     * @return  PoolMember       If pool member is attached to this pool
      *          null            else
      */
     public PoolMember getMember(String name){
-        
+
         for(PoolMember pm: this.members){
             if(pm.getName().equals(name)){
                 return pm;
@@ -196,7 +196,7 @@ public class Pool {
         }
         return null;
     }
-    
+
     /**
      * Add new pool member to the pool
      * @param pm        Add this new pool
@@ -204,12 +204,12 @@ public class Pool {
     public void addMember(PoolMember pm){
         this.members.add(pm);
     }
-    
+
     /**
      * Remove pool member from the pool list
      * @param name Remove this pool member
-     * @return true    If pool member was attached to this pool and successfully removed
-     *          false  If pool member is not attached to this pool
+     * @return  true    If pool member was attached to this pool and successfully removed
+     *          false   If pool member is not attached to this pool
      */
     public boolean removeMember(String name){
         for(PoolMember pm: this.members){
@@ -220,7 +220,7 @@ public class Pool {
         }
         return false;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#hashCode()
      */
@@ -232,7 +232,7 @@ public class Pool {
         result = prime * result + ((name == null) ? 0 : name.hashCode());
         return result;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#equals(java.lang.Object)
      */
@@ -264,7 +264,7 @@ public class Pool {
         }
         return true;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#toString()
      */
index 31297ebcce8f27b27a8cf9bea1ab3ddfd333b4f2..31949b43d48311c52f884ee262a0131ead4b3ee6 100644 (file)
@@ -17,111 +17,111 @@ import javax.xml.bind.annotation.XmlRootElement;
  * This class represents the host where load balancing service will
  * redirect VIP traffic for load balancing. All these hosts have to
  * register with a pool to be a part of traffic load balancing.
- * This entity is referred to as a 'PoolMember'. 
- * Load balancer service differentiates each pool member based on its 
+ * This entity is referred to as a 'PoolMember'.
+ * Load balancer service differentiates each pool member based on its
  * two properties { ip address, attached pool }.
  * A host (IP) can be attached to two different pools through creation of two
  * different pool member objects.
- * 
+ *
  * NOTE: Each pool member should have a unique name.
  *
  */
 @XmlRootElement(name="poolmember")
 @XmlAccessorType(XmlAccessType.NONE)
 public class PoolMember {
-    
+
     /*
      * Unique name of the pool member
      */
     @XmlElement
     private String name;
-    
+
     /*
      * IP address of the pool member
      */
     @XmlElement
     private String ip;
-    
+
     /*
      * Name of the pool this member is attached to.
      */
     @XmlElement(name="poolname")
     private String poolName;
-    
+
     /*
      * Status (active/inactive)
      */
     @XmlElement
     private String status;
-    
+
     /**
      * Private constructor used for JAXB mapping
      */
     @SuppressWarnings("unused")
     private PoolMember() {}
-    
+
     public PoolMember(String name, String memberIP, String poolName){
         this.name = name;
         this.ip = memberIP;
         this.poolName = poolName;
     }
-    
+
     /**
      * @return the name
      */
     public String getName() {
         return name;
     }
-    
+
     /**
      * @param name the name to set
      */
     public void setName(String name) {
         this.name = name;
     }
-    
+
     /**
      * @return the ip
      */
     public String getIp() {
         return ip;
     }
-    
+
     /**
      * @param ip the ip to set
      */
     public void setIp(String ip) {
         this.ip = ip;
     }
-    
+
     /**
      * @return the poolName
      */
     public String getPoolName() {
         return poolName;
     }
-    
+
     /**
      * @param poolName the poolName to set
      */
     public void setPoolName(String poolName) {
         this.poolName = poolName;
     }
-    
+
     /**
      * @return the status
      */
     public String getStatus() {
         return status;
     }
-    
+
     /**
      * @param status the status to set
      */
     public void setStatus(String status) {
         this.status = status;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#hashCode()
      */
@@ -134,7 +134,7 @@ public class PoolMember {
                 + ((poolName == null) ? 0 : poolName.hashCode());
         return result;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#equals(java.lang.Object)
      */
index 6f866fe23f0b2521739ec56f7e7afdff6f062df5..22a7109f59c87c027f7da8d084d52872995e2180 100644 (file)
@@ -18,47 +18,47 @@ import javax.xml.bind.annotation.XmlRootElement;
  * 1. IP address of the VIP exposed by the application
  * 2. Protocol of the network traffic (TCP/UDP)
  * 3. Port to which incoming traffic is destined
- * 
- * User is allowed to create mutliple VIPs with the same IP, but all such VIPs (with the same IP) 
+ *
+ * User is allowed to create mutliple VIPs with the same IP, but all such VIPs (with the same IP)
  * should differ at least in the protocol or port or both.
- * 
+ *
  * NOTE: Each VIP should have a unique name.
  */
 @XmlRootElement(name="vip")
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class VIP {
-    
+
     /*
      * Unique name of the VIP
      */
     @XmlElement
     private String name;
-    
+
     /*
-     * Virtual IP address of the VIP 
+     * Virtual IP address of the VIP
      */
     @XmlElement
     private String ip;
-    
+
     /*
-     * Network traffic protocol 
+     *  Network traffic protocol
      */
     @XmlElement
     private String protocol;
-    
+
     /*
      * Port where network traffic is destined (destination port)
      */
     @XmlElement
     private short port;
-    
+
     /*
      * Name of the pool attached to the VIP for load balancing its traffic
      */
     @XmlElement(name="poolname")
     private String poolName;
-    
+
     /*
      * Status (Active/inactive)
      */
@@ -70,7 +70,7 @@ public class VIP {
      */
     @SuppressWarnings("unused")
     private VIP() {}
-    
+
     public VIP(String name,
                 String ip,
                 String protocol,
@@ -82,61 +82,61 @@ public class VIP {
         this.port = port;
         this.poolName = poolName;
     }
-    
+
     public String getName() {
         return name;
     }
-    
+
     public void setName(String name) {
         this.name = name;
     }
-    
+
     public String getIp() {
         return ip;
     }
-    
+
     public void setIp(String ip) {
         this.ip = ip;
     }
-    
+
     public String getProtocol() {
         return protocol;
     }
-    
+
     public void setProtocol(String protocol) {
         this.protocol = protocol;
     }
-    
+
     public short getPort() {
         return port;
     }
-    
+
     public void setPort(short port) {
         this.port = port;
     }
-    
+
     public String getPoolName() {
         return poolName;
     }
-    
+
     public void setPoolName(String poolName) {
         this.poolName = poolName;
     }
-    
+
     /**
      * @return the status
      */
     public String getStatus() {
         return status;
     }
-    
+
     /**
      * @param status the status to set
      */
     public void setStatus(String status) {
         this.status = status;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#hashCode()
      */
@@ -150,7 +150,7 @@ public class VIP {
                 + ((protocol == null) ? 0 : protocol.hashCode());
         return result;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#equals(java.lang.Object)
      */
@@ -158,7 +158,7 @@ public class VIP {
     public boolean equals(Object obj) {
         if (this == obj) {
             return true;
-            
+
         }
         if (obj == null) {
             return false;
@@ -166,7 +166,7 @@ public class VIP {
         if (!(obj instanceof VIP)) {
             return false;
         }
-        
+
         VIP other = (VIP) obj;
         if (ip == null) {
             if (other.ip != null) {
@@ -187,7 +187,7 @@ public class VIP {
         }
         return true;
     }
-    
+
     /* (non-Javadoc)
      * @see java.lang.Object#toString()
      */
index 0568fced6ea4faa9534684d7b9fa8a9d7b7c6aa0..fc78a72eaf0ff08b9b8a1010a04a9dc76b2a82e0 100644 (file)
@@ -23,13 +23,13 @@ import org.opendaylight.controller.sal.routing.IRouting;
 import org.opendaylight.controller.samples.loadbalancer.IConfigManager;
 
 /**
- * Main application activator class for registering the dependencies and 
+ * Main application activator class for registering the dependencies and
  * initialising the load balancer application.
  *
  */
 
 public class Activator extends ComponentActivatorAbstractBase {
-    
+
     /*
      * Logger instance
      */
@@ -86,13 +86,13 @@ public class Activator extends ComponentActivatorAbstractBase {
             props.put("salListenerName", "loadbalancer");
 
             c.setInterface(new String[] { IListenDataPacket.class.getName(),
-                       IConfigManager.class.getName()}, props);
+                        IConfigManager.class.getName()}, props);
 
             c.add(createContainerServiceDependency(containerName).setService(
                     IDataPacketService.class).setCallbacks(
                     "setDataPacketService", "unsetDataPacketService")
                     .setRequired(true));
-            
+
             c.add(createContainerServiceDependency(containerName).setService(
                     IRouting.class).setCallbacks("setRouting", "unsetRouting")
                     .setRequired(false));
index ddfde38931f5db3544ef323dab11ec8222cd629d..7eaa8b4ec03377cf429c67d670341dd74d20aa57 100644 (file)
@@ -56,78 +56,78 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * This class is the main class that represents the load balancer service. 
- * This is a sample load balancer application that balances traffic to backend servers 
- * based on the source address and source port on each incoming packet.  The service 
+ * This class is the main class that represents the load balancer service.
+ * This is a sample load balancer application that balances traffic to backend servers
+ * based on the source address and source port on each incoming packet.  The service
  * reactively installs OpenFlow rules to direct all packets with a specific source address
- * and source port to one of the appropriate backend servers.  The servers may be chosen 
- * using a round robin policy or a random policy. This service can be configured via a 
+ * and source port to one of the appropriate backend servers.  The servers may be chosen
+ * using a round robin policy or a random policy. This service can be configured via a
  * REST APIs which are similar to the OpenStack Quantum LBaaS (Load-balancer-as-a-Service)
  * v1.0 API proposal (http://wiki.openstack.org/Quantum/LBaaS)
- * 
+ *
  * To use this service, a virtual IP (or VIP) should be exposed to the clients of this service
  * and used as the destination address. A VIP is a entity that comprises of a virtual IP, port
  * and protocol (TCP or UDP).
  * Assumptions:
  *      1. One or more VIPs may be mapped to the same server pool. All VIPs that share the same
  *      pool must also share the same load balancing policy (random or round robin).
- *      
+ *
  *      2. Only one server pool can be be assigned to a VIP.
- *      
+ *
  *      3. All flow rules are installed with an idle timeout of 5 seconds.
- *      
+ *
  *      4. Packets to a VIP must leave the OpenFlow  cluster from the same switch from where
  *      it entered it.
- *      
+ *
  *      5. When you delete a VIP or a server pool or a server from a pool, the service does not
  *      delete the flow rules it has already installed. The flow rules should automatically
- *      time out after the idle timeout of 5 seconds. 
+ *      time out after the idle timeout of 5 seconds.
  *
  */
 public class LoadBalancerService implements IListenDataPacket, IConfigManager{
-    
+
     /*
      * Logger instance
      */
     private static Logger lbsLogger = LoggerFactory.getLogger(LoadBalancerService.class);
-    
+
     /*
      * Single instance of the configuration manager. Application passes this reference to all
      * the new policies implemented for load balancing.
      */
     private static ConfigManager configManager = new ConfigManager();
-    
+
     /*
      * Round robing policy instance. Need to implement factory patterns to get
      * policy instance.
      */
     private static RoundRobinLBPolicy rrLBMethod= new RoundRobinLBPolicy(configManager);
-    
+
     /*
      * Random policy instance.
      */
     private static RandomLBPolicy ranLBMethod= new RandomLBPolicy(configManager);
-    
+
     /*
      * Reference to the data packet service
      */
     private IDataPacketService dataPacketService = null;
-    
+
     /*
      * Reference to the host tracker service
      */
     private IfIptoHost hostTracker;
-    
+
     /*
      * Reference to the forwarding manager
      */
     private IForwardingRulesManager ruleManager;
-    
+
     /*
      * Reference to the routing service
      */
     private IRouting routing;
-    
+
     /*
      * Load balancer application installs all flows with priority 2.
      */
@@ -139,7 +139,7 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
     private String containerName = null;
 
     /*
-     * Set/unset methods for the service instance that load balancer 
+     * Set/unset methods for the service instance that load balancer
      * service requires
      */
     public String getContainerName() {
@@ -147,7 +147,7 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
             return GlobalConstants.DEFAULT.toString();
         return containerName;
     }
-    
+
     void setDataPacketService(IDataPacketService s) {
         this.dataPacketService = s;
     }
@@ -157,7 +157,7 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
             this.dataPacketService = null;
         }
     }
-    
+
     public void setRouting(IRouting routing) {
         this.routing = routing;
     }
@@ -169,7 +169,7 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
     }
 
     public void setHostTracker(IfIptoHost hostTracker) {
-       lbsLogger.debug("Setting HostTracker");
+        lbsLogger.debug("Setting HostTracker");
         this.hostTracker = hostTracker;
     }
 
@@ -181,7 +181,7 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
 
     public void setForwardingRulesManager(
             IForwardingRulesManager forwardingRulesManager) {
-       lbsLogger.debug("Setting ForwardingRulesManager");
+        lbsLogger.debug("Setting ForwardingRulesManager");
         this.ruleManager = forwardingRulesManager;
     }
 
@@ -194,68 +194,68 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
 
     /**
      * This method receives first packet of flows for which there is no
-     * matching flow rule installed on the switch. IP addresses used for VIPs 
+     * matching flow rule installed on the switch. IP addresses used for VIPs
      * are not supposed to be used by any real/virtual host in the network.
      * Hence, any forwarding/routing service will not install any flows rules matching
      * these VIPs. This ensures that all the flows destined for VIPs will not find a match
      * in the switch and will be forwarded to the load balancing service.
-     * Service will decide where to route this traffic based on the load balancing 
-     * policy of the VIP's attached pool and will install appropriate flow rules 
-     * in a reactive manner. 
+     * Service will decide where to route this traffic based on the load balancing
+     * policy of the VIP's attached pool and will install appropriate flow rules
+     * in a reactive manner.
      */
     @Override
     public PacketResult receiveDataPacket(RawPacket inPkt){
-        
+
         if (inPkt == null) {
             return PacketResult.IGNORED;
         }
-        
+
         Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt);
-        
+
         if (formattedPak instanceof Ethernet) {
             byte[] vipMacAddr = ((Ethernet) formattedPak).getDestinationMACAddress();
             Object ipPkt = formattedPak.getPayload();
-            
+
             if (ipPkt instanceof IPv4) {
-                
+
                 lbsLogger.debug("Packet recieved from switch : {}",inPkt.getIncomingNodeConnector().getNode().toString());
                 IPv4 ipv4Pkt = (IPv4)ipPkt;
                 if(IPProtocols.getProtocolName(ipv4Pkt.getProtocol()).equals(IPProtocols.TCP.toString())
                         || IPProtocols.getProtocolName(ipv4Pkt.getProtocol()).equals(IPProtocols.UDP.toString())){
-                    
+
                     lbsLogger.debug("Packet protocol : {}",IPProtocols.getProtocolName(ipv4Pkt.getProtocol()));
                     Client client = new LBUtil().getClientFromPacket(ipv4Pkt);
                     VIP vip = new LBUtil().getVIPFromPacket(ipv4Pkt);
-                    
+
                     if(configManager.vipExists(vip)){
                         VIP vipWithPoolName = configManager.getVIPWithPoolName(vip);
                         String poolMemberIp = null;
                         if(configManager.getPool(vipWithPoolName.getPoolName()).getLbMethod().equalsIgnoreCase(LBConst.ROUND_ROBIN_LB_METHOD)){
-                            
+
                             poolMemberIp = rrLBMethod.getPoolMemberForClient(client,vipWithPoolName);
                         }
-                        
+
                         if(configManager.getPool(vipWithPoolName.getPoolName()).getLbMethod().equalsIgnoreCase(LBConst.RANDOM_LB_METHOD)){
                             poolMemberIp = ranLBMethod.getPoolMemberForClient(client,vipWithPoolName);
                         }
-                        
+
                         try {
-                            
+
                             Node clientNode = inPkt.getIncomingNodeConnector().getNode();
                             HostNodeConnector hnConnector = this.hostTracker.hostFind(InetAddress.getByName(poolMemberIp));
-                            
+
                             Node destNode = hnConnector.getnodeconnectorNode();
-                            
+
                             lbsLogger.debug("Client is connected to switch : {}",clientNode.toString());
                             lbsLogger.debug("Destination pool machine is connected to switch : {}",destNode.toString());
-                            
+
                             //Get path between both the nodes
                             Path route = this.routing.getRoute(clientNode, destNode);
-                            
+
                             lbsLogger.info("Path between source (client) and destination switch nodes : {}",route.toString());
-                            
+
                             NodeConnector forwardPort = route.getEdges().get(0).getTailNodeConnector();
-                            
+
                             if(installLoadBalancerFlow(client,
                                                             vip,
                                                             clientNode,
@@ -268,7 +268,7 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
                             }else{
                                 lbsLogger.error("Not able to route traffic from client : {}",client );
                             }
-                            
+
                             if(installLoadBalancerFlow(client,
                                                             vip,
                                                             clientNode,
@@ -291,7 +291,7 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
         }
         return PacketResult.IGNORED;
     }
-    
+
     /*
      * This method installs the flow rule for routing the traffic between two hosts.
      * @param source    Traffic is sent by this source
@@ -301,21 +301,21 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
      * @param destMachineMac    MAC address of the pool member where traffic needs to be routed
      * @param outport   Use this port to send out traffic
      * @param flowDirection     FORWARD_DIRECTION_LB_FLOW or REVERSE_DIRECTION_LB_FLOW
-     * @return true     If flow installation was successful
-     *          false  else
+     * @return  true     If flow installation was successful
+     *          false   else
      *          @throws UnknownHostException
      */
     private boolean installLoadBalancerFlow(Client source,
                                             VIP dest,
                                             Node sourceSwitch,
                                             String destMachineIp,
-                                            byte[] destMachineMac, 
+                                            byte[] destMachineMac,
                                             NodeConnector outport,
                                             int flowDirection) throws UnknownHostException{
-        
+
         Match match = new Match();
         List<Action> actions = new ArrayList<Action>();
-        
+
         if(flowDirection == LBConst.FORWARD_DIRECTION_LB_FLOW){
             match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
             match.setField(MatchType.NW_SRC, InetAddress.getByName(source.getIp()));
@@ -323,11 +323,11 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
             match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(dest.getProtocol()));
             match.setField(MatchType.TP_SRC, source.getPort());
             match.setField(MatchType.TP_DST, dest.getPort());
-            
+
             actions.add(new SetNwDst(InetAddress.getByName(destMachineIp)));
             actions.add(new SetDlDst(destMachineMac));
         }
-        
+
         if(flowDirection == LBConst.REVERSE_DIRECTION_LB_FLOW){
             match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
             match.setField(MatchType.NW_SRC, InetAddress.getByName(destMachineIp));
@@ -335,37 +335,37 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
             match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(source.getProtocol()));
             match.setField(MatchType.TP_SRC, dest.getPort());
             match.setField(MatchType.TP_DST,source.getPort());
-            
+
             actions.add(new SetNwSrc(InetAddress.getByName(dest.getIp())));
             actions.add(new SetDlSrc(destMachineMac));
         }
-        
+
         actions.add(new Output(outport));
-        
+
         // Make sure the priority for IP switch entries is
         // set to a level just above default drop entries
-        
+
         Flow flow = new Flow(match, actions);
         flow.setIdleTimeout((short) 5);
         flow.setHardTimeout((short) 0);
         flow.setPriority(LB_IPSWITCH_PRIORITY);
-        
+
         String policyName = source.getIp()+":"+source.getProtocol()+":"+source.getPort();
         String flowName =null;
-        
+
         if(flowDirection == LBConst.FORWARD_DIRECTION_LB_FLOW){
             flowName = "["+policyName+":"+source.getIp() + ":"+dest.getIp()+"]";
         }
-        
+
         if(flowDirection == LBConst.REVERSE_DIRECTION_LB_FLOW){
-            
+
             flowName = "["+policyName+":"+dest.getIp() + ":"+source.getIp()+"]";
         }
-        
+
         FlowEntry fEntry = new FlowEntry(policyName, flowName, flow, sourceSwitch);
-        
+
         lbsLogger.info("Install flow entry {} on node {}",fEntry.toString(),sourceSwitch.toString());
-        
+
         if(!this.ruleManager.checkFlowEntryConflict(fEntry)){
             if(this.ruleManager.installFlowEntry(fEntry).isSuccess()){
                 return true;
@@ -377,7 +377,7 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
         }
         return false;
     }
-    
+
     /**
      * Function called by the dependency manager when all the required
      * dependencies are satisfied
@@ -387,16 +387,16 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
         Dictionary<?, ?> props = c.getServiceProperties();
         if (props != null) {
             this.containerName = (String) props.get("containerName");
-            
+
             lbsLogger.info("Running container name:" + this.containerName);
         }else {
-            
+
             // In the Global instance case the containerName is empty
             this.containerName = "";
         }
         lbsLogger.info(configManager.toString());
     }
-    
+
     /**
      * Function called by the dependency manager when at least one
      * dependency become unsatisfied or when the component is shutting
@@ -426,106 +426,106 @@ public class LoadBalancerService implements IListenDataPacket, IConfigManager{
 
     /*
      * All the methods below are just proxy methods to direct the REST API requests to configuration
-     * manager. We need this redirection as currently, opendaylight supports only one 
-     * implementation of the service. 
+     * manager. We need this redirection as currently, opendaylight supports only one
+     * implementation of the service.
      */
     @Override
     public Set<VIP> getAllVIPs() {
         return configManager.getAllVIPs();
     }
-    
+
     @Override
     public boolean vipExists(String name, String ip, String protocol,
                                 short protocolPort, String poolName) {
         return configManager.vipExists(name, ip, protocol, protocolPort, poolName);
     }
-    
+
     @Override
     public boolean vipExists(VIP vip) {
         return configManager.vipExists(vip);
     }
-    
+
     @Override
     public VIP createVIP(String name, String ip, String protocol,
                             short protocolPort, String poolName) {
         return configManager.createVIP(name, ip, protocol, protocolPort, poolName);
     }
-    
+
     @Override
     public VIP updateVIP(String name, String poolName) {
         return configManager.updateVIP(name, poolName);
     }
-    
+
     @Override
     public VIP deleteVIP(String name) {
         return configManager.deleteVIP(name);
     }
-    
+
     @Override
     public boolean memberExists(String name, String memberIP, String poolName) {
         return configManager.memberExists(name, memberIP, poolName);
     }
-    
+
     @Override
     public Set<PoolMember> getAllPoolMembers(String poolName) {
-        
+
         return configManager.getAllPoolMembers(poolName);
     }
-    
+
     @Override
-    public PoolMember addPoolMember(String name, 
+    public PoolMember addPoolMember(String name,
                                     String memberIP,
                                     String poolName) {
         return configManager.addPoolMember(name, memberIP, poolName);
     }
-    
+
     @Override
     public PoolMember removePoolMember(String name, String poolName) {
-        
+
         return configManager.removePoolMember(name, poolName);
     }
-    
+
     @Override
     public Set<Pool> getAllPools() {
-        
+
         return configManager.getAllPools();
     }
-    
+
     @Override
     public Pool getPool(String poolName) {
         return configManager.getPool(poolName);
     }
-    
+
     @Override
     public boolean poolExists(String name, String lbMethod) {
         return configManager.poolExists(name, lbMethod);
     }
-    
+
     @Override
     public Pool createPool(String name, String lbMethod) {
         return configManager.createPool(name, lbMethod);
     }
-    
+
     @Override
     public Pool deletePool(String poolName) {
         return configManager.deletePool(poolName);
     }
-    
+
     @Override
     public boolean vipExists(String name) {
         return configManager.vipExists(name);
     }
-    
+
     @Override
     public boolean memberExists(String name, String poolName) {
         return configManager.memberExists(name, poolName);
     }
-    
+
     @Override
     public boolean poolExists(String name) {
         return configManager.poolExists(name);
     }
-    
+
     @Override
     public String getVIPAttachedPool(String name) {
         return configManager.getVIPAttachedPool(name);
index d69c63c20081a47e9c654bdeb29b3febccc0806e..f9562d6c523b10da5723f2a6efba3b2798be2a79 100644 (file)
@@ -14,16 +14,16 @@ import org.opendaylight.controller.samples.loadbalancer.entities.VIP;
  * All new load balancer policies must implement this interface.
  */
 public interface ILoadBalancingPolicy {
-    
+
     /**
      * Returns IP address of the next pool member from the pool
      * to which the load balancer service can direct incoming packets.
      * @param source    source on the packet
      * @param dest      virtual IP (VIP) that is used as destination on the packet
-     * @return IP address of the next pool member which will serve
+     * @return  IP address of the next pool member which will serve
      *          all incoming traffic destined for the given VIP and with the given source
      *          information
      */
     public String getPoolMemberForClient(Client source, VIP dest);
-    
+
 }
\ No newline at end of file
index b4b616f3a8027571ad173533b7c79a0b55bd7d82..ba5d5babb6d117e47fbb8413ae13e8e6c19c4cf2 100644 (file)
@@ -24,31 +24,31 @@ import org.slf4j.LoggerFactory;
  *
  */
 public class RandomLBPolicy implements ILoadBalancingPolicy {
-    
+
     /*
      * Instance logger
      */
     private static final Logger rLogger = LoggerFactory.getLogger(RandomLBPolicy.class);
-    
+
     /*
-     * Reference to the configuration manager. This reference is passed from load balancer 
+     * Reference to the configuration manager. This reference is passed from load balancer
      * class.
      */
     private ConfigManager cmgr;
-    
+
     /*
      * Mapping between the client and the pool member that serves all traffic for that client.
      */
     private HashMap<Client, PoolMember> clientMemberMap;
-    
+
     /*
      * Random generator
      */
     Random randomGenerator = null;
-    
+
     @SuppressWarnings("unused")
     private RandomLBPolicy(){}
-    
+
     public RandomLBPolicy(ConfigManager cmgr){
         this.cmgr = cmgr;
         this.clientMemberMap = new HashMap<Client, PoolMember>();
@@ -56,13 +56,13 @@ public class RandomLBPolicy implements ILoadBalancingPolicy {
     }
     @Override
     public String getPoolMemberForClient(Client source, VIP dest){
-        
+
         rLogger.info("Received traffic from client : {} for VIP : {} ",source, dest);
-        
+
         syncWithLoadBalancerData();
-        
+
         PoolMember pm= null;
-        
+
         if(this.clientMemberMap.containsKey(source)){
             pm= this.clientMemberMap.get(source);
             rLogger.info("Client {} had sent traffic before,new traffic will be routed to the same pool member {}",source,pm);
@@ -76,7 +76,7 @@ public class RandomLBPolicy implements ILoadBalancingPolicy {
         }
         return pm.getIp();
     }
-    
+
     /*
      * This method does the clean up. Whenever a new client packet arrives with a given VIP,
      * this method checks the current configuration to see if any pool members have been deleted and
@@ -84,25 +84,25 @@ public class RandomLBPolicy implements ILoadBalancingPolicy {
      */
     private void syncWithLoadBalancerData(){
         rLogger.debug("[Client - PoolMember] table before cleanup : {}",this.clientMemberMap.toString());
-        
+
         ArrayList<Client> removeClient = new ArrayList<Client>();
-        
+
         if(this.clientMemberMap.size() != 0){
             for(Client client : this.clientMemberMap.keySet()){
-                
+
                 if(!this.cmgr.memberExists(this.clientMemberMap.get(client).getName(),
                                                 this.clientMemberMap.get(client).getPoolName())){
                     removeClient.add(client);
                 }
             }
         }
-        
+
         for(Client client : removeClient){
             this.clientMemberMap.remove(client);
-            
+
             rLogger.debug("Removed client : {} ",client);
         }
         rLogger.debug("[Client - PoolMember] table after cleanup : {}",this.clientMemberMap.toString());
     }
-    
+
 }
index f1011dddc5fdf6f054db30603b1f60b0a7a35a50..c8687883e7e08cc0711a4d53a34762471fe06bb0 100644 (file)
@@ -23,23 +23,23 @@ import org.slf4j.LoggerFactory;
  *
  */
 public class RoundRobinLBPolicy implements ILoadBalancingPolicy{
-    
+
     /*
      * Logger instance
      */
     private static final Logger rrLogger = LoggerFactory.getLogger(RoundRobinLBPolicy.class);
-    
+
     /*
-     * Reference to the configuration manager. This reference is passed from load balancer 
+     * Reference to the configuration manager. This reference is passed from load balancer
      * class.
      */
     private ConfigManager cmgr;
-    
+
     /*
      * Mapping between the client and the pool member that serves all traffic for that client.
      */
     private HashMap<Client, PoolMember> clientMemberMap;
-    
+
     /*
      * Maintains the next pool member counter for the VIPs.
      * More than one VIP can be attached to one pool, so each VIP
@@ -47,34 +47,34 @@ public class RoundRobinLBPolicy implements ILoadBalancingPolicy{
      * the same pool.
      */
     private HashMap<VIP,Integer> nextItemFromPool;
-    
+
     @SuppressWarnings("unused")
     private RoundRobinLBPolicy(){}
-    
+
     public RoundRobinLBPolicy(ConfigManager cmgr){
         this.cmgr = cmgr;
         this.clientMemberMap = new HashMap<Client, PoolMember>();
         this.nextItemFromPool = new HashMap<VIP, Integer>();
     }
-    
+
     @Override
     public String getPoolMemberForClient(Client source, VIP dest){
-        
+
         rrLogger.info("Received traffic from client : {} for VIP : {} ",source, dest);
-        
+
         syncWithLoadBalancerData();
-        
+
         PoolMember pm= null;
-        
+
         if(this.clientMemberMap.containsKey(source)){
-            
+
             pm= this.clientMemberMap.get(source);
             rrLogger.info("Client {} had sent traffic before,new traffic will be routed to the same pool member {}",source,pm);
         }else{
-            
+
             Pool pool = null;
             if(nextItemFromPool.containsKey(dest)){
-                
+
                 int memberNum = nextItemFromPool.get(dest).intValue();
                 rrLogger.debug("Packet is from new client for VIP {}",dest);
                 pool = this.cmgr.getPool(dest.getPoolName());
@@ -82,19 +82,19 @@ public class RoundRobinLBPolicy implements ILoadBalancingPolicy{
                 this.clientMemberMap.put(source, pm );
                 rrLogger.info("New client's packet will be directed to pool member {}",pm);
                 memberNum++;
-                
+
                 if(memberNum > pool.getAllMembers().size()-1){
                     memberNum = 0;
                 }
                 rrLogger.debug("Next pool member for new client of VIP is set to {}",pool.getAllMembers().get(memberNum));
-                
+
                 this.nextItemFromPool.put(dest, new Integer(memberNum));
             }else{
                 rrLogger.debug("Network traffic for VIP : {} has appeared first time from client {}",dest,source);
                 pool = this.cmgr.getPool(dest.getPoolName());
                 pm = pool.getAllMembers().get(0);
                 this.clientMemberMap.put(source, pm);
-                
+
                 rrLogger.info("Network traffic from client {} will be directed to pool member {}",pm);
                 this.nextItemFromPool.put(dest, new Integer(1));
                 rrLogger.debug("Next pool member for new client of VIP is set to {}",pool.getAllMembers().get(1));
@@ -102,7 +102,7 @@ public class RoundRobinLBPolicy implements ILoadBalancingPolicy{
         }
         return pm.getIp();
     }
-    
+
     /*
      * This method does the clean up. Whenever a new client packet arrives with a given VIP,
      * this method checks the current configuration to see if any pool members have been deleted and
@@ -111,43 +111,43 @@ public class RoundRobinLBPolicy implements ILoadBalancingPolicy{
     private void syncWithLoadBalancerData(){
         rrLogger.debug("[Client - PoolMember] table before cleanup : {}",this.clientMemberMap.toString());
         ArrayList<Client> removeClient = new ArrayList<Client>();
-        
+
         if(this.clientMemberMap.size() != 0){
             for(Client client : this.clientMemberMap.keySet()){
                 if(!this.cmgr.memberExists(this.clientMemberMap.get(client).getName(),
                                             this.clientMemberMap.get(client).getPoolName())){
-                    
+
                     removeClient.add(client);
                 }
             }
         }
-        
+
         for(Client client : removeClient){
             this.clientMemberMap.remove(client);
-            
+
             rrLogger.debug("Removed client : {} ",client);
         }
         rrLogger.debug("[Client - PoolMember] table after cleanup : {}",this.clientMemberMap.toString());
-        
+
         rrLogger.debug("[VIP- NextMember] table before cleanup : {}",this.nextItemFromPool.toString());
-        
+
         ArrayList<VIP> resetVIPPoolMemberCount= new ArrayList<VIP>();
-        
+
         if(this.nextItemFromPool.size() != 0){
-            
+
             for(VIP vip:this.nextItemFromPool.keySet()){
                 if(this.nextItemFromPool.get(vip).intValue() > this.cmgr.getPool(vip.getPoolName()).getAllMembers().size()-1){
-                    
+
                     resetVIPPoolMemberCount.add(vip);
                 }
             }
         }
-        
+
         for(VIP vip:resetVIPPoolMemberCount){
             rrLogger.debug("VIP next pool member counter reset to 0");
             this.nextItemFromPool.put(vip, new Integer(0));
         }
-        
+
         rrLogger.debug("[VIP- NextMember] table after cleanup : {}",this.nextItemFromPool.toString());
     }
 }
index f8633b9ef839d20ed8123e0f60b08481b79bef6f..45d041c3e1e02533251ff672da2f0908a4da46a9 100644 (file)
@@ -20,7 +20,7 @@ import org.opendaylight.controller.samples.loadbalancer.policies.RoundRobinLBPol
 import junit.framework.TestCase;\r
 \r
 /**\r
- * \r
+ *\r
  * Class to unit test the load balancing policies.\r
  *\r
  */\r
@@ -30,7 +30,7 @@ public class LoadBalancerTest extends TestCase {
         ConfigManager cm = null;\r
         cm = new ConfigManager();\r
         Assert.assertFalse(cm== null);\r
-        \r
+\r
         Pool pool = cm.createPool("TestPool","roundrobin");\r
         VIP vip = cm.createVIP("TestVIP","10.0.0.9","TCP",(short)5550,"TestPool");\r
         PoolMember host1 = new PoolMember("host1","10.0.0.1","TestPool");\r
@@ -40,7 +40,7 @@ public class LoadBalancerTest extends TestCase {
         PoolMember host5 = new PoolMember("host5","10.0.0.5","TestPool");\r
         PoolMember host6 = new PoolMember("host6","10.0.0.6","TestPool");\r
         PoolMember host7 = new PoolMember("host7","10.0.0.7","TestPool");\r
-        \r
+\r
         pool.addMember(host1);\r
         pool.addMember(host2);\r
         pool.addMember(host3);\r
@@ -49,20 +49,20 @@ public class LoadBalancerTest extends TestCase {
         pool.addMember(host6);\r
         pool.addMember(host7);\r
         pool.addVIP(vip);\r
-        \r
+\r
         Assert.assertTrue(cm.getAllPoolMembers("TestPool").size() == pool.getAllMembers().size());\r
-        \r
+\r
         RoundRobinLBPolicy rrp = new RoundRobinLBPolicy(cm);\r
-        \r
+\r
         Client c1 = new Client("10.0.0.1","TCP",(short)5000);\r
         Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host1.getIp()));\r
-        \r
+\r
         c1 = new Client("10.0.0.1","TCP",(short)5001);\r
         Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host2.getIp()));\r
-        \r
+\r
         c1 = new Client("10.0.0.1","TCP",(short)5002);\r
         Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host3.getIp()));\r
-        \r
+\r
         c1 = new Client("10.0.0.1","TCP",(short)5003);\r
         Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host4.getIp()));\r
     }\r
index e666af7e512a72ae1c11005274436df16316a8d0..13ec7ca5ecdadfd1dfd95029b6d656119f1c12f3 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <enunciate label="full" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://enunciate.codehaus.org/schemas/enunciate-1.26.xsd">
-  
+
   <services>
     <rest defaultRestSubcontext="/one/nb/v2/lb"/>
   </services>
index 4ec567c95b5dff139b8713d06fb7a3997de8c838..8ea0d78360427f4b683a579d8ff117468e530941 100644 (file)
@@ -41,38 +41,38 @@ import org.opendaylight.controller.samples.loadbalancer.IConfigManager;
 /**
  * This class exposes North bound REST APIs for the Load Balancer Service.
  * Following APIs are exposed by the Load Balancer Service:
- * 
+ *
  * Data retrieval REST APIs::
- *     1. Get details of all existing pools
- *             Type : GET  
- *             URI : /one/nb/v2/lb/{container-name}/
- *     NOTE: Current implementation of the opendaylight usage 'default' as a container-name
- *     e.g : http://localhost:8080/one/nb/v2/lb/default will give you list of all the pools
- *     
- *     2. Get details of all the existing VIPs
- *             Type : GET
- *             URI:  /one/nb/v2/lb/{container-name}/vips
- * 
+ *      1. Get details of all existing pools
+ *              Type : GET
+ *              URI : /one/nb/v2/lb/{container-name}/
+ *      NOTE: Current implementation of the opendaylight usage 'default' as a container-name
+ *      e.g : http://localhost:8080/one/nb/v2/lb/default will give you list of all the pools
+ *
+ *      2. Get details of all the existing VIPs
+ *              Type : GET
+ *              URI:  /one/nb/v2/lb/{container-name}/vips
+ *
  * Pool related REST APIs::
- *     1. Create Pool : 
- *             Type : POST
- *             URI : /one/nb/v2/lb/{container-name}/create/pool
- *             Request body :
+ *      1. Create Pool :
+ *              Type : POST
+ *              URI : /one/nb/v2/lb/{container-name}/create/pool
+ *              Request body :
  *                      {
  *                              "name":"",
  *                              "lbmethod":""
  *                      }
- *             Currently, two load balancing policies are allowed {"roundrobin" and "random" }
- * 
- *     2. Delete Pool : 
- *             Type : DELETE
- *             URI : /one/nb/v2/lb/{container-name}/delete/pool/{pool-name}
- * 
+ *              Currently, two load balancing policies are allowed {"roundrobin" and "random" }
+ *
+ *      2. Delete Pool :
+ *              Type : DELETE
+ *              URI : /one/nb/v2/lb/{container-name}/delete/pool/{pool-name}
+ *
  * VIP related REST APIs::
- *     1. Create VIP: 
- *             Type : POST
- *             URI : /one/nb/v2/lb/{container-name}/create/vip
- *             Request body :
+ *      1. Create VIP:
+ *              Type : POST
+ *              URI : /one/nb/v2/lb/{container-name}/create/vip
+ *              Request body :
  *                      {
  *                              "name":"",
  *                              "ip":"ip in (xxx.xxx.xxx.xxx) format",
@@ -80,12 +80,12 @@ import org.opendaylight.controller.samples.loadbalancer.IConfigManager;
  *                              "port":"any valid port number",
  *                              "poolname":"" (optional)
  *                       }
- *             The pool name is optional and can be set up at a later stage (using the REST API given below).
- * 
- *     2. Update VIP: Update pool name of the VIP
- *             Type : PUT
- *             URI : /one/nb/v2/lb/{container-name}/update/vip
- *             Request body :
+ *              The pool name is optional and can be set up at a later stage (using the REST API given below).
+ *
+ *      2. Update VIP: Update pool name of the VIP
+ *              Type : PUT
+ *              URI : /one/nb/v2/lb/{container-name}/update/vip
+ *              Request body :
  *                      {
  *                              "name":"",
  *                              "poolname":""
@@ -94,34 +94,34 @@ import org.opendaylight.controller.samples.loadbalancer.IConfigManager;
  *              and not of the VIP name itself.
  *              The specified pool name must already exist. If the specified VIP is already attached to a pool, the update
  *              will fail.
- * 
- *     3. Delete VIP : 
- *             Type : DELETE
- *             URI : /one/nb/v2/lb/{container-name}/delete/vip/{vip-name} 
- * 
+ *
+ *      3. Delete VIP :
+ *              Type : DELETE
+ *              URI : /one/nb/v2/lb/{container-name}/delete/vip/{vip-name}
+ *
  * Pool member related REST APIs::
- *     1. Create pool member:
- *             Type : POST
- *             URI : /one/nb/v2/lb/default/create/poolmember
- *             Request body :
+ *      1. Create pool member:
+ *              Type : POST
+ *              URI : /one/nb/v2/lb/default/create/poolmember
+ *              Request body :
  *                      {
  *                              "name":"",
  *                              "ip":"ip in (xxx.xxx.xxx.xxx) format",
  *                              "poolname":"existing pool name"
  *                       }
- * 
- *     2. Delete pool member:
- *             Type : DELETE
- *             URI     : /one/nb/v2/lb/{container-name}/delete/poolmember/{pool-member-name}/{pool-name}
- *     
- *     NOTE: Property "name" of each individual entity must be unique. 
- *     All the above REST APIs throw appropriate response codes in case of error/success. 
- *     Please consult the respective methods to get details of various response codes.
+ *
+ *      2. Delete pool member:
+ *              Type : DELETE
+ *              URI : /one/nb/v2/lb/{container-name}/delete/poolmember/{pool-member-name}/{pool-name}
+ *
+ *  NOTE: Property "name" of each individual entity must be unique.
+ *  All the above REST APIs throw appropriate response codes in case of error/success.
+ *  Please consult the respective methods to get details of various response codes.
  */
 
 @Path("/")
 public class LoadBalancerNorthbound {
-    
+
     /*
      * Method returns the Load balancer service instance running within
      * 'default' container.
@@ -148,7 +148,7 @@ public class LoadBalancerNorthbound {
         }
 
         IConfigManager configManager = (IConfigManager) ServiceHelper.getInstance(
-                       IConfigManager.class, containerName, this);
+                        IConfigManager.class, containerName, this);
 
         if (configManager == null) {
             throw new ServiceUnavailableException("Load Balancer"
@@ -168,13 +168,13 @@ public class LoadBalancerNorthbound {
         @ResponseCode(code = 503, condition = "Load balancer service is unavailable") })
     public Pools getAllPools(
             @PathParam("containerName") String containerName) {
-        
+
         IConfigManager configManager = getConfigManagerService(containerName);
         if (configManager == null) {
             throw new ServiceUnavailableException("Load Balancer "
                                                     + RestMessages.SERVICEUNAVAILABLE.toString());
         }
-        
+
         return new Pools(configManager.getAllPools());
     }
 
@@ -188,7 +188,7 @@ public class LoadBalancerNorthbound {
         @ResponseCode(code = 503, condition = "Load balancer service is unavailable") })
     public VIPs getAllVIPs(
             @PathParam("containerName") String containerName) {
-        
+
         IConfigManager configManager = getConfigManagerService(containerName);
         if (configManager == null) {
             throw new ServiceUnavailableException("Load Balancer "
@@ -209,7 +209,7 @@ public class LoadBalancerNorthbound {
         @ResponseCode(code = 415, condition = "Invalid input data")})
     public Response addVIP(@PathParam("containerName") String containerName,
             @TypeHint(VIP.class) JAXBElement<VIP> inVIP){
-        
+
         VIP vipInput = inVIP.getValue();
         String name = vipInput.getName();
         String ip = vipInput.getIp();
@@ -222,16 +222,16 @@ public class LoadBalancerNorthbound {
                 protocolPort < 0 ){
             throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
         }
-        
+
         IConfigManager configManager = getConfigManagerService(containerName);
-        
+
         if (configManager == null) {
             throw new ServiceUnavailableException("Load Balancer "
                     + RestMessages.SERVICEUNAVAILABLE.toString());
         }
-        
+
         if(!configManager.vipExists(name, ip, protocol, protocolPort, poolName)){
-            
+
             VIP vip = configManager.createVIP(name, ip, protocol, protocolPort, poolName);
             if ( vip != null){
                 return Response.status(Response.Status.CREATED).build();
@@ -254,7 +254,7 @@ public class LoadBalancerNorthbound {
         @ResponseCode(code = 415, condition = "Invalid input name")})
     public Response updateVIP(@PathParam("containerName") String containerName,
             @TypeHint(VIP.class) JAXBElement<VIP> inVIP) {
-        
+
         VIP vipInput = inVIP.getValue();
         String name = vipInput.getName();
         String poolName = vipInput.getPoolName();
@@ -262,25 +262,25 @@ public class LoadBalancerNorthbound {
                 poolName.isEmpty()){
             throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
         }
-        
+
         IConfigManager configManager = getConfigManagerService(containerName);
         if (configManager == null) {
             throw new ServiceUnavailableException("Load Balancer "
                                                 + RestMessages.SERVICEUNAVAILABLE.toString());
         }
-        
+
         if(!configManager.poolExists(poolName))
             throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND);
-        
+
         if(configManager.getVIPAttachedPool(name)!=null)
             throw new MethodNotAllowedException(NBConst.RES_VIP_POOL_EXIST);
-        
+
         if(configManager.updateVIP(name, poolName)!= null)
             return Response.status(Response.Status.ACCEPTED).build();
-        
+
         throw new InternalServerErrorException(NBConst.RES_VIP_UPDATE_FAILED);
     }
-    
+
     @Path("/{containerName}/delete/vip/{vipName}")
     @DELETE
     @Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@@ -293,19 +293,19 @@ public class LoadBalancerNorthbound {
     public Response deleteVIP(
             @PathParam(value = "containerName") String containerName,
             @PathParam(value = "vipName") String vipName) {
-        
+
         if(vipName.isEmpty())
             throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
-        
+
         IConfigManager configManager = getConfigManagerService(containerName);
         if (configManager == null) {
             throw new ServiceUnavailableException("Load Balancer"
                                             + RestMessages.SERVICEUNAVAILABLE.toString());
         }
-        
+
         if(!configManager.vipExists(vipName))
             throw new ResourceNotFoundException(NBConst.RES_VIP_NOT_FOUND);
-        
+
         for(VIP vip : configManager.getAllVIPs()){
             if(vip.getName().equals(vipName)){
                 configManager.deleteVIP(vipName);
@@ -326,7 +326,7 @@ public class LoadBalancerNorthbound {
         @ResponseCode(code = 415, condition = "Invalid input data")})
     public Response addPool(@PathParam("containerName") String containerName,
             @TypeHint(Pool.class) JAXBElement<Pool> inPool) {
-        
+
         Pool poolInput = inPool.getValue();
         String name = poolInput.getName();
         String lbMethod =poolInput.getLbMethod();
@@ -334,15 +334,15 @@ public class LoadBalancerNorthbound {
                 lbMethod.isEmpty()){
             throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
         }
-        
+
         IConfigManager configManager = getConfigManagerService(containerName);
         if (configManager == null) {
             throw new ServiceUnavailableException("Load Balancer "
                                             + RestMessages.SERVICEUNAVAILABLE.toString());
         }
-        
+
         if(!configManager.poolExists(name)){
-            
+
             Pool pool = configManager.createPool(name, lbMethod);
             if ( pool != null){
                 return Response.status(Response.Status.CREATED).build();
@@ -365,19 +365,19 @@ public class LoadBalancerNorthbound {
     public Response deletePool(
             @PathParam(value = "containerName") String containerName,
             @PathParam(value = "poolName") String poolName) {
-        
+
         if(poolName.isEmpty())
             throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
-        
+
         IConfigManager configManager = getConfigManagerService(containerName);
         if (configManager == null) {
             throw new ServiceUnavailableException("Load Balancer"
                                         + RestMessages.SERVICEUNAVAILABLE.toString());
         }
-        
+
         if(!configManager.poolExists(poolName))
             throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND);
-        
+
         for(Pool pool:configManager.getAllPools()){
             if(pool.getName().equals(poolName)){
                 configManager.deletePool(poolName);
@@ -399,37 +399,37 @@ public class LoadBalancerNorthbound {
         @ResponseCode(code = 415, condition = "Invalid input data")})
     public Response addPoolMember(@PathParam("containerName") String containerName,
             @TypeHint(PoolMember.class) JAXBElement<PoolMember> inPoolMember){
-        
+
         PoolMember pmInput = inPoolMember.getValue();
-       String name = pmInput.getName();
-       String memberIP = pmInput.getIp();
-       String poolName = pmInput.getPoolName();
-       
-       if(name.isEmpty() ||
-               memberIP.isEmpty()||
-               poolName.isEmpty()){
-           throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
-       }
-       
-       IConfigManager configManager = getConfigManagerService(containerName);
-       if (configManager == null) {
-           throw new ServiceUnavailableException("Load Balancer "
-                                       + RestMessages.SERVICEUNAVAILABLE.toString());
-       }
-       
-       if(!configManager.poolExists(poolName))
-           throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND);
-       
-       if(!configManager.memberExists(name, memberIP, poolName)){
-           
-           PoolMember poolMember = configManager.addPoolMember(name, memberIP, poolName);
-           if ( poolMember != null){
-               return Response.status(Response.Status.CREATED).build();
-           }
-       }else{
-           throw new ResourceConflictException(NBConst.RES_POOLMEMBER_ALREADY_EXIST);
-       }
-       throw new InternalServerErrorException(NBConst.RES_POOLMEMBER_CREATION_FAILED);
+        String name = pmInput.getName();
+        String memberIP = pmInput.getIp();
+        String poolName = pmInput.getPoolName();
+
+        if(name.isEmpty() ||
+                memberIP.isEmpty()||
+                poolName.isEmpty()){
+            throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
+        }
+
+        IConfigManager configManager = getConfigManagerService(containerName);
+        if (configManager == null) {
+            throw new ServiceUnavailableException("Load Balancer "
+                                        + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+
+        if(!configManager.poolExists(poolName))
+            throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND);
+
+        if(!configManager.memberExists(name, memberIP, poolName)){
+
+            PoolMember poolMember = configManager.addPoolMember(name, memberIP, poolName);
+            if ( poolMember != null){
+                return Response.status(Response.Status.CREATED).build();
+            }
+        }else{
+            throw new ResourceConflictException(NBConst.RES_POOLMEMBER_ALREADY_EXIST);
+        }
+        throw new InternalServerErrorException(NBConst.RES_POOLMEMBER_CREATION_FAILED);
     }
 
     @Path("/{containerName}/delete/poolmember/{poolMemberName}/{poolName}")
@@ -445,25 +445,25 @@ public class LoadBalancerNorthbound {
             @PathParam(value = "containerName") String containerName,
             @PathParam(value = "poolMemberName") String poolMemberName,
             @PathParam(value = "poolName") String poolName) {
-        
+
         if(poolMemberName.isEmpty()||
                 poolName.isEmpty())
             throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString());
-        
+
         IConfigManager configManager = getConfigManagerService(containerName);
-        
+
         if (configManager == null) {
             throw new ServiceUnavailableException("Load Balancer"
                                         + RestMessages.SERVICEUNAVAILABLE.toString());
         }
-        
+
         if(!configManager.poolExists(poolName))
             throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND);
-        
+
         if(configManager.memberExists(poolMemberName, poolName)){
-            
+
             configManager.removePoolMember(poolMemberName, poolName);
-            
+
             return Response.ok().build();
         }
         throw new ResourceNotFoundException(NBConst.RES_POOLMEMBER_NOT_FOUND);
index 4aa4705a53755407aa27709a94dc07d385b6cb84..a5d2091470b46aeae9a00e3f9790c06cfae25af2 100644 (file)
@@ -12,32 +12,32 @@ package org.opendaylight.controller.samples.loadbalancer.northbound;
  *
  */
 public class NBConst {
-    
+
     public static final String RES_VIP_ALREADY_EXIST= " VIP already exists";
-    
+
     public static final String RES_VIP_NOT_FOUND= " VIP not found";
-    
+
     public static final String RES_VIP_CREATION_FAILED = " Creation of VIP failed";
-    
+
     public static final String RES_VIP_DELETION_FAILED = " Deletion of VIP failed";
-    
+
     public static final String RES_VIP_UPDATE_FAILED = " Update of VIP failed";
-    
+
     public static final String RES_POOL_ALREADY_EXIST= " Pool already exists";
-    
+
     public static final String RES_POOL_NOT_FOUND= " Pool not found";
-    
+
     public static final String RES_POOL_CREATION_FAILED = " Creation of pool failed";
-    
+
     public static final String RES_POOL_DELETION_FAILED = " Deletion of pool failed";
-    
+
     public static final String RES_POOLMEMBER_ALREADY_EXIST= " Pool member already exists";
-    
+
     public static final String RES_POOLMEMBER_NOT_FOUND= " Pool member not found";
-    
+
     public static final String RES_POOLMEMBER_CREATION_FAILED = " Creation of pool member failed";
-    
+
     public static final String RES_POOLMEMBER_DELETION_FAILED = " Deletion of pool member failed";
-    
+
     public static final String RES_VIP_POOL_EXIST = "Pool already attached to a VIP";
 }
index abb5495cbf7c6d19c0209d510a42695bc9b95946..74be568018af3c5123f8b96c89ee73cd146940c9 100644 (file)
@@ -19,29 +19,29 @@ import org.opendaylight.controller.samples.loadbalancer.entities.Pool;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 /**
- * JAX-RS resource for handling details of all the available pools 
+ * JAX-RS resource for handling details of all the available pools
  * in response to respective REST API requests.
  */
 
 public class Pools {
-    
+
     @XmlElement (name="pool")
     Set<Pool> loadBalancerPools;
-    
+
     public Pools() {
     }
-    
+
     public Pools (Set<Pool> loadBalancerPools) {
         this.loadBalancerPools = loadBalancerPools;
     }
-    
+
     /**
      * @return the loadBalancerPools
      */
     public Set<Pool> getLoadBalancerPools() {
         return loadBalancerPools;
     }
-    
+
     /**
      * @param loadBalancerPools the loadBalancerPools to set
      */
index f0af929b39aed15becefb996efe2a5806b398557..66a20338abffd2ef2ebd0ddfc440ccce2be6e3ba 100644 (file)
@@ -25,28 +25,28 @@ import org.opendaylight.controller.samples.loadbalancer.entities.VIP;
 @XmlAccessorType(XmlAccessType.NONE)
 
 public class VIPs {
-    
+
     @XmlElement (name="vip")
     Set<VIP> loadBalancerVIPs;
-    
+
     public VIPs() {}
-    
-    
+
+
     public VIPs (Set<VIP> loadBalancerVIPs) {
         this.loadBalancerVIPs = loadBalancerVIPs;
     }
-    
+
     /**
      * @return the loadBalancerVIPs
      */
     public Set<VIP> getLoadBalancerVIPs() {
         return loadBalancerVIPs;
     }
-    
+
     /**
      * @param loadBalancerVIPs the loadBalancerVIPs to set
      */
-    
+
     public void setLoadBalancerVIPs(Set<VIP> loadBalancerVIPs) {
         this.loadBalancerVIPs = loadBalancerVIPs;
     }
index 365e4b22d6493a194ce273adc12b846ff1445606..aac4647de669a930dbd0ffa39d30130434946054 100644 (file)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
   <servlet>
     <servlet-name>JAXRSLoadBalancer</servlet-name>
     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
     <url-pattern>/*</url-pattern>
   </servlet-mapping>
 
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>NB api</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>NB api</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
-       <login-config>
-               <auth-method>BASIC</auth-method>
-               <realm-name>opendaylight</realm-name>
-       </login-config>
+        <login-config>
+                <auth-method>BASIC</auth-method>
+                <realm-name>opendaylight</realm-name>
+        </login-config>
 </web-app>
index c2fee970ac00c8354140de8318786cd0bfcac7c4..11056478dbf1742ec48e5cc6bbf9ec3bf01ad56a 100644 (file)
@@ -147,7 +147,7 @@ public class SimpleForwardingImpl implements IfNewHostNotify,
     }
 
     @SuppressWarnings("deprecation")
-       private void allocateCaches() {
+        private void allocateCaches() {
         if (this.clusterContainerService == null) {
             log.info("un-initialized clusterContainerService, can't create cache");
             return;
@@ -178,7 +178,7 @@ public class SimpleForwardingImpl implements IfNewHostNotify,
     }
 
     @SuppressWarnings("deprecation")
-       private void destroyCaches() {
+        private void destroyCaches() {
         if (this.clusterContainerService == null) {
             log.info("un-initialized clusterContainerService, can't destroy cache");
             return;
@@ -367,7 +367,7 @@ public class SimpleForwardingImpl implements IfNewHostNotify,
                 }
 
             } else {
-                log.debug("Adding policyMatch(DIP = {}) Action(outPort= {}) " + 
+                log.debug("Adding policyMatch(DIP = {}) Action(outPort= {}) " +
                         "to node {}", new Object[] {
                         host.getNetworkAddress().getHostAddress(), outPort,
                         currNode});
@@ -482,7 +482,7 @@ public class SimpleForwardingImpl implements IfNewHostNotify,
         updatePerHostRuleInSW(host, rootNode, rootNode, null, new HostNodePair(
                 host, rootNode), ports);
 
-        //             log.debug("Getting out at the end!");
+        //      log.debug("Getting out at the end!");
         return switchesToProgram;
     }
 
@@ -575,10 +575,10 @@ public class SimpleForwardingImpl implements IfNewHostNotify,
         // rest of the world
         // switchesToProgram.add(rootNode);
         //updatePerHostRuleInSW(host, rootNode,
-        //                                       rootNode, null,
-        //                                       new HostNodePair(host, rootNode),ports);
+        //                                        rootNode, null,
+        //                                        new HostNodePair(host, rootNode),ports);
 
-        //             log.debug("Getting out at the end!");
+        //      log.debug("Getting out at the end!");
         return switchesToProgram;
     }
 
@@ -617,7 +617,7 @@ public class SimpleForwardingImpl implements IfNewHostNotify,
                     Status poStatus = this.frm.installFlowEntry(po);
                     if (!poStatus.isSuccess()) {
                         log.error("Failed to install policy: "
-                                + po.getGroupName() + " (" 
+                                + po.getGroupName() + " ("
                                 + poStatus.getDescription() + ")");
 
                         retCode = RulesProgrammingReturnCode.FAILED_FEW_SWITCHES;
@@ -632,8 +632,8 @@ public class SimpleForwardingImpl implements IfNewHostNotify,
                               swId, host);
                     /* // Now dump every single rule */
                     /* for (HostNodePair dumpkey : this.rulesDB.keySet()) { */
-                    /*         po = this.rulesDB.get(dumpkey); */
-                    /*         log.debug("Dumping entry H{" + dumpkey.getHost() + "} S{" + dumpkey.getSwitchId() + "} = {" + (po == null ? "null policy" : po)); */
+                    /*  po = this.rulesDB.get(dumpkey); */
+                    /*  log.debug("Dumping entry H{" + dumpkey.getHost() + "} S{" + dumpkey.getSwitchId() + "} = {" + (po == null ? "null policy" : po)); */
                     /* } */
                 }
             }
index 7ee475ed2b01be2b8efb4c1eb0704c2816359f83..1bf1c7ca74785b890c2263d712bfa6232edf04a1 100644 (file)
@@ -29,7 +29,7 @@
               org.apache.felix.dm
             </Import-Package>
             <Export-Package>
-              org.opendaylight.controller.statisticsmanager 
+              org.opendaylight.controller.statisticsmanager
             </Export-Package>
           </instructions>
           <manifestLocation>${project.basedir}/META-INF</manifestLocation>
index 98977f6e91d15b6eee512d941365133cdb387697..a2ab07ac7b6bc7249f44ca1c66415c731faf738c 100644 (file)
@@ -31,7 +31,7 @@ public interface IStatisticsManager {
      * If the context is the default container, the returned statistics are for all the flows installed on the node,
      * regardless of the container they belong to
      *
-     * @param node     the network node
+     * @param node  the network node
      * @return the list of flows installed on the network node
      */
     List<FlowOnNode> getFlows(Node node);
@@ -40,7 +40,7 @@ public interface IStatisticsManager {
      * Returns the statistics for the flows specified in the list
      *
      * @param flows
-     * @return the list of flows installed on the network node
+     * @return  the list of flows installed on the network node
      */
     Map<Node, List<FlowOnNode>> getFlowStatisticsForFlowList(
             List<FlowEntry> flows);
index e7b8c59dffe896824e8862a6fd0ba723fb565ee9..29d0a42f85722d43707f166188809680fc81f04c 100644 (file)
@@ -23,11 +23,11 @@ public interface IInventoryListener {
     /**
      * This method is called when some properties of a node are added/deleted/changed.
      *
-     * @param node                     {@link org.opendaylight.controller.sal.core.Node} being updated
-     * @param type             {@link org.opendaylight.controller.sal.core.UpdateType}
-     * @param propMap          map of {@link org.opendaylight.controller.sal.core.Property} such as
-     *                                                 {@link org.opendaylight.controller.sal.core.Description} and/or
-     *                                                 {@link org.opendaylight.controller.sal.core.Tier} etc.
+     * @param node                      {@link org.opendaylight.controller.sal.core.Node} being updated
+     * @param type              {@link org.opendaylight.controller.sal.core.UpdateType}
+     * @param propMap           map of {@link org.opendaylight.controller.sal.core.Property} such as
+     *                                          {@link org.opendaylight.controller.sal.core.Description} and/or
+     *                                          {@link org.opendaylight.controller.sal.core.Tier} etc.
      */
     public void notifyNode(Node node, UpdateType type,
             Map<String, Property> propMap);
@@ -35,11 +35,11 @@ public interface IInventoryListener {
     /**
      * This method is called when some properties of a node connector are added/deleted/changed.
      *
-     * @param nodeConnector    {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
-     * @param type             {@link org.opendaylight.controller.sal.core.UpdateType}
-     * @param propMap          map of {@link org.opendaylight.controller.sal.core.Property} such as
-     *                                                 {@link org.opendaylight.controller.sal.core.Description} and/or
-     *                                                 {@link org.opendaylight.controller.sal.core.State} etc.
+     * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated
+     * @param type              {@link org.opendaylight.controller.sal.core.UpdateType}
+     * @param propMap           map of {@link org.opendaylight.controller.sal.core.Property} such as
+     *                                          {@link org.opendaylight.controller.sal.core.Description} and/or
+     *                                          {@link org.opendaylight.controller.sal.core.State} etc.
      */
     public void notifyNodeConnector(NodeConnector nodeConnector,
             UpdateType type, Map<String, Property> propMap);
index af1ab1cc7bfad197eb42e3575a033681357fc049..1e4a79fcc00a147a0b31a29bc08b5c07540705fb 100644 (file)
@@ -22,9 +22,9 @@ public interface ISpanAware {
     /**
      * This method is called when list of ports in a node are added/deleted as span ports.
      *
-     * @param node             {@link org.opendaylight.controller.sal.core.Node} being updated
-     * @param portList list of span {@link org.opendaylight.controller.sal.core.NodeConnector}
-     * @param add              true if add; false if delete.
+     * @param node      {@link org.opendaylight.controller.sal.core.Node} being updated
+     * @param portList  list of span {@link org.opendaylight.controller.sal.core.NodeConnector}
+     * @param add       true if add; false if delete.
      */
     public void spanUpdate(Node node, List<NodeConnector> portList, boolean add);
 }
\ No newline at end of file
index ddc5f8ffee2777cd098148e05abe0c2ee741e7ea..48f5aa48f61c579127fc1d5229dbd116e57cd70e 100644 (file)
@@ -44,7 +44,7 @@ public interface ISwitchManager {
     /**
      * Remove a subnet configuration
      *
-     * @param  configObject    refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig}
+     * @param  configObject refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig}
      * @return "Success" or failure reason
      */
     public Status removeSubnet(SubnetConfig configObject);
@@ -53,14 +53,14 @@ public interface ISwitchManager {
      * Remove a subnet configuration given the name
      *
      * @param   name      subnet name
-     * @return "Success" or failure reason
+     * @return  "Success" or failure reason
      */
     public Status removeSubnet(String name);
 
     /**
      * Return a list of all known devices in the system
      *
-     * @return returns a list of {@link org.opendaylight.controller.switchmanager.Switch}
+     * @return  returns a list of {@link org.opendaylight.controller.switchmanager.Switch}
      */
     public List<Switch> getNetworkDevices();
 
@@ -82,8 +82,8 @@ public interface ISwitchManager {
     /**
      * Return a subnet configuration given the network address
      *
-     * @param networkAddress   the ip address in long format
-     * @return                                         the {@link org.opendaylight.controller.switchmanager.Subnet}
+     * @param networkAddress    the ip address in long format
+     * @return                                  the {@link org.opendaylight.controller.switchmanager.Subnet}
      */
     public Subnet getSubnetByNetworkAddress(InetAddress networkAddress);
 
@@ -98,7 +98,7 @@ public interface ISwitchManager {
      * Add a span port configuration
      *
      * @param SpanConfig refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SpanConfig}
-     * @return                         status code
+     * @return              status code
      */
     public Status addSpanConfig(SpanConfig configObject);
 
@@ -106,7 +106,7 @@ public interface ISwitchManager {
      * Remove a span port configuration
      *
      * @param SpanConfig refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SpanConfig}
-     * @return                         status code
+     * @return              status code
      */
     public Status removeSpanConfig(SpanConfig cfgObject);
 
@@ -152,8 +152,8 @@ public interface ISwitchManager {
     /**
      * Remove node connectors from a subnet
      *
-     * @param name                             the subnet config name
-     * @param nodeConnectors   nodePorts string specified by {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig}
+     * @param name              the subnet config name
+     * @param nodeConnectors    nodePorts string specified by {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig}
      * @return "Success" or failure reason
      */
     public Status removePortsFromSubnet(String name, String nodeConnectors);
@@ -170,16 +170,16 @@ public interface ISwitchManager {
      *
      * @param node {@link org.opendaylight.controller.sal.core.Node}
      * @return map of {@link org.opendaylight.controller.sal.core.Property} such as
-     *            {@link org.opendaylight.controller.sal.core.Description} and/or
-     *                    {@link org.opendaylight.controller.sal.core.Tier} etc.
+     *             {@link org.opendaylight.controller.sal.core.Description} and/or
+     *             {@link org.opendaylight.controller.sal.core.Tier} etc.
      */
     public Map<String, Property> getNodeProps(Node node);
 
     /**
      * Return a specific property of a node given the property name
      *
-     * @param node             {@link org.opendaylight.controller.sal.core.Node}
-     * @param propName         the property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
+     * @param node              {@link org.opendaylight.controller.sal.core.Node}
+     * @param propName  the property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
      * @return {@link org.opendaylight.controller.sal.core.Property}
      */
     public Property getNodeProp(Node node, String propName);
@@ -187,23 +187,23 @@ public interface ISwitchManager {
     /**
      * Set a specific property of a node
      *
-     * @param node             {@link org.opendaylight.controller.sal.core.Node}
-     * @param prop             {@link org.opendaylight.controller.sal.core.Property}
+     * @param node              {@link org.opendaylight.controller.sal.core.Node}
+     * @param prop              {@link org.opendaylight.controller.sal.core.Property}
      */
     public void setNodeProp(Node node, Property prop);
 
     /**
      * Remove a property of a node
-     * 
-     * @param nc               {@link org.opendaylight.controller.sal.core.Node}
-     * @param propName         the property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
+     *
+     * @param nc                {@link org.opendaylight.controller.sal.core.Node}
+     * @param propName  the property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
      * @return success or failed reason
      */
     public Status removeNodeProp(Node node, String propName);
 
     /**
      * Remove all the properties of a node
-     * 
+     *
      * @param node {@link org.opendaylight.controller.sal.core.Node}
      * @return success or failed reason
      */
@@ -238,8 +238,8 @@ public interface ISwitchManager {
      *
      * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector}
      * @return map of {@link org.opendaylight.controller.sal.core.Property} such as
-     *                    {@link org.opendaylight.controller.sal.core.Description} and/or
-     *                    {@link org.opendaylight.controller.sal.core.State} etc.
+     *             {@link org.opendaylight.controller.sal.core.Description} and/or
+     *             {@link org.opendaylight.controller.sal.core.State} etc.
      */
     public Map<String, Property> getNodeConnectorProps(
             NodeConnector nodeConnector);
@@ -266,7 +266,7 @@ public interface ISwitchManager {
 
     /**
      * Remove a property of a node connector
-     * 
+     *
      * @param nc {@link org.opendaylight.controller.sal.core.NodeConnector}
      * @param propName property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
      * @return success or failed reason
@@ -275,7 +275,7 @@ public interface ISwitchManager {
 
     /**
      * Remove all the properties of a node connector
-     * 
+     *
      * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector}
      * @return success or failed reason
      */
@@ -284,7 +284,7 @@ public interface ISwitchManager {
     /**
      * Return the node connector given its name
      *
-     * @param node                             {@link org.opendaylight.controller.sal.core.Node}
+     * @param node                              {@link org.opendaylight.controller.sal.core.Node}
      * @param nodeConnectorName node connector identifier specified by {@link org.opendaylight.controller.sal.core.NodeConnector}
      * @return {@link org.opendaylight.controller.sal.core.NodeConnector}
      */
@@ -309,7 +309,7 @@ public interface ISwitchManager {
 
     /**
      * Return controller MAC address
-        *
+         *
      * @return MAC address in byte array
      */
     public byte[] getControllerMAC();
@@ -317,7 +317,7 @@ public interface ISwitchManager {
     /**
      * Return MAC address for a given node
      *
-     * @param node     {@link org.opendaylight.controller.sal.core.Node}
+     * @param node  {@link org.opendaylight.controller.sal.core.Node}
      * @return MAC address in byte array
      */
     public byte[] getNodeMAC(Node node);
@@ -338,22 +338,22 @@ public interface ISwitchManager {
      */
     public int getHostRetryCount();
 
-       /**
-        * Create a Name/Tier/Bandwidth Property object based on given property
-        * name and value. Other property types are not supported yet.
-        * 
+        /**
+         * Create a Name/Tier/Bandwidth Property object based on given property
+         * name and value. Other property types are not supported yet.
+         *
      * @param propName Name of the Property specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
      * @param propValue Value of the Property specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes
-        * @return {@link org.opendaylight.controller.sal.core.Property}
-        */
+         * @return {@link org.opendaylight.controller.sal.core.Property}
+         */
     public Property createProperty(String propName, String propValue);
-    
+
     /**
-     * Returns the description for the specified node. It is either the one 
+     * Returns the description for the specified node. It is either the one
      * configured by user or the description advertised by the node.
-     * 
+     *
      * @param node the network node identifier
-     * @return the description of the specified node. If no description is 
+     * @return the description of the specified node. If no description is
      * configured and the network node does not provide its description,
      * an empty string is returned.
      */
index eae01a6487cd5351783eb0e24292a3e947a9da7d..a665096e8b529ee54e7b851c566a04aaddb51b7b 100644 (file)
@@ -16,9 +16,9 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.utils.HexEncode;
 
 /**
  * The class describes switch related information including L2 address, ports,
@@ -164,6 +164,8 @@ public class Switch implements Serializable {
 
     @Override
     public String toString() {
-        return "Switch[" + ReflectionToStringBuilder.toString(this) + "]";
+        return "Switch [dataLayerAddress=" + HexEncode.bytesToHexStringFormat(dataLayerAddress)
+                + ", nodeConnectors=" + nodeConnectors + ", spanPorts="
+                + spanPorts + ", node=" + node + "]";
     }
 }
index 778310e07ff6a4d7879ed8e26e33cf7e9976901b..253096edc34116ed4cc9474624f9711f90efa13a 100644 (file)
@@ -47,9 +47,9 @@ public class SwitchConfig implements Serializable {
     }
 
     public boolean isProactive() {
-       return Integer.parseInt(mode) != 0;
+        return Integer.parseInt(mode) != 0;
     }
-    
+
     public static long getSerialversionuid() {
         return serialVersionUID;
     }
index 1499f9e2ef345c3b5a39350c95eb23cb0f1e7262..18b3195372ff2f6f42a97c277b6d507be4d4dc33 100644 (file)
@@ -119,23 +119,23 @@ public class SwitchTest {
         Assert.assertTrue(sw.getSpanPorts().isEmpty());
 
     }
-    
+
     @Test
     public void testSwitchConfig(){
         SwitchConfig sc = new SwitchConfig(null, null, null, null);
         SwitchConfig sc2 = new SwitchConfig(null, null, null, null);
         Assert.assertTrue(sc.equals(sc2));
-        
+
         Assert.assertNull(sc.getMode());
         Assert.assertNull(sc.getNodeId());
         Assert.assertNull(sc.getTier());
         Assert.assertNull(sc.getNodeDescription());
-        
+
         SwitchConfig sc3 = new SwitchConfig("123", "name", "tier", "mode");
         SwitchConfig sc4 = new SwitchConfig("123", "name", "tier", "mode");
         Assert.assertFalse(sc.equals(sc3));
         Assert.assertTrue(sc3.equals(sc4));
-        
+
         Assert.assertTrue(sc3.getNodeId().equals("123"));
         Assert.assertTrue(sc3.getNodeDescription().equals("name"));
         Assert.assertTrue(sc3.getTier().equals("tier"));
index 971213e483e567b4d4a6d0336ee613b85ceb25a8..443c7a42ab7da517fbb8df65082c36d1a220a79e 100644 (file)
@@ -820,6 +820,8 @@ CommandProvider {
 
     @Override
     public void updateNode(Node node, UpdateType type, Set<Property> props) {
+        log.debug("updateNode: {} type {} props {} for container {}",
+                new Object[] { node, type, props, containerName });
         switch (type) {
         case ADDED:
             addNode(node, props);
@@ -841,7 +843,8 @@ CommandProvider {
         Node node = nodeConnector.getNode();
         Map<String, Property> propMap = new HashMap<String, Property>();
 
-        log.trace("{} {}", nodeConnector, type);
+        log.debug("updateNodeConnector: {} type {} props {} for container {}",
+                new Object[] { nodeConnector, type, props, containerName });
 
         if (nodeConnectorProps == null) {
             return;
@@ -1335,6 +1338,8 @@ CommandProvider {
         Set<Node> nodeSet = nodeProps.keySet();
         if (nodeSet != null) {
             for (Node node : nodeSet) {
+                log.debug("getInventories: {} added for container {}",
+                        new Object[] { node, containerName });
                 addNode(node, null);
             }
         }
@@ -1384,17 +1389,17 @@ CommandProvider {
     }
 
     private void bulkUpdateService(IInventoryListener service) {
+        Map<String, Property> propMap;
+        UpdateType type = UpdateType.ADDED;
+
         for (Node node : getNodes()) {
-            service.notifyNode(node, UpdateType.ADDED, null);
+            propMap = nodeProps.get(node);
+            service.notifyNode(node, type, propMap);
         }
 
-        Map<String, Property> propMap = new HashMap<String, Property>();
-        propMap.put(State.StatePropName, new State(State.EDGE_UP));
         for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) {
-            if (isNodeConnectorEnabled(nodeConnector)) {
-                service.notifyNodeConnector(nodeConnector, UpdateType.ADDED,
-                        propMap);
-            }
+            propMap = nodeConnectorProps.get(nodeConnector);
+            service.notifyNodeConnector(nodeConnector, type, propMap);
         }
     }
 
index 44ad73c4968679a95cd38c1e72dc12f621c4bf46..e774dae115d4617bc3c7548fe4a8b9f7388aa628 100644 (file)
@@ -21,7 +21,7 @@
       <dependency>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>switchmanager.implementation</artifactId>
-         <version>0.4.0-SNAPSHOT</version>
+      <version>0.4.0-SNAPSHOT</version>
     </dependency>
      <dependency>
       <groupId>org.opendaylight.controller</groupId>
index 872fb17129108598fe2f9a5afc038a549dc3e295..f485fdd0dbf140e3c4ac51beb7fec0cc5ddce48a 100644 (file)
@@ -127,7 +127,7 @@ public class TopologyUserLinkConfig implements Serializable {
             return false;
         }
 
-        if (!isValidNodeConnector(srcNodeConnector) || 
+        if (!isValidNodeConnector(srcNodeConnector) ||
                 !isValidNodeConnector(dstNodeConnector)) {
             logger.warn("Invalid NodeConnector");
             return false;
@@ -178,4 +178,4 @@ public class TopologyUserLinkConfig implements Serializable {
                 + ", srcNodeConnector=" + srcNodeConnector
                 + ", dstNodeConnector=" + dstNodeConnector + "]";
     }
-}
\ No newline at end of file
+}
index 277465813baef5d1e183f36ac64efad92cf7fb0c..f9574b993ca709d769a48562f5f03cd5ea5e72aa 100644 (file)
@@ -608,7 +608,7 @@ CommandProvider {
         if (srcNodeConnector == null || dstNodeConnector == null) return null;
         try {
             linkTuple = new Edge(srcNodeConnector, dstNodeConnector);
-        } catch (Exception e) {            
+        } catch (Exception e) {
         }
         return linkTuple;
     }
index b4dfba9277cd12befbf7eb54a6f4943096ef7946..65487a614a85af96fabbac4e7df289d2f28c20e8 100644 (file)
@@ -45,9 +45,9 @@ public class TopologyManagerImplTest {
      * NodeConnectorId> : <1:1>--><11:11>; <1:2>--><11:12>; <3:3>--><13:13>;
      * <3:4>--><13:14>; <5:5>--><15:15>; <5:6>--><15:16>; Method used by two
      * tests: testGetNodeEdges and testGetEdges
-     * 
+     *
      * @param topoManagerImpl
-     * 
+     *
      * @throws ConstructionException
      */
     public void setNodeEdges(TopologyManagerImpl topoManagerImpl)
@@ -73,16 +73,16 @@ public class TopologyManagerImplTest {
             NodeConnector tailnc1 = NodeConnectorCreator
                     .createOFNodeConnector((short) (i + 10),
                             NodeCreator.createOFNode((long) (i + 10)));
-            Edge e1 = new Edge(headnc1, tailnc1);
+            Edge e1 = new Edge(tailnc1, headnc1);
             TopoEdgeUpdate teu1 = new TopoEdgeUpdate(e1, props,
                     UpdateType.ADDED);
             topoedgeupdateList.add(teu1);
 
-            NodeConnector headnc2 = NodeConnectorCreator.createOFNodeConnector(
-                    (short) (i + 1), headnc1.getNode());
             NodeConnector tailnc2 = NodeConnectorCreator.createOFNodeConnector(
+                    (short) (i + 1), headnc1.getNode());
+            NodeConnector headnc2 = NodeConnectorCreator.createOFNodeConnector(
                     (short) (i + 11), tailnc1.getNode());
-            Edge e2 = new Edge(headnc2, tailnc2);
+            Edge e2 = new Edge(tailnc2, headnc2);
             TopoEdgeUpdate teu2 = new TopoEdgeUpdate(e2, props,
                     UpdateType.ADDED);
             topoedgeupdateList.add(teu2);
@@ -111,25 +111,12 @@ public class TopologyManagerImplTest {
                         .longValue();
                 Long tailNcId = ((Short) edge.getTailNodeConnector().getID())
                         .longValue();
-                if (nodeId == 1 || nodeId == 3 || nodeId == 5) {
-                    Assert.assertTrue((headNcId.equals(nodeId) && tailNcId
-                            .equals(nodeId + 10))
-                            || (headNcId.equals(nodeId + 10) && tailNcId
-                                    .equals(nodeId))
-                                    || (headNcId.equals(nodeId + 1) && tailNcId
-                                            .equals(nodeId + 11))
-                                            || (headNcId.equals(nodeId + 11) && tailNcId
-                                                    .equals(nodeId + 1)));
-                } else if (nodeId == 11 || nodeId == 13 || nodeId == 15) {
-                    Assert.assertTrue((headNcId.equals(nodeId) && tailNcId
-                            .equals(nodeId - 10))
-                            || (headNcId.equals(nodeId) && tailNcId
-                                    .equals(nodeId - 10))
-                                    || (headNcId.equals(nodeId - 9) && tailNcId
-                                            .equals(nodeId + 1))
-                                            || (headNcId.equals(nodeId + 1) && tailNcId
-                                                    .equals(nodeId - 9)));
-                }
+                Assert.assertTrue(
+                        (headNcId.equals(nodeId) && tailNcId.equals(nodeId + 10))
+                        || (headNcId.equals(nodeId + 11) && tailNcId.equals(nodeId + 1))
+                        || (headNcId.equals(nodeId + 1) && tailNcId.equals(nodeId - 9))
+                        || (headNcId.equals(nodeId - 10) && tailNcId.equals(nodeId))
+                        );
             }
             i.remove();
         }
similarity index 95%
rename from opendaylight/usermanager/pom.xml
rename to opendaylight/usermanager/api/pom.xml
index 1859e8ed4c5d6b0fe2bfdc3b26bc2be6a8ec655f..877461daaaeed0ae970f554cb2c36f07c877c707 100644 (file)
@@ -6,7 +6,7 @@
     <groupId>org.opendaylight.controller</groupId>
     <artifactId>commons.opendaylight</artifactId>
     <version>1.4.0-SNAPSHOT</version>
-    <relativePath>../commons/opendaylight</relativePath>
+    <relativePath>../../commons/opendaylight</relativePath>
   </parent>
 
   <artifactId>usermanager</artifactId>
             </Import-Package>
             <Export-Package>
               org.opendaylight.controller.usermanager,
+<!--
               org.opendaylight.controller.usermanager.internal
-            </Export-Package>
+ -->
+             </Export-Package>
             <Bundle-Activator>
+<!--
               org.opendaylight.controller.usermanager.internal.Activator
-            </Bundle-Activator>
+ -->
+             </Bundle-Activator>
           </instructions>
           <manifestLocation>${project.basedir}/META-INF</manifestLocation>
         </configuration>
similarity index 89%
rename from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/internal/AuthorizationConfig.java
rename to opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthorizationConfig.java
index 038ccca2fcf6f998273056e2717719900f7c7731..bad8fa511f76b382d79d1a0b00b0c8fd8756f466 100644 (file)
@@ -6,9 +6,10 @@
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
 
-package org.opendaylight.controller.usermanager.internal;
+package org.opendaylight.controller.usermanager;
 
 import java.util.ArrayList;
+import java.util.Iterator;
 import java.util.List;
 
 import org.opendaylight.controller.sal.utils.Status;
@@ -44,4 +45,9 @@ public class AuthorizationConfig extends UserConfig {
     public String toString() {
         return "AuthorizationConfig=[user: " + user + ", roles: " + roles + "]";
     }
+
+    public String getRolesString() {
+        return super.getRolesString();
+    }
+
 }
similarity index 98%
rename from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java
rename to opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java
index 0fb26a1a625ce21afb1c883c8f642e1baa0cba97..36a2c06bf6873118e58a3df90bd41652259ce776 100644 (file)
@@ -18,7 +18,7 @@ public interface IAAAProvider {
     /**
      * Authenticate user with AAA server and return authentication and
      * authorization info using the Provider's mechanism
-     * 
+     *
      * @param userName
      *            the username
      * @param password
@@ -35,7 +35,7 @@ public interface IAAAProvider {
 
     /**
      * Returns the Name of the Provider
-     * 
+     *
      * @return Name of the AAA provider
      */
     public String getName();
similarity index 98%
rename from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java
rename to opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java
index 8149d7a5a2a8add3566eb4e2970a97769d03ec65..372462eaae1366a17b87bebbdb45ad21e9d20802 100644 (file)
@@ -11,14 +11,14 @@ package org.opendaylight.controller.usermanager;
 import javax.servlet.http.HttpSessionListener;
 
 /**
- * 
+ *
  * This interface defines method(s) to invalidate a session.
  */
 public interface ISessionManager extends HttpSessionListener {
 
     /**
      * Invalidates the session for a given user and a session Id
-     * 
+     *
      * @param username
      *            the username
      * @param sessionId
similarity index 92%
rename from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java
rename to opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java
index ed23b5f067c45ebd000ac52fffc919e9707800ef..cd86ed73fe6935cc2c437d4b3be1b03fb35d1689 100644 (file)
@@ -15,9 +15,9 @@ import java.util.Set;
 import org.opendaylight.controller.sal.authorization.AuthResultEnum;
 import org.opendaylight.controller.sal.authorization.UserLevel;
 import org.opendaylight.controller.sal.utils.Status;
-import org.opendaylight.controller.usermanager.internal.AuthorizationConfig;
-import org.opendaylight.controller.usermanager.internal.ServerConfig;
-import org.opendaylight.controller.usermanager.internal.UserConfig;
+import org.opendaylight.controller.usermanager.AuthorizationConfig;
+import org.opendaylight.controller.usermanager.ServerConfig;
+import org.opendaylight.controller.usermanager.UserConfig;
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.web.context.SecurityContextRepository;
 
@@ -267,6 +267,18 @@ public interface IUserManager extends UserDetailsService {
      */
     public ISessionManager getSessionManager();
 
+    /**
+     * Checks if the specified role belongs to any application. Usually an
+     * application will call this function when configuring a role, to check if
+     * that role is already being used by another application.
+     *
+     * @param role
+     *            The role to check
+     * @return true if the specified role belongs to any application or if the
+     *         role is a well-known controller role, false otherwise.
+     */
+    public boolean isRoleInUse(String role);
+
     /* non-Javadoc
      * Returns the password for a given user
      *
similarity index 89%
rename from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java
rename to opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java
index 9766fd475af8ae85c4ad7cce05d795ab132db209..ca6000a9f59f10d7712a29527728c489f85e0b96 100644 (file)
@@ -13,8 +13,8 @@ import org.opendaylight.controller.sal.authorization.UserLevel;
 import org.springframework.security.core.GrantedAuthority;
 
 public class ODLUserLevel implements GrantedAuthority {
-       private static final long serialVersionUID = 1L;
-       UserLevel userLevel;
+        private static final long serialVersionUID = 1L;
+        UserLevel userLevel;
 
     public ODLUserLevel(UserLevel userLevel) {
         this.userLevel = userLevel;
similarity index 94%
rename from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/internal/ServerConfig.java
rename to opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ServerConfig.java
index 2ad98aba68ff58cc64ea546e6db0fe689e000fa9..f50f9e71c9c7f05d23de14034744fbeba676c730 100644 (file)
@@ -7,7 +7,7 @@
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
 
-package org.opendaylight.controller.usermanager.internal;
+package org.opendaylight.controller.usermanager;
 
 import java.io.Serializable;
 
@@ -27,11 +27,11 @@ public class ServerConfig implements Serializable {
     }
 
     public ServerConfig(String ip, String secret, String protocol) {
-       this.ip = ip;
-       this.secret = secret;
-       this.protocol = protocol;
+        this.ip = ip;
+        this.secret = secret;
+        this.protocol = protocol;
     }
-    
+
     public String getAddress() {
         return ip;
     }
similarity index 98%
rename from opendaylight/usermanager/src/main/java/org/opendaylight/controller/usermanager/internal/UserConfig.java
rename to opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/UserConfig.java
index 176af3a3e4d1d48ed9b8120f65b7bc5a6bca9ffb..0e6a48ab52b32bdc66eb114ad26021ef07aa56ad 100644 (file)
@@ -6,7 +6,7 @@
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
 
-package org.opendaylight.controller.usermanager.internal;
+package org.opendaylight.controller.usermanager;
 
 import java.io.Serializable;
 import java.util.ArrayList;
@@ -49,7 +49,7 @@ public class UserConfig implements Serializable {
         this.roles = (roles == null) ? new ArrayList<String>()
                 : new ArrayList<String>(roles);
     }
-    
+
     public String getUser() {
         return user;
     }
@@ -161,24 +161,24 @@ public class UserConfig implements Serializable {
             return new Status(StatusCode.BADREQUEST,
                     "Current password is incorrect");
         }
-        
+
         // Create a new object with the proposed modifications
         UserConfig proposed = new UserConfig();
         proposed.user = this.user;
         proposed.password = (newPassword != null)? newPassword : this.password;
         proposed.roles = (newRoles != null)? newRoles : this.roles;
-        
+
         // Validate it
         Status status = proposed.validate();
         if (!status.isSuccess()) {
             return status;
         }
-        
+
         // Accept the modifications
         this.user = proposed.user;
         this.password = proposed.password;
         this.roles = new ArrayList<String>(proposed.roles);
-        
+
         return status;
     }
 
@@ -192,7 +192,7 @@ public class UserConfig implements Serializable {
         }
         return locResponse;
     }
-    
+
     protected String getRolesString() {
         StringBuffer buffer = new StringBuffer();
         if (!roles.isEmpty()) {
@@ -5,7 +5,7 @@
  * 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.usermanager.internal;
+package org.opendaylight.controller.usermanager;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -18,6 +18,8 @@ import org.junit.Test;
 import org.opendaylight.controller.sal.authorization.AuthResultEnum;
 import org.opendaylight.controller.sal.authorization.UserLevel;
 import org.opendaylight.controller.usermanager.AuthResponse;
+import org.opendaylight.controller.usermanager.AuthorizationConfig;
+import org.opendaylight.controller.usermanager.UserConfig;
 
 /*
  * This test case includes tests for UserConfig and the extending class AuthorizationConfig
@@ -65,13 +67,13 @@ public class AuthorizationUserConfigTest {
         roles.clear();
         roles.add(UserLevel.NETWORKADMIN.toString());
         assertTrue(userConfig.update("ciscocisco", null, roles).isSuccess());
-        
+
         // Role change and same new password
         roles.clear();
         roles.add(UserLevel.NETWORKOPERATOR.toString());
         assertTrue(userConfig.update("ciscocisco", "ciscocisco", roles)
                 .isSuccess());
-        
+
         // New Password = null, No change in password
         assertTrue(userConfig.getPassword().equals("ciscocisco"));
 
similarity index 82%
rename from opendaylight/usermanager/src/test/java/org/opendaylight/controller/usermanager/internal/ServerConfigTest.java
rename to opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/ServerConfigTest.java
index 33c11de0bae2e503ac90e9215e9cd21778c3b60e..eaeca730036dc5587a605d3b9feb270d62b81347 100644 (file)
@@ -1,12 +1,12 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved. 
+ * 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.usermanager.internal;
+package org.opendaylight.controller.usermanager;
 
 public class ServerConfigTest   {
 }
diff --git a/opendaylight/usermanager/implementation/pom.xml b/opendaylight/usermanager/implementation/pom.xml
new file mode 100644 (file)
index 0000000..a558fa2
--- /dev/null
@@ -0,0 +1,97 @@
+<?xml version="1.0" encoding="UTF-8"?> <project
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+  xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>commons.opendaylight</artifactId>
+    <version>1.4.0-SNAPSHOT</version>
+    <relativePath>../../commons/opendaylight</relativePath>
+  </parent>
+
+  <artifactId>usermanager.implementation</artifactId>
+  <version>0.4.0-SNAPSHOT</version>
+  <packaging>bundle</packaging>
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.felix</groupId>
+        <artifactId>maven-bundle-plugin</artifactId>
+        <version>2.3.6</version>
+        <extensions>true</extensions>
+        <configuration>
+          <instructions>
+            <Import-Package>
+              org.opendaylight.controller.clustering.services,
+              org.opendaylight.controller.configuration,
+              org.opendaylight.controller.sal.authorization,
+              org.opendaylight.controller.sal.core,
+              org.opendaylight.controller.sal.packet,
+              org.opendaylight.controller.sal.utils,
+              org.opendaylight.controller.switchmanager,
+              org.opendaylight.controller.containermanager,
+              org.slf4j,
+              org.eclipse.osgi.framework.console,
+              org.osgi.framework,
+              org.apache.felix.dm,
+              org.apache.commons.lang3.builder,
+              org.apache.commons.logging,
+              javax.servlet,
+              javax.servlet.http,
+              org.springframework.security.web.context,
+              org.springframework.security.core,
+              org.springframework.security.core.context,
+              org.apache.commons.lang3,
+              org.springframework.security.authentication,
+              org.springframework.security.core.authority,
+              org.springframework.security.core.userdetails,
+              org.opendaylight.controller.usermanager
+            </Import-Package>
+            <Export-Package>
+<!--
+              org.opendaylight.controller.usermanager,
+              org.opendaylight.controller.usermanager.internal
+ -->
+             </Export-Package>
+            <Bundle-Activator>
+              org.opendaylight.controller.usermanager.internal.Activator
+            </Bundle-Activator>
+          </instructions>
+          <manifestLocation>${project.basedir}/META-INF</manifestLocation>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+  <dependencies>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>usermanager</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>switchmanager</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>containermanager</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>clustering.services</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>configuration</artifactId>
+      <version>0.4.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>sal</artifactId>
+      <version>0.5.0-SNAPSHOT</version>
+    </dependency>
+  </dependencies>
+</project>
@@ -43,11 +43,16 @@ import org.opendaylight.controller.sal.utils.ObjectReader;
 import org.opendaylight.controller.sal.utils.ObjectWriter;
 import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.usermanager.AuthResponse;
+import org.opendaylight.controller.usermanager.AuthorizationConfig;
 import org.opendaylight.controller.usermanager.IAAAProvider;
 import org.opendaylight.controller.usermanager.ISessionManager;
 import org.opendaylight.controller.usermanager.IUserManager;
+import org.opendaylight.controller.usermanager.ServerConfig;
+import org.opendaylight.controller.usermanager.UserConfig;
 import org.opendaylight.controller.usermanager.security.SessionManager;
 import org.opendaylight.controller.usermanager.security.UserSecurityContextRepository;
+import org.opendaylight.controller.usermanager.internal.AuthenticatedUser;
+
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.FrameworkUtil;
 import org.slf4j.Logger;
@@ -156,9 +161,9 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
                     "usermanager.authorizationSaveConfigEvent",
                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
         } catch (CacheConfigException cce) {
-            logger.error("\nCache configuration invalid - check cache mode");
+            logger.error("Cache configuration invalid - check cache mode");
         } catch (CacheExistException ce) {
-            logger.error("\nCache already exits - destroy and recreate if needed");
+            logger.debug("Skipping cache creation as already present");
         }
     }
 
@@ -172,43 +177,43 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
         activeUsers = (ConcurrentMap<String, AuthenticatedUser>) clusterGlobalService
                 .getCache("usermanager.activeUsers");
         if (activeUsers == null) {
-            logger.error("\nFailed to get cache for activeUsers");
+            logger.error("Failed to get cache for activeUsers");
         }
 
         localUserConfigList = (ConcurrentMap<String, UserConfig>) clusterGlobalService
                 .getCache("usermanager.localUserConfigList");
         if (localUserConfigList == null) {
-            logger.error("\nFailed to get cache for localUserConfigList");
+            logger.error("Failed to get cache for localUserConfigList");
         }
 
         remoteServerConfigList = (ConcurrentMap<String, ServerConfig>) clusterGlobalService
                 .getCache("usermanager.remoteServerConfigList");
         if (remoteServerConfigList == null) {
-            logger.error("\nFailed to get cache for remoteServerConfigList");
+            logger.error("Failed to get cache for remoteServerConfigList");
         }
 
         authorizationConfList = (ConcurrentMap<String, AuthorizationConfig>) clusterGlobalService
                 .getCache("usermanager.authorizationConfList");
         if (authorizationConfList == null) {
-            logger.error("\nFailed to get cache for authorizationConfList");
+            logger.error("Failed to get cache for authorizationConfList");
         }
 
         localUserListSaveConfigEvent = (ConcurrentMap<Long, String>) clusterGlobalService
                 .getCache("usermanager.localUserSaveConfigEvent");
         if (localUserListSaveConfigEvent == null) {
-            logger.error("\nFailed to get cache for localUserSaveConfigEvent");
+            logger.error("Failed to get cache for localUserSaveConfigEvent");
         }
 
         remoteServerSaveConfigEvent = (ConcurrentMap<Long, String>) clusterGlobalService
                 .getCache("usermanager.remoteServerSaveConfigEvent");
         if (remoteServerSaveConfigEvent == null) {
-            logger.error("\nFailed to get cache for remoteServerSaveConfigEvent");
+            logger.error("Failed to get cache for remoteServerSaveConfigEvent");
         }
 
         authorizationSaveConfigEvent = (ConcurrentMap<Long, String>) clusterGlobalService
                 .getCache("usermanager.authorizationSaveConfigEvent");
         if (authorizationSaveConfigEvent == null) {
-            logger.error("\nFailed to get cache for authorizationSaveConfigEvent");
+            logger.error("Failed to get cache for authorizationSaveConfigEvent");
         }
     }
 
@@ -866,29 +871,29 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
 
     @Override
     public List<String> getUserRoles(String userName) {
-        if (userName == null) {
-            return new ArrayList<String>(0);
+        List<String> roles = null;
+        if (userName != null) {
+            /*
+             * First look in active users then in local configured users,
+             * finally in local authorized users
+             */
+            if (activeUsers.containsKey(userName)) {
+                roles = activeUsers.get(userName).getUserRoles();
+            } else if (localUserConfigList.containsKey(userName)) {
+                roles = localUserConfigList.get(userName).getRoles();
+            } else if (authorizationConfList.containsKey(userName)) {
+                roles = authorizationConfList.get(userName).getRoles();
+            }
         }
-        AuthenticatedUser locatedUser = activeUsers.get(userName);
-        return (locatedUser == null) ? new ArrayList<String>(0) : locatedUser
-                .getUserRoles();
+        return (roles == null) ? new ArrayList<String>(0) : roles;
     }
 
     @Override
     public UserLevel getUserLevel(String username) {
-        // Returns the controller well-know user level for the passed user
-        List<String> rolesNames = null;
-
-        // First check in active users then in local configured users
-        if (activeUsers.containsKey(username)) {
-            List<String> roles = activeUsers.get(username).getUserRoles();
-            rolesNames = (roles == null || roles.isEmpty()) ? null : roles;
-        } else if (localUserConfigList.containsKey(username)) {
-            UserConfig config = localUserConfigList.get(username);
-            rolesNames = (config == null) ? null : config.getRoles();
-        }
+        // Returns the highest controller user level for the passed user
+        List<String> rolesNames = getUserRoles(username);
 
-        if (rolesNames == null) {
+        if (rolesNames.isEmpty()) {
             return UserLevel.NOUSER;
         }
 
@@ -926,19 +931,11 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
 
     @Override
     public List<UserLevel> getUserLevels(String username) {
-        // Returns the controller well-know user levels for the passed user
-        List<String> rolesNames = null;
+        // Returns the controller user levels for the passed user
+        List<String> rolesNames =  getUserRoles(username);
         List<UserLevel> levels = new ArrayList<UserLevel>();
 
-        if (activeUsers.containsKey(username)) {
-            List<String> roles = activeUsers.get(username).getUserRoles();
-            rolesNames = (roles == null || roles.isEmpty()) ? null : roles;
-        } else if (localUserConfigList.containsKey(username)) {
-            UserConfig config = localUserConfigList.get(username);
-            rolesNames = (config == null) ? null : config.getRoles();
-        }
-
-        if (rolesNames == null) {
+        if (rolesNames.isEmpty()) {
             return levels;
         }
 
@@ -1075,7 +1072,7 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
 
     }
 
-    // following are setters for use in unit testing
+    // Following are setters for use in unit testing
     void setLocalUserConfigList(ConcurrentMap<String, UserConfig> ucl) {
         if (ucl != null) {
             this.localUserConfigList = ucl;
@@ -1119,4 +1116,32 @@ public class UserManagerImpl implements IUserManager, IObjectReader,
     public String getPassword(String username) {
         return localUserConfigList.get(username).getPassword();
     }
+
+    @Override
+    public boolean isRoleInUse(String role) {
+        if (role == null || role.isEmpty()) {
+            return false;
+        }
+        // Check against controller roles
+        if (role.equals(UserLevel.SYSTEMADMIN.toString())
+                || role.equals(UserLevel.NETWORKADMIN.toString())
+                || role.equals(UserLevel.NETWORKOPERATOR.toString())) {
+            return true;
+        }
+        // Check if container roles
+        if (containerAuthorizationClient != null) {
+            if (containerAuthorizationClient.isApplicationRole(role)) {
+                return true;
+            }
+        }
+        // Finally if application role
+        if (applicationAuthorizationClients != null) {
+            for (IResourceAuthorization client : this.applicationAuthorizationClients) {
+                if (client.isApplicationRole(role)) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
 }
@@ -83,7 +83,7 @@ public class SessionManager implements ISessionManager {
                 while (sessIterator.hasNext()) {
                     HttpSession session = sessIterator.next();
                     if (session != null && sessionId != null && session.getId() != null && !session.getId().equals(sessionId)) {
-                        sessionsList.add(session);                                
+                        sessionsList.add(session);
                         sessIterator.remove();
                     }
                     else {
diff --git a/opendaylight/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/AuthenticatedUserTest.java b/opendaylight/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/AuthenticatedUserTest.java
new file mode 100644 (file)
index 0000000..f4810c9
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * 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.usermanager.internal;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import org.opendaylight.controller.sal.authorization.UserLevel;
+import org.springframework.security.core.GrantedAuthority;
+
+public class AuthenticatedUserTest {
+
+        static String[] roleArray;
+        static AuthenticatedUser user;
+
+        @BeforeClass
+        public static void testSetup() {
+                roleArray = new String[] { UserLevel.NETWORKOPERATOR.toString(),
+                                UserLevel.APPUSER.toString() };
+        }
+
+        @Test
+        public void testAuthenticatedUser() {
+                user = new AuthenticatedUser("auser");
+
+                Assert.assertFalse(user.getAccessDate().isEmpty());
+                Assert.assertNull(user.getUserRoles());
+        }
+
+        @Test
+        public void testSetUserRoleList() {
+                List<String> retrievedRoleList = null;
+                List<String> roleList = Arrays.asList(roleArray);
+
+                // list arg
+                user = new AuthenticatedUser("auser");
+                user.setRoleList(roleList);
+                retrievedRoleList = user.getUserRoles();
+                Assert.assertTrue(roleList.equals(retrievedRoleList));
+
+                // array arg
+                user = new AuthenticatedUser("auser");
+                user.setRoleList(roleArray);
+                retrievedRoleList = user.getUserRoles();
+                for (int i = 0; i < roleArray.length; i++)
+                        Assert.assertTrue(roleArray[i].equals(retrievedRoleList.get(i)));
+
+                // test addUserRole
+                user.addUserRole("AnotherRole");
+                Assert.assertTrue(user.getUserRoles().lastIndexOf("AnotherRole") != -1);
+
+        }
+
+        @Test
+        public void testGetGrantedAuthorities() {
+                List<GrantedAuthority> gaList = user
+                                .getGrantedAuthorities(UserLevel.NETWORKOPERATOR);
+                Assert.assertTrue(gaList.get(0).getAuthority()
+                                .equals("ROLE_NETWORK-OPERATOR"));
+        }
+
+}
@@ -25,6 +25,9 @@ import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.usermanager.AuthResponse;
 import org.opendaylight.controller.usermanager.IAAAProvider;
 import org.opendaylight.controller.usermanager.IUserManager;
+import org.opendaylight.controller.usermanager.ServerConfig;
+import org.opendaylight.controller.usermanager.UserConfig;
+import org.opendaylight.controller.usermanager.AuthorizationConfig;
 
 /**
  * Unit Tests for UserManagerImpl
@@ -55,14 +58,17 @@ public class UserManagerImplTest {
                         // Server config can't be empty
                         static final long serialVersionUID = 8645L;
 
+                        @Override
                         public String getAddress() {
                             return "1.1.1.1";
                         }
 
+                        @Override
                         public String getSecret() {
                             return "secret";
                         }
 
+                        @Override
                         public String getProtocol() {
                             return "IPv4";
                         }
@@ -80,11 +86,21 @@ public class UserManagerImplTest {
                             "7029,7455,8165,7029,7881", roles));
                 }
             });
+
+            um.setAuthorizationConfList(new ConcurrentHashMap<String, AuthorizationConfig>() {
+                static final long serialVersionUID = 2L;
+                {
+                    List<String> roles = new ArrayList<String>(3);
+                    roles.add(UserLevel.NETWORKOPERATOR.toString());
+                    roles.add("Container1-Admin");
+                    roles.add("Application2-User");
+
+                    put("Andrew", new AuthorizationConfig("Andrew", roles));
+                }
+            });
             // instantiate an empty activeUser collection
             um.setActiveUsers(new ConcurrentHashMap<String, AuthenticatedUser>());
-
         }
-
     }
 
     /**
@@ -97,11 +113,13 @@ public class UserManagerImplTest {
         // instantiate an anonymous AAAProvider
         IAAAProvider a3p = new IAAAProvider() {
 
+            @Override
             public AuthResponse authService(String userName, String password,
                     String server, String secretKey) {
                 return new AuthResponse();
             };
 
+            @Override
             public String getName() {
                 return "dummyAAAProvider";
             }
@@ -142,7 +160,7 @@ public class UserManagerImplTest {
 
     /**
      * Test method for
-     * {@link org.opendaylight.controller.usermanager.internal.UserManagerImpl#addRemoveLocalUser(org.opendaylight.controller.usermanager.internal.UserConfig, boolean)}
+     * {@link org.opendaylight.controller.usermanager.internal.UserManagerImpl#addRemoveLocalUser(org.opendaylight.controller.usermanager.org.opendaylight.controller.usermanager.internal.UserConfig, boolean)}
      * .
      */
     @Test
@@ -254,6 +272,9 @@ public class UserManagerImplTest {
         Assert.assertTrue(um.getUserLevel("Jack") == UserLevel.SYSTEMADMIN);
         // Run the check on configured users
         Assert.assertTrue(um.getUserLevel("John") == UserLevel.NETWORKOPERATOR);
-        Assert.assertTrue(um.getUserLevel("Andrew") == UserLevel.NOUSER);
+        // Run the check on local authorized users
+        Assert.assertTrue(um.getUserLevel("Andrew") == UserLevel.NETWORKOPERATOR);
+        // Non locally known user
+        Assert.assertTrue(um.getUserLevel("Tom") == UserLevel.NOUSER);
     }
 }
diff --git a/opendaylight/usermanager/src/test/java/org/opendaylight/controller/usermanager/internal/AuthenticatedUserTest.java b/opendaylight/usermanager/src/test/java/org/opendaylight/controller/usermanager/internal/AuthenticatedUserTest.java
deleted file mode 100644 (file)
index 810500b..0000000
+++ /dev/null
@@ -1,72 +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.usermanager.internal;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import org.opendaylight.controller.sal.authorization.UserLevel;
-import org.springframework.security.core.GrantedAuthority;
-
-public class AuthenticatedUserTest {
-
-       static String[] roleArray;
-       static AuthenticatedUser user;
-
-       @BeforeClass
-       public static void testSetup() {
-               roleArray = new String[] { UserLevel.NETWORKOPERATOR.toString(),
-                               UserLevel.APPUSER.toString() };
-       }
-
-       @Test
-       public void testAuthenticatedUser() {
-               user = new AuthenticatedUser("auser");
-
-               Assert.assertFalse(user.getAccessDate().isEmpty());
-               Assert.assertNull(user.getUserRoles());
-       }
-
-       @Test
-       public void testSetUserRoleList() {
-               List<String> retrievedRoleList = null;
-               List<String> roleList = Arrays.asList(roleArray);
-
-               // list arg
-               user = new AuthenticatedUser("auser");
-               user.setRoleList(roleList);
-               retrievedRoleList = user.getUserRoles();
-               Assert.assertTrue(roleList.equals(retrievedRoleList));
-
-               // array arg
-               user = new AuthenticatedUser("auser");
-               user.setRoleList(roleArray);
-               retrievedRoleList = user.getUserRoles();
-               for (int i = 0; i < roleArray.length; i++)
-                       Assert.assertTrue(roleArray[i].equals(retrievedRoleList.get(i)));
-
-               // test addUserRole
-               user.addUserRole("AnotherRole");
-               Assert.assertTrue(user.getUserRoles().lastIndexOf("AnotherRole") != -1);
-
-       }
-
-       @Test
-       public void testGetGrantedAuthorities() {
-               List<GrantedAuthority> gaList = user
-                               .getGrantedAuthorities(UserLevel.NETWORKOPERATOR);
-               Assert.assertTrue(gaList.get(0).getAuthority()
-                               .equals("ROLE_NETWORK-OPERATOR"));
-       }
-
-}
index 6b0a731b99cc445df4c262beebb1e2407b8666f9..af5cd8d4569650ecbd719167171d2762bfb993cd 100644 (file)
@@ -3,19 +3,19 @@
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
   xmlns:context="http://www.springframework.org/schema/context"\r
   xmlns:mvc="http://www.springframework.org/schema/mvc"\r
-  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \r
+  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\r
                       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd\r
                       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">\r
 \r
   <context:component-scan base-package="org.opendaylight.controller.devices.web"/>\r
-  \r
+\r
   <mvc:resources mapping="/js/**" location="/js/" />\r
   <mvc:resources mapping="/css/**" location="/css/" />\r
   <mvc:resources mapping="/img/**" location="/img/" />\r
   <mvc:annotation-driven/>\r
-  \r
+\r
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">\r
-       <property name="prefix" value="/WEB-INF/jsp/"/>\r
-       <property name="suffix" value=".jsp"/>\r
+        <property name="prefix" value="/WEB-INF/jsp/"/>\r
+        <property name="suffix" value=".jsp"/>\r
   </bean>\r
 </beans>\r
index 0c7edce24979757d351c68260e842d9f2ac4017a..6294a9fb5b794dbd0b23e7edb88d7cb0c7918612 100644 (file)
@@ -1,75 +1,75 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>free access</web-resource-name>
-                       <url-pattern>/js/*</url-pattern>
-                       <url-pattern>/images/*</url-pattern>
-                       <url-pattern>/css/*</url-pattern>
-                       <url-pattern>/favicon.ico</url-pattern>
-               </web-resource-collection>
-       </security-constraint>
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>free access</web-resource-name>
+                        <url-pattern>/js/*</url-pattern>
+                        <url-pattern>/images/*</url-pattern>
+                        <url-pattern>/css/*</url-pattern>
+                        <url-pattern>/favicon.ico</url-pattern>
+                </web-resource-collection>
+        </security-constraint>
 
-       <security-constraint>
-               <display-name>DevicesApp</display-name>
-               <web-resource-collection>
-                       <web-resource-name>DevicesGUI</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
+        <security-constraint>
+                <display-name>DevicesApp</display-name>
+                <web-resource-collection>
+                        <web-resource-name>DevicesGUI</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
-       <login-config>
-               <auth-method>FORM</auth-method>
-               <form-login-config>
-                       <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
-                       <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
-               </form-login-config>
-       </login-config>
+        <login-config>
+                <auth-method>FORM</auth-method>
+                <form-login-config>
+                        <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
+                        <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
+                </form-login-config>
+        </login-config>
 
     <error-page>
             <error-code>403</error-code>
             <location>/WEB-INF/jsp/autherror.jsp</location>
     </error-page>
 
-       <servlet>
-               <servlet-name>Devices</servlet-name>
-               <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
-               <load-on-startup>1</load-on-startup>
-       </servlet>
+        <servlet>
+                <servlet-name>Devices</servlet-name>
+                <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
+                <load-on-startup>1</load-on-startup>
+        </servlet>
 
-       <servlet-mapping>
-               <servlet-name>Devices</servlet-name>
-               <url-pattern>/</url-pattern>
-       </servlet-mapping>
+        <servlet-mapping>
+                <servlet-name>Devices</servlet-name>
+                <url-pattern>/</url-pattern>
+        </servlet-mapping>
 
-       <listener>
-               <listener-class>org.opendaylight.controller.web.ControllerUISessionManager</listener-class>
-       </listener>
-       <session-config>
-               <cookie-config>
-                       <path>/</path>
-               </cookie-config>
-       </session-config>
+        <listener>
+                <listener-class>org.opendaylight.controller.web.ControllerUISessionManager</listener-class>
+        </listener>
+        <session-config>
+                <cookie-config>
+                        <path>/</path>
+                </cookie-config>
+        </session-config>
 
 </web-app>
index 7cb2b3a054f679b435f5c0963a6d80469800e3e4..e1cfcc57087d4c1ca340f0fc13dccfd7d2ab5fb1 100644 (file)
@@ -76,7 +76,7 @@ public class Flows implements IDaylightWeb {
     @ResponseBody
     public Set<Map<String, Object>> getFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
         String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-        
+
         // fetch frm
         IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
                 .getInstance(IForwardingRulesManager.class, containerName, this);
@@ -113,7 +113,7 @@ public class Flows implements IDaylightWeb {
     @ResponseBody
     public Map<String, Object> getNodePorts(HttpServletRequest request, @RequestParam(required = false) String container) {
         String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-        
+
         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                 .getInstance(ISwitchManager.class, containerName, this);
         if (switchManager == null) {
@@ -160,7 +160,7 @@ public class Flows implements IDaylightWeb {
     @ResponseBody
     public Map<String, Object> getNodeFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
         String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-        
+
         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                 .getInstance(ISwitchManager.class, containerName, this);
         if (switchManager == null) {
@@ -201,7 +201,7 @@ public class Flows implements IDaylightWeb {
         if (!isUserAuthorized(UserLevel.NETWORKADMIN, request)) {
             return "Operation not authorized";
         }
-        
+
         String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
 
         IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
@@ -232,7 +232,7 @@ public class Flows implements IDaylightWeb {
         if (!isUserAuthorized(UserLevel.NETWORKADMIN, request)) {
             return "Operation not authorized";
         }
-        
+
         String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
 
         IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
@@ -261,7 +261,7 @@ public class Flows implements IDaylightWeb {
     /**
      * Returns whether the current user's level is same or above the required
      * authorization level.
-     * 
+     *
      * @param requiredLevel
      *            the authorization level required
      */
index fbe69795c2c73a3858e6f1e2750ab59821e7a2e5..293fa77ef11c29dbb6c9c5ffd9d5490cf65feb45 100644 (file)
@@ -3,19 +3,19 @@
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
   xmlns:context="http://www.springframework.org/schema/context"\r
   xmlns:mvc="http://www.springframework.org/schema/mvc"\r
-  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \r
+  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\r
                       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd\r
                       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">\r
 \r
   <context:component-scan base-package="org.opendaylight.controller.flows.web"/>\r
-  \r
+\r
   <mvc:resources mapping="/js/**" location="/js/" />\r
   <mvc:resources mapping="/css/**" location="/css/" />\r
   <mvc:resources mapping="/img/**" location="/img/" />\r
   <mvc:annotation-driven/>\r
-  \r
+\r
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">\r
-       <property name="prefix" value="/WEB-INF/jsp/"/>\r
-       <property name="suffix" value=".jsp"/>\r
+        <property name="prefix" value="/WEB-INF/jsp/"/>\r
+        <property name="suffix" value=".jsp"/>\r
   </bean>\r
 </beans>\r
index 5660a37a14df775b87bb2b3396cd658f2b0866bb..c5d2479f6b8029c43617715a772392265343e51b 100644 (file)
@@ -1,79 +1,79 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
 
 
-       <servlet>
-               <servlet-name>Flows</servlet-name>
-               <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
-               <load-on-startup>1</load-on-startup>
-       </servlet>
+        <servlet>
+                <servlet-name>Flows</servlet-name>
+                <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
+                <load-on-startup>1</load-on-startup>
+        </servlet>
 
-       <servlet-mapping>
-               <servlet-name>Flows</servlet-name>
-               <url-pattern>/</url-pattern>
-       </servlet-mapping>
+        <servlet-mapping>
+                <servlet-name>Flows</servlet-name>
+                <url-pattern>/</url-pattern>
+        </servlet-mapping>
 
 
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>free access</web-resource-name>
-                       <url-pattern>/js/*</url-pattern>
-                       <url-pattern>/images/*</url-pattern>
-                       <url-pattern>/css/*</url-pattern>
-                       <url-pattern>/favicon.ico</url-pattern>
-               </web-resource-collection>
-       </security-constraint>
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>free access</web-resource-name>
+                        <url-pattern>/js/*</url-pattern>
+                        <url-pattern>/images/*</url-pattern>
+                        <url-pattern>/css/*</url-pattern>
+                        <url-pattern>/favicon.ico</url-pattern>
+                </web-resource-collection>
+        </security-constraint>
 
-       <security-constraint>
-               <display-name>FlowApp</display-name>
-               <web-resource-collection>
-                       <web-resource-name>FlowMgrGUI</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-constraint>
+                <display-name>FlowApp</display-name>
+                <web-resource-collection>
+                        <web-resource-name>FlowMgrGUI</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
-       <login-config>
-               <auth-method>FORM</auth-method>
-               <form-login-config>
-                       <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
-                       <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
-               </form-login-config>
-       </login-config>
+        <login-config>
+                <auth-method>FORM</auth-method>
+                <form-login-config>
+                        <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
+                        <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
+                </form-login-config>
+        </login-config>
 
     <error-page>
             <error-code>403</error-code>
             <location>/WEB-INF/jsp/autherror.jsp</location>
     </error-page>
 
-       <listener>
-               <listener-class>org.opendaylight.controller.web.ControllerUISessionManager</listener-class>
-       </listener>
+        <listener>
+                <listener-class>org.opendaylight.controller.web.ControllerUISessionManager</listener-class>
+        </listener>
 
-       <session-config>
-               <cookie-config>
-                       <path>/</path>
-               </cookie-config>
-       </session-config>
+        <session-config>
+                <cookie-config>
+                        <path>/</path>
+                </cookie-config>
+        </session-config>
 
 
 
index 46b8d4e0fe5e0329299a5671a6440ae801fbc853..ba2075ddb6a50c198e4d3fbb4d38369391c4fa13 100644 (file)
@@ -17,7 +17,7 @@ import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.sal.utils.StatusCode;
 import org.opendaylight.controller.usermanager.IUserManager;
-import org.opendaylight.controller.usermanager.internal.UserConfig;
+import org.opendaylight.controller.usermanager.UserConfig;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -95,7 +95,7 @@ public class DaylightWebAdmin {
 
         return userManager.removeLocalUser(userName).getDescription();
     }
-    
+
     @RequestMapping(value = "/users/password/{username}", method = RequestMethod.POST)
     @ResponseBody
     public Status changePassword(@PathVariable("username") String username, HttpServletRequest request,
@@ -105,23 +105,23 @@ public class DaylightWebAdmin {
         if (userManager == null) {
             return new Status(StatusCode.GONE, "User Manager not found");
         }
-        
+
         if (!authorize(userManager, UserLevel.NETWORKADMIN, request)) {
             return new Status(StatusCode.FORBIDDEN, "Operation not permitted");
         }
-        
+
         if (newPassword.isEmpty()) {
             return new Status(StatusCode.BADREQUEST, "Empty passwords not allowed");
         }
-        
+
         Status status = userManager.changeLocalUserPassword(username, currentPassword, newPassword);
-        
+
         return status;
     }
 
     /**
      * Is the operation permitted for the given level
-     * 
+     *
      * @param level
      */
     private boolean authorize(IUserManager userManager, UserLevel level,
index ee8284e8835e0d33f00c65ef89c484c812bbf302..a7f7133cb2a8b634d871f1ef53a550d2b0a1a15d 100644 (file)
@@ -11,11 +11,11 @@ import org.opendaylight.controller.sal.utils.ServiceHelper;
 
 public class DaylightWebUtil {
     private static String defaultName = GlobalConstants.DEFAULT.toString();
-    
+
     /**
      * Returns the container that this user is authorized to access. If the user is not authorized to the requested
      * container, then this method will return the default container.
-     * 
+     *
      * @param request - HttpServletRequest object to retrieve username
      * @param container - requested container
      * @param bundle - respective bundle
@@ -25,7 +25,7 @@ public class DaylightWebUtil {
         if (container == null) {
             return defaultName;
         }
-        
+
         String username = request.getUserPrincipal().getName();
         IContainerAuthorization containerAuthorization = (IContainerAuthorization)
                 ServiceHelper.getGlobalInstance(IContainerAuthorization.class, bundle);
index 55e3ee51103ffd8d88a7d1a1dc8969af270eba00..7421759d985086269e8b8dabfe4dcaf37bcf60c0 100644 (file)
@@ -14,31 +14,31 @@ public interface IDaylightWeb {
     /**
      * Returns the name of the bundle. In the GUI, this name will be displayed
      * on the tab.
-     * 
+     *
      * @return Name assigned to the bundle.
      */
     public String getWebName();
 
     /**
      * Returns the Id assigned to the web bundle.
-     * 
+     *
      * @return Id assigned to the web bundle.
      */
     public String getWebId();
 
     /**
      * Returns the position where the bundle tab will be placed in the GUI.
-     * 
+     *
      * @return Position number for the bundle tab.
      */
     public short getWebOrder();
 
     /**
      * This method checks if the user is authorized to access the bundle.
-     * 
+     *
      * @param userLevel
      *            user role level in the controller space.
-     * 
+     *
      * @return true, if user is authorized to access the bundle, else false.
      */
     public boolean isAuthorized(UserLevel userLevel);
index a818c8e6c9fbf10ff467bd5d1d935c361526964f..a8cb864367781639330bb03689c6d3f663b2cfb0 100644 (file)
@@ -3,19 +3,19 @@
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
-  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
+  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
   <context:component-scan base-package="org.opendaylight.controller.web"/>
-  
+
   <mvc:resources mapping="/js/**" location="/js/" />
   <mvc:resources mapping="/css/**" location="/css/" />
   <mvc:resources mapping="/img/**" location="/img/" />
   <mvc:annotation-driven/>
-  
+
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
-       <property name="prefix" value="/WEB-INF/jsp/"/>
-       <property name="suffix" value=".jsp"/>
+        <property name="prefix" value="/WEB-INF/jsp/"/>
+        <property name="suffix" value=".jsp"/>
   </bean>
 </beans>
\ No newline at end of file
index 18ac6e7ecb1cc84d7f3b85ecbb74207a713382a5..1e373fb56cd43d8d25550559e1b8878ee44b9db3 100644 (file)
@@ -1,82 +1,82 @@
 <beans:beans xmlns="http://www.springframework.org/schema/security"
-       xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://www.springframework.org/schema/beans
+        xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/security
            http://www.springframework.org/schema/security/spring-security-3.1.xsd">
 
 
-       <http pattern="/css/**" security="none" />
-       <http pattern="/js/**" security="none" />
-       <http pattern="/images/**" security="none" />
-       <http pattern="/favicon.ico" security="none" />
-       <http pattern="/controller/web/css/**" security="none" />
-       <http pattern="/controller/web/js/**" security="none" />
-       <http pattern="/controller/web/images/**" security="none" />
-
-
-       <http auto-config="false" authentication-manager-ref="authenticationManager"
-               security-context-repository-ref="securityContextRepo" entry-point-ref="loginUrlAuthenticationEntryPoint">
-               <intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
-               <intercept-url pattern="/logout*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
-
-
-               <intercept-url pattern="/**"
-                       access="ROLE_SYSTEM-ADMIN, ROLE_NETWORK-ADMIN, ROLE_NETWORK-OPERATOR, ROLE_CONTAINER-USER" />
-               <custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER" />
-               <custom-filter position="LOGOUT_FILTER" ref="logoutFilter" />
-               <custom-filter position="LAST" ref="controllerFilter" />
-               <remember-me services-ref="rememberMeServices" key="SDN" />
-       </http>
-       
-       <beans:bean id="controllerFilter"
-               class="org.opendaylight.controller.web.ControllerCustomFilter" />
-
-       <authentication-manager id="authenticationManager">
-               <authentication-provider ref="authenticationProviderWrapper" />
-       </authentication-manager>
-
-       <beans:bean id="authenticationFilter"
-               class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
-               <beans:property name="authenticationManager" ref="authenticationManager" />
-               <beans:property name="authenticationFailureHandler"
-                       ref="authenticationFailureHandler" />
-               <beans:property name="authenticationSuccessHandler">
-                       <beans:bean
-                               class="org.opendaylight.controller.web.ControllerAuthenticationSuccessHandler">
-                               <beans:property name="targetUrlParameter" value="x-page-url" />
-                               <beans:property name="defaultTargetUrl" value="/" />
-                       </beans:bean>
-               </beans:property>
-               <beans:property name="rememberMeServices" ref="rememberMeServices" />
-       </beans:bean>
-
-       <beans:bean id="securityContextRepo"
-               class="org.opendaylight.controller.web.ControllerWebSecurityContextRepository" />
-
-       <beans:bean id="authenticationFailureHandler"
-               class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
-               <beans:property name="useForward" value="false" />
-               <beans:property name="defaultFailureUrl" value="/login" />              
-       </beans:bean>
-
-       <beans:bean id="loginUrlAuthenticationEntryPoint"
-               class="org.opendaylight.controller.web.ControllerLoginUrlAuthEntryPoint">
-               <beans:property name="loginFormUrl" value="/login" />
-       </beans:bean>
-
-       <beans:bean id="authenticationProviderWrapper"
-               class="org.opendaylight.controller.web.AuthenticationProviderWrapper" />
+        <http pattern="/css/**" security="none" />
+        <http pattern="/js/**" security="none" />
+        <http pattern="/images/**" security="none" />
+        <http pattern="/favicon.ico" security="none" />
+        <http pattern="/controller/web/css/**" security="none" />
+        <http pattern="/controller/web/js/**" security="none" />
+        <http pattern="/controller/web/images/**" security="none" />
+
+
+        <http auto-config="false" authentication-manager-ref="authenticationManager"
+                security-context-repository-ref="securityContextRepo" entry-point-ref="loginUrlAuthenticationEntryPoint">
+                <intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
+                <intercept-url pattern="/logout*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
+
+
+                <intercept-url pattern="/**"
+                        access="ROLE_SYSTEM-ADMIN, ROLE_NETWORK-ADMIN, ROLE_NETWORK-OPERATOR, ROLE_CONTAINER-USER" />
+                <custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER" />
+                <custom-filter position="LOGOUT_FILTER" ref="logoutFilter" />
+                <custom-filter position="LAST" ref="controllerFilter" />
+                <remember-me services-ref="rememberMeServices" key="SDN" />
+        </http>
+
+        <beans:bean id="controllerFilter"
+                class="org.opendaylight.controller.web.ControllerCustomFilter" />
+
+        <authentication-manager id="authenticationManager">
+                <authentication-provider ref="authenticationProviderWrapper" />
+        </authentication-manager>
+
+        <beans:bean id="authenticationFilter"
+                class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
+                <beans:property name="authenticationManager" ref="authenticationManager" />
+                <beans:property name="authenticationFailureHandler"
+                        ref="authenticationFailureHandler" />
+                <beans:property name="authenticationSuccessHandler">
+                        <beans:bean
+                                class="org.opendaylight.controller.web.ControllerAuthenticationSuccessHandler">
+                                <beans:property name="targetUrlParameter" value="x-page-url" />
+                                <beans:property name="defaultTargetUrl" value="/" />
+                        </beans:bean>
+                </beans:property>
+                <beans:property name="rememberMeServices" ref="rememberMeServices" />
+        </beans:bean>
+
+        <beans:bean id="securityContextRepo"
+                class="org.opendaylight.controller.web.ControllerWebSecurityContextRepository" />
+
+        <beans:bean id="authenticationFailureHandler"
+                class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
+                <beans:property name="useForward" value="false" />
+                <beans:property name="defaultFailureUrl" value="/login" />
+        </beans:bean>
+
+        <beans:bean id="loginUrlAuthenticationEntryPoint"
+                class="org.opendaylight.controller.web.ControllerLoginUrlAuthEntryPoint">
+                <beans:property name="loginFormUrl" value="/login" />
+        </beans:bean>
+
+        <beans:bean id="authenticationProviderWrapper"
+                class="org.opendaylight.controller.web.AuthenticationProviderWrapper" />
 
     <!-- logout related -->
-    
+
     <beans:bean id="logoutHandler"
         class="org.opendaylight.controller.web.ControllerLogoutHandler" />
-        
+
     <beans:bean id="securityContextLogoutHandler"
-        class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />    
-        
-            
+        class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
+
+
     <beans:bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
         <!-- if logout succeed then this is the URL -->
         <beans:constructor-arg value="/login" />
             </beans:list>
         </beans:constructor-arg>
         <beans:property name="filterProcessesUrl" value="/logout" />
-    </beans:bean>       
-        
+    </beans:bean>
+
+
 
 
+        <!-- remember me related -->
+        <beans:bean id="rememberMeFilter"
+                class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
+                <beans:property name="rememberMeServices" ref="rememberMeServices" />
+                <beans:property name="authenticationManager" ref="authenticationManager" />
+        </beans:bean>
 
-       <!-- remember me related -->
-       <beans:bean id="rememberMeFilter"
-               class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
-               <beans:property name="rememberMeServices" ref="rememberMeServices" />
-               <beans:property name="authenticationManager" ref="authenticationManager" />
-       </beans:bean>
+        <beans:bean id="rememberMeServices"
+                class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
+                <beans:property name="userDetailsService" ref="userDetailsServiceRef" />
+                <beans:property name="key" value="SDN" />
+                <beans:property name="alwaysRemember" value="true"></beans:property>
+                <beans:property name="tokenValiditySeconds" value="3600" />
+                <beans:property name="cookieName" value="SDN-Controller" />
+        </beans:bean>
 
-       <beans:bean id="rememberMeServices"
-               class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
-               <beans:property name="userDetailsService" ref="userDetailsServiceRef" />
-               <beans:property name="key" value="SDN" />
-               <beans:property name="alwaysRemember" value="true"></beans:property>
-               <beans:property name="tokenValiditySeconds" value="3600" />
-               <beans:property name="cookieName" value="SDN-Controller" />
-       </beans:bean>
+        <beans:bean id="userDetailsServiceRef" class="org.opendaylight.controller.web.ControllerUserDetailsService" />
 
-       <beans:bean id="userDetailsServiceRef" class="org.opendaylight.controller.web.ControllerUserDetailsService" />
 
+        <beans:bean id="rememberMeAuthenticationProvider"
+                class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
+                <beans:property name="key" value="SDN" />
+        </beans:bean>
 
-       <beans:bean id="rememberMeAuthenticationProvider"
-               class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
-               <beans:property name="key" value="SDN" />
-       </beans:bean>
-       
 </beans:beans>
index d96fb6eba249a5d883a6aa00287e3919276fff70..557b9c74f5a0b3fd28cb53281339105c242d9698 100644 (file)
@@ -1,84 +1,84 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
-<!-- <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
-       xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" 
-       version="2.4"> -->
+<!-- <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
+        version="2.4"> -->
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
 
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>free access</web-resource-name>
-                       <url-pattern>/js/*</url-pattern>
-                       <url-pattern>/images/*</url-pattern>
-                       <url-pattern>/css/*</url-pattern>
-                       <url-pattern>/favicon.ico</url-pattern>
-               </web-resource-collection>
-       </security-constraint>
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>free access</web-resource-name>
+                        <url-pattern>/js/*</url-pattern>
+                        <url-pattern>/images/*</url-pattern>
+                        <url-pattern>/css/*</url-pattern>
+                        <url-pattern>/favicon.ico</url-pattern>
+                </web-resource-collection>
+        </security-constraint>
 
-       <security-constraint>
-               <display-name>RootApp</display-name>
-               <web-resource-collection>
-                       <web-resource-name>RootGUI</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
+        <security-constraint>
+                <display-name>RootApp</display-name>
+                <web-resource-collection>
+                        <web-resource-name>RootGUI</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
 
-       <login-config>
-               <auth-method>FORM</auth-method>
-               <form-login-config>
-                       <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
-                       <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
-               </form-login-config>
-       </login-config>
+        <login-config>
+                <auth-method>FORM</auth-method>
+                <form-login-config>
+                        <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
+                        <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
+                </form-login-config>
+        </login-config>
 
     <error-page>
             <error-code>403</error-code>
             <location>/WEB-INF/jsp/autherror.jsp</location>
     </error-page>
 
-       <servlet>
-               <servlet-name>RootGUI</servlet-name>
-               <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
-               <load-on-startup>1</load-on-startup>
-       </servlet>
+        <servlet>
+                <servlet-name>RootGUI</servlet-name>
+                <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
+                <load-on-startup>1</load-on-startup>
+        </servlet>
 
-       <servlet-mapping>
-               <servlet-name>RootGUI</servlet-name>
-               <url-pattern>/</url-pattern>
-       </servlet-mapping>
+        <servlet-mapping>
+                <servlet-name>RootGUI</servlet-name>
+                <url-pattern>/</url-pattern>
+        </servlet-mapping>
 
-       <display-name>OpenDaylight Controller</display-name>
-       <description>OpenDaylight Controller</description>
+        <display-name>OpenDaylight Controller</display-name>
+        <description>OpenDaylight Controller</description>
 
-       <listener>
-               <listener-class>org.opendaylight.controller.web.ControllerUISessionManager</listener-class>
-       </listener>
+        <listener>
+                <listener-class>org.opendaylight.controller.web.ControllerUISessionManager</listener-class>
+        </listener>
 
-       <session-config>
-               <cookie-config>
-                       <path>/</path>
-               </cookie-config>
-       </session-config>
+        <session-config>
+                <cookie-config>
+                        <path>/</path>
+                </cookie-config>
+        </session-config>
 
 </web-app>
index b4695defdb4468d5e3a1324e723e6bab169513ae..62b64a51849ea2ee08c4b9f43cffca8439bd5cad 100644 (file)
@@ -70,77 +70,77 @@ public class Topology implements IObjectReader, IConfigurationAware {
     protected Map<String, Map<String, Map<String, Object>>> metaCache = new HashMap<String, Map<String, Map<String, Object>>>();
     protected Map<String, Map<String, Object>> stagedNodes;
     protected Map<String, Map<String, Object>> newNodes;
-    
+
     protected Map<String, Integer> metaNodeHash = new HashMap<String, Integer>();
     protected Map<String, Integer> metaHostHash = new HashMap<String, Integer>();
     protected Map<String, Integer> metaNodeSingleHash = new HashMap<String, Integer>();
     protected Map<String, Integer> metaNodeConfigurationHash = new HashMap<String, Integer>();
-    
+
     public Topology() {
-       ServiceHelper.registerGlobalService(IConfigurationAware.class, this, null);
-       topologyWebFileName = ROOT + "topologyCache.sav";
-       loadConfiguration();
+        ServiceHelper.registerGlobalService(IConfigurationAware.class, this, null);
+        topologyWebFileName = ROOT + "topologyCache.sav";
+        loadConfiguration();
     }
-    
+
     /**
      * Topology of nodes and hosts in the network in JSON format.
-     * 
+     *
      * Mainly intended for consumption by the visual topology.
-     * 
+     *
      * @return - JSON output for visual topology
      */
     @RequestMapping(value = "/visual.json", method = RequestMethod.GET)
     @ResponseBody
     public Collection<Map<String, Object>> getLinkData(@RequestParam(required = false) String container, HttpServletRequest request) {
-       String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-       
+        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+
         ITopologyManager topologyManager = (ITopologyManager) ServiceHelper
                 .getInstance(ITopologyManager.class, containerName, this);
         if (topologyManager == null) {
-               return null;
+                return null;
         }
         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                 .getInstance(ISwitchManager.class, containerName, this);
         if (switchManager == null) {
-               return null;
+                return null;
         }
-        
+
         Map<Node, Set<Edge>> nodeEdges = topologyManager.getNodeEdges();
         Map<Node, Set<NodeConnector>> hostEdges = topologyManager
                 .getNodesWithNodeConnectorHost();
         List<Switch> nodes = switchManager.getNetworkDevices();
-        
+
         List<SwitchConfig> switchConfigurations = new ArrayList<SwitchConfig>();
         for(Switch sw : nodes) {
-               Node n = sw.getNode();
-               SwitchConfig config = switchManager.getSwitchConfig(n.toString());
-               switchConfigurations.add(config);
+                Node n = sw.getNode();
+                SwitchConfig config = switchManager.getSwitchConfig(n.toString());
+                switchConfigurations.add(config);
         }
-        
+
         // initialize cache if needed
         if (!metaCache.containsKey(containerName)) {
-               metaCache.put(containerName, new HashMap<String, Map<String, Object>>());
-               // initialize hashes
-               metaNodeHash.put(containerName, null);
-               metaHostHash.put(containerName, null);
-               metaNodeSingleHash.put(containerName, null);
-               metaNodeConfigurationHash.put(containerName, null);
+                metaCache.put(containerName, new HashMap<String, Map<String, Object>>());
+                // initialize hashes
+                metaNodeHash.put(containerName, null);
+                metaHostHash.put(containerName, null);
+                metaNodeSingleHash.put(containerName, null);
+                metaNodeConfigurationHash.put(containerName, null);
         }
-        
+
         // return cache if topology hasn't changed
         if (
-               (metaNodeHash.get(containerName) != null && metaHostHash.get(containerName) != null && metaNodeSingleHash.get(containerName) != null && metaNodeConfigurationHash.get(containerName) != null) &&
-               metaNodeHash.get(containerName).equals(nodeEdges.hashCode()) && metaHostHash.get(containerName).equals(hostEdges.hashCode()) && metaNodeSingleHash.get(containerName).equals(nodes.hashCode()) && metaNodeConfigurationHash.get(containerName).equals(switchConfigurations.hashCode())
+                (metaNodeHash.get(containerName) != null && metaHostHash.get(containerName) != null && metaNodeSingleHash.get(containerName) != null && metaNodeConfigurationHash.get(containerName) != null) &&
+                metaNodeHash.get(containerName).equals(nodeEdges.hashCode()) && metaHostHash.get(containerName).equals(hostEdges.hashCode()) && metaNodeSingleHash.get(containerName).equals(nodes.hashCode()) && metaNodeConfigurationHash.get(containerName).equals(switchConfigurations.hashCode())
         ) {
-               return metaCache.get(containerName).values();
+                return metaCache.get(containerName).values();
         }
-        
+
         // cache has changed, we must assign the new values
         metaNodeHash.put(containerName, nodeEdges.hashCode());
         metaHostHash.put(containerName, hostEdges.hashCode());
         metaNodeSingleHash.put(containerName, nodes.hashCode());
         metaNodeConfigurationHash.put(containerName, switchConfigurations.hashCode());
-        
+
         stagedNodes = new HashMap<String, Map<String, Object>>();
         newNodes = new HashMap<String, Map<String, Object>>();
 
@@ -149,12 +149,12 @@ public class Topology implements IObjectReader, IConfigurationAware {
 
         // single nodes addition
         addSingleNodes(nodes, switchManager, containerName);
-        
+
         // hostNodes addition
         addHostNodes(hostEdges, topologyManager, containerName);
-        
+
         repositionTopology(containerName);
-        
+
         return metaCache.get(containerName).values();
     }
 
@@ -165,20 +165,20 @@ public class Topology implements IObjectReader, IConfigurationAware {
      * @param topology - the topology instance
      */
     private void addNodes(Map<Node, Set<Edge>> nodeEdges,
-            ITopologyManager topology, ISwitchManager switchManager, String containerName) {           
+            ITopologyManager topology, ISwitchManager switchManager, String containerName) {
         Bandwidth bandwidth = new Bandwidth(0);
         Map<Edge, Set<Property>> properties = topology.getEdges();
-        
+
         for (Map.Entry<Node, Set<Edge>> e : nodeEdges.entrySet()) {
             Node n = e.getKey();
             String description = switchManager.getNodeDescription(n);
             NodeBean node = createNodeBean(description, n);
-            
+
             // skip production node
             if (nodeIgnore(n)) {
                 continue;
             }
-            
+
             List<Map<String, Object>> adjacencies = new LinkedList<Map<String, Object>>();
             Set<Edge> links = e.getValue();
             for (Edge link : links) {
@@ -187,53 +187,53 @@ public class Topology implements IObjectReader, IConfigurationAware {
                 }
                 for (Property p : properties.get(link)) {
                     if (p instanceof Bandwidth) {
-                       bandwidth = (Bandwidth) p;
+                        bandwidth = (Bandwidth) p;
                         break;
                     }
                 }
                 EdgeBean edge = new EdgeBean(link, bandwidth);
                 adjacencies.add(edge.out());
             }
-            
+
             node.setLinks(adjacencies);
             if (metaCache.get(containerName).containsKey(node.id())) {
-               // retrieve node from cache
-               Map<String, Object> nodeEntry = metaCache.get(containerName).get(node.id());
-
-                       Map<String, String> data = (Map<String, String>) nodeEntry.get("data");
-                       data.put("$desc", description);
-                       nodeEntry.put("data", data);
-                       
-               // always update adjacencies
-               nodeEntry.put("adjacencies", adjacencies);
-               // stage this cached node (with position)
-               stagedNodes.put(node.id(), nodeEntry);
+                // retrieve node from cache
+                Map<String, Object> nodeEntry = metaCache.get(containerName).get(node.id());
+
+                        Map<String, String> data = (Map<String, String>) nodeEntry.get("data");
+                        data.put("$desc", description);
+                        nodeEntry.put("data", data);
+
+                // always update adjacencies
+                nodeEntry.put("adjacencies", adjacencies);
+                // stage this cached node (with position)
+                stagedNodes.put(node.id(), nodeEntry);
             } else {
-               newNodes.put(node.id(), node.out());
+                newNodes.put(node.id(), node.out());
             }
         }
     }
-    
+
     /**
      * Check if this node shouldn't appear in the visual topology
-     * 
+     *
      * @param node
      * @return
      */
     private boolean nodeIgnore(Node node) {
         String nodeType = node.getType();
-        
+
         // add other node types to ignore later
         if (nodeType.equals(NodeIDType.PRODUCTION)) {
             return true;
         }
-        
+
         return false;
     }
-    
+
     /**
      * Check if this edge shouldn't appear in the visual topology
-     * 
+     *
      * @param edge
      * @return
      */
@@ -243,57 +243,57 @@ public class Topology implements IObjectReader, IConfigurationAware {
         if (nodeIgnore(headNode)) {
             return true;
         }
-        
+
         NodeConnector tailNodeConnector = edge.getTailNodeConnector();
         Node tailNode = tailNodeConnector.getNode();
         if (nodeIgnore(tailNode)) {
             return true;
         }
-        
+
         return false;
     }
-    
+
     protected NodeBean createNodeBean(String description, Node node) {
-       String name = (description == null || 
-                       description.trim().isEmpty() ||
-                       description.equalsIgnoreCase("none"))?
-                                       node.toString() : description;
-               return  new NodeBean(node.toString(), name, NodeType.NODE);
+        String name = (description == null ||
+                        description.trim().isEmpty() ||
+                        description.equalsIgnoreCase("none"))?
+                                        node.toString() : description;
+                return  new NodeBean(node.toString(), name, NodeType.NODE);
     }
-    
+
     @SuppressWarnings("unchecked")
-       private void addSingleNodes(List<Switch> nodes, ISwitchManager switchManager, String containerName) {
-       if (nodes == null) {
-               return;
-       }
-       for (Switch sw : nodes) {
-               Node n = sw.getNode();
-               
-               // skip production node
-               if (nodeIgnore(n)) {
-                   continue;
-               }
-
-               String description = switchManager.getNodeDescription(n);
-               
-               if ((stagedNodes.containsKey(n.toString()) && metaCache.get(containerName).containsKey(n.toString())) || newNodes.containsKey(n.toString())) {
-                       continue;
-               }
-               NodeBean node = createNodeBean(description, n);
-               
-               // FIXME still doesn't display standalone node when last remaining link is removed
-               if (metaCache.get(containerName).containsKey(node.id()) && !stagedNodes.containsKey(node.id())) {
-                       Map<String, Object> nodeEntry = metaCache.get(containerName).get(node.id());
-                               Map<String, String> data = (Map<String, String>) nodeEntry.get("data");
-                       data.put("$desc", description);
-                       nodeEntry.put("data", data);
-                       // clear adjacencies since this is now a single node
-                       nodeEntry.put("adjacencies", new LinkedList<Map<String, Object>>());
-               stagedNodes.put(node.id(), nodeEntry);
+        private void addSingleNodes(List<Switch> nodes, ISwitchManager switchManager, String containerName) {
+        if (nodes == null) {
+                return;
+        }
+        for (Switch sw : nodes) {
+                Node n = sw.getNode();
+
+                // skip production node
+                if (nodeIgnore(n)) {
+                    continue;
+                }
+
+                String description = switchManager.getNodeDescription(n);
+
+                if ((stagedNodes.containsKey(n.toString()) && metaCache.get(containerName).containsKey(n.toString())) || newNodes.containsKey(n.toString())) {
+                        continue;
+                }
+                NodeBean node = createNodeBean(description, n);
+
+                // FIXME still doesn't display standalone node when last remaining link is removed
+                if (metaCache.get(containerName).containsKey(node.id()) && !stagedNodes.containsKey(node.id())) {
+                        Map<String, Object> nodeEntry = metaCache.get(containerName).get(node.id());
+                                Map<String, String> data = (Map<String, String>) nodeEntry.get("data");
+                        data.put("$desc", description);
+                        nodeEntry.put("data", data);
+                        // clear adjacencies since this is now a single node
+                        nodeEntry.put("adjacencies", new LinkedList<Map<String, Object>>());
+                stagedNodes.put(node.id(), nodeEntry);
             } else {
-               newNodes.put(node.id(), node.out());
+                newNodes.put(node.id(), node.out());
             }
-       }
+        }
     }
 
     /**
@@ -313,22 +313,22 @@ public class Topology implements IObjectReader, IConfigurationAware {
                 addressByteBuffer.putShort((short) 0);
                 addressByteBuffer.put(dmac.getValue());
                 addressByteBuffer.rewind();
-                
+
                 long hid = addressByteBuffer.getLong();
                 String hostId = String.valueOf(hid);
-                
+
                 NodeBean hostBean = new NodeBean(hostId, host.getNetworkAddressAsString(), NodeType.HOST);
                 List<Map<String, Object>> adjacencies = new LinkedList<Map<String, Object>>();
                 EdgeBean edge = new EdgeBean(connector, hid);
                 adjacencies.add(edge.out());
                 hostBean.setLinks(adjacencies);
-                
+
                 if (metaCache.get(containerName).containsKey(hostId)) {
-                       Map<String, Object> hostEntry = metaCache.get(containerName).get(hostId);
-                       hostEntry.put("adjacencies", adjacencies);
-                       stagedNodes.put(hostId, hostEntry);
+                        Map<String, Object> hostEntry = metaCache.get(containerName).get(hostId);
+                        hostEntry.put("adjacencies", adjacencies);
+                        stagedNodes.put(hostId, hostEntry);
                 } else {
-                       newNodes.put(String.valueOf(hid), hostBean.out());
+                        newNodes.put(String.valueOf(hid), hostBean.out());
                 }
             }
         }
@@ -339,24 +339,24 @@ public class Topology implements IObjectReader, IConfigurationAware {
      */
     private void repositionTopology(String containerName) {
         Graph<String, String> graph = new SparseMultigraph<String, String>();
-        
+
         metaCache.get(containerName).clear();
         metaCache.get(containerName).putAll(stagedNodes);
         metaCache.get(containerName).putAll(newNodes);
-        
+
         for (Map<String, Object> on : metaCache.get(containerName).values()) {
             graph.addVertex(on.toString());
 
             List<Map<String, Object>> adjacencies = (List<Map<String, Object>>) on.get("adjacencies");
-            
+
             for (Map<String, Object> adj : adjacencies) {
                 graph.addEdge(
-                       adj.toString(), adj.get("nodeFrom").toString(),
-                       adj.get("nodeTo").toString()
+                        adj.toString(), adj.get("nodeFrom").toString(),
+                        adj.get("nodeTo").toString()
                 );
             }
         }
-        
+
         CircleLayout<String, String> layout = new CircleLayout<String, String>(graph);
         layout.setSize(new Dimension(1200, 365));
         for (Map.Entry<String, Map<String, Object>> v : newNodes.entrySet()) {
@@ -373,7 +373,7 @@ public class Topology implements IObjectReader, IConfigurationAware {
 
     /**
      * Update node position
-     * 
+     *
      * This method is mainly used by the visual topology
      *
      * @param nodeId - The node to update
@@ -382,16 +382,16 @@ public class Topology implements IObjectReader, IConfigurationAware {
     @RequestMapping(value = "/node/{nodeId}", method = RequestMethod.POST)
     @ResponseBody
     public Map<String, Object> post(@PathVariable String nodeId, @RequestParam(required = true) String x,
-               @RequestParam(required = true) String y, @RequestParam(required = false) String container, 
-               HttpServletRequest request) {
-       if (!authorize(UserLevel.NETWORKADMIN, request)) {
-               return new HashMap<String, Object>(); // silently disregard new node position
-       }
-       
-       String containerName = getAuthorizedContainer(request, container);
-       
+                @RequestParam(required = true) String y, @RequestParam(required = false) String container,
+                HttpServletRequest request) {
+        if (!authorize(UserLevel.NETWORKADMIN, request)) {
+                return new HashMap<String, Object>(); // silently disregard new node position
+        }
+
+        String containerName = getAuthorizedContainer(request, container);
+
         String id = new String(nodeId);
-        
+
         if (!metaCache.get(containerName).containsKey(id)) {
             return null;
         }
@@ -403,123 +403,123 @@ public class Topology implements IObjectReader, IConfigurationAware {
         data.put("$y", y);
 
         node.put("data", data);
-        
+
         return node;
     }
-    
+
     /**
      * Node object for visual topology
      */
     protected class NodeBean {
-       protected String id;
-       protected String name;
-       protected Map<String, String> data;
-       protected List<Map<String, Object>> links;
-       
-       public NodeBean() {
-               data = new HashMap<String, String>();
-               links = new ArrayList<Map<String, Object>>();
-       }
-       
-       public NodeBean(String id, String name, String type) {
-               this();
-               this.id = id;
-               this.name = name;
-               data.put("$desc", name);
-               data.put("$type", type);
-       }
-       
-       public void setLinks(List<Map<String, Object>> links) {
-               this.links = links;
-       }
-       
-       public Map<String, Object> out() {
-               Map<String, Object> node = new HashMap<String, Object>();
-               node.put("id", this.id);
-               node.put("name", this.name);
-               node.put("data", this.data);
-               node.put("adjacencies", this.links);
-               
-               return node;
-       }
-       
-       public String name() {
-               return this.name;
-       }
-       
-       public String id() {
-               return this.id;
-       }
+        protected String id;
+        protected String name;
+        protected Map<String, String> data;
+        protected List<Map<String, Object>> links;
+
+        public NodeBean() {
+                data = new HashMap<String, String>();
+                links = new ArrayList<Map<String, Object>>();
+        }
+
+        public NodeBean(String id, String name, String type) {
+                this();
+                this.id = id;
+                this.name = name;
+                data.put("$desc", name);
+                data.put("$type", type);
+        }
+
+        public void setLinks(List<Map<String, Object>> links) {
+                this.links = links;
+        }
+
+        public Map<String, Object> out() {
+                Map<String, Object> node = new HashMap<String, Object>();
+                node.put("id", this.id);
+                node.put("name", this.name);
+                node.put("data", this.data);
+                node.put("adjacencies", this.links);
+
+                return node;
+        }
+
+        public String name() {
+                return this.name;
+        }
+
+        public String id() {
+                return this.id;
+        }
     }
-    
+
     /**
      * Edge object for visual topology
      */
     protected class EdgeBean {
-       protected NodeConnector source;
-       protected NodeConnector destination;
-       protected Map<String, String> data;
-       protected Long hostId;
-       
-       public EdgeBean() {
-               data = new HashMap<String, String>();
-       }
-       
-       public EdgeBean(Edge link, Bandwidth bandwidth) {
-               this();
-               this.source = link.getHeadNodeConnector();
-               this.destination = link.getTailNodeConnector();
-               
-               // data
-               data.put("$bandwidth", bandwidth.toString());
-               data.put("$color", bandwidthColor(bandwidth));
-               data.put("$nodeToPort", destination.getID().toString());
-               data.put("$nodeFromPort", source.getID().toString());
-               data.put("$descFrom", source.getNode().toString());
-               data.put("$descTo", destination.getNode().toString());
-               data.put("$nodeFromPortName", source.toString());
-               data.put("$nodeToPortName", destination.toString());
-       }
-       
-       public EdgeBean(NodeConnector connector, Long hostId) {
-               this();
-               this.source = null;
-               this.destination = connector;
-               this.hostId = hostId;
-               
-               data.put("$bandwidth", "N/A");
-               data.put("$color", bandwidthColor(new Bandwidth(0)));
-               data.put("$nodeToPort", connector.getNodeConnectorIDString());
-               data.put("$nodeFromPort", connector.getNodeConnectorIDString());
-               data.put("$descTo", "");
-               data.put("$descFrom", "");
-               data.put("$nodeToPortName", "");
-               data.put("$nodeFromPortName", "");
-       }
-       
-       public Map<String, Object> out() {
-               Map<String, Object> edge = new HashMap<String, Object>();
-               
-               edge.put("data", data);
-               if (source == null) {
-                       edge.put("nodeFrom", String.valueOf(this.hostId));
-               } else {
-                       edge.put("nodeFrom", source.getNode().toString());
-               }
-               edge.put("nodeTo", destination.getNode().toString());
-               
-               
-               return edge;
-       }
-       
-       private String bandwidthColor(Bandwidth bandwidth) {
-               String color = null;
-               long bandwidthValue = bandwidth.getValue();
-               
-               if (bandwidthValue == 0) {
+        protected NodeConnector source;
+        protected NodeConnector destination;
+        protected Map<String, String> data;
+        protected Long hostId;
+
+        public EdgeBean() {
+                data = new HashMap<String, String>();
+        }
+
+        public EdgeBean(Edge link, Bandwidth bandwidth) {
+                this();
+                this.source = link.getHeadNodeConnector();
+                this.destination = link.getTailNodeConnector();
+
+                // data
+                data.put("$bandwidth", bandwidth.toString());
+                data.put("$color", bandwidthColor(bandwidth));
+                data.put("$nodeToPort", destination.getID().toString());
+                data.put("$nodeFromPort", source.getID().toString());
+                data.put("$descFrom", source.getNode().toString());
+                data.put("$descTo", destination.getNode().toString());
+                data.put("$nodeFromPortName", source.toString());
+                data.put("$nodeToPortName", destination.toString());
+        }
+
+        public EdgeBean(NodeConnector connector, Long hostId) {
+                this();
+                this.source = null;
+                this.destination = connector;
+                this.hostId = hostId;
+
+                data.put("$bandwidth", "N/A");
+                data.put("$color", bandwidthColor(new Bandwidth(0)));
+                data.put("$nodeToPort", connector.getNodeConnectorIDString());
+                data.put("$nodeFromPort", connector.getNodeConnectorIDString());
+                data.put("$descTo", "");
+                data.put("$descFrom", "");
+                data.put("$nodeToPortName", "");
+                data.put("$nodeFromPortName", "");
+        }
+
+        public Map<String, Object> out() {
+                Map<String, Object> edge = new HashMap<String, Object>();
+
+                edge.put("data", data);
+                if (source == null) {
+                        edge.put("nodeFrom", String.valueOf(this.hostId));
+                } else {
+                        edge.put("nodeFrom", source.getNode().toString());
+                }
+                edge.put("nodeTo", destination.getNode().toString());
+
+
+                return edge;
+        }
+
+        private String bandwidthColor(Bandwidth bandwidth) {
+                String color = null;
+                long bandwidthValue = bandwidth.getValue();
+
+                if (bandwidthValue == 0) {
                 color = "#000";
             } else if (bandwidthValue < Bandwidth.BW1Kbps) {
-               color = "#148AC6";
+                color = "#148AC6";
             } else if (bandwidthValue < Bandwidth.BW1Mbps) {
                 color = "#2858A0";
             } else if (bandwidthValue < Bandwidth.BW1Gbps) {
@@ -529,58 +529,58 @@ public class Topology implements IObjectReader, IConfigurationAware {
             } else if (bandwidthValue < Bandwidth.BW1Pbps) {
                 color = "#F9F464";
             }
-               
-               return color;
+
+                return color;
         }
     }
-    
+
     protected class NodeType {
-       public static final String NODE = "swtch";
-       public static final String HOST = "host";
+        public static final String NODE = "swtch";
+        public static final String HOST = "host";
     }
-    
+
     private boolean authorize(UserLevel level, HttpServletRequest request) {
-       IUserManager userManager = (IUserManager) ServiceHelper
+        IUserManager userManager = (IUserManager) ServiceHelper
                 .getGlobalInstance(IUserManager.class, this);
         if (userManager == null) {
-               return false;
+                return false;
         }
-        
+
         String username = request.getUserPrincipal().getName();
         UserLevel userLevel = userManager.getUserLevel(username);
         if (userLevel.toNumber() <= level.toNumber()) {
-               return true;
+                return true;
         }
         return false;
     }
-    
+
     private String getAuthorizedContainer(HttpServletRequest request, String container) {
-       String username = request.getUserPrincipal().getName();
-       IContainerAuthorization containerAuthorization = (IContainerAuthorization) ServiceHelper.
-                       getGlobalInstance(IContainerAuthorization.class, this);
-       if (containerAuthorization != null) {
-               Set<Resource> resources = containerAuthorization.getAllResourcesforUser(username);
-               if (authorizeContainer(container, resources)) {
-                       return container;
-               }
-       }
-       
-       return GlobalConstants.DEFAULT.toString();
+        String username = request.getUserPrincipal().getName();
+        IContainerAuthorization containerAuthorization = (IContainerAuthorization) ServiceHelper.
+                        getGlobalInstance(IContainerAuthorization.class, this);
+        if (containerAuthorization != null) {
+                Set<Resource> resources = containerAuthorization.getAllResourcesforUser(username);
+                if (authorizeContainer(container, resources)) {
+                        return container;
+                }
+        }
+
+        return GlobalConstants.DEFAULT.toString();
     }
-    
+
     private boolean authorizeContainer(String container, Set<Resource> resources) {
-       for(Resource resource : resources) {
-               String containerName = (String) resource.getResource();
-               if (containerName.equals(container)) {
-                       return true;
-               }
-       }
-       
-       return false;
+        for(Resource resource : resources) {
+                String containerName = (String) resource.getResource();
+                if (containerName.equals(container)) {
+                        return true;
+                }
+        }
+
+        return false;
     }
 
     @SuppressWarnings("unchecked")
-       private void loadConfiguration() {
+        private void loadConfiguration() {
         ObjectReader objReader = new ObjectReader();
         metaCache = (Map<String, Map<String, Map<String, Object>>>) objReader.read(this, topologyWebFileName);
         if (metaCache == null) metaCache = new HashMap<String, Map<String, Map<String, Object>>>();
index 1c05bbcd7ea94dd6459b46f76a277bf5930ded2f..cb6f2b6973863f9bb2cb937f38fd51d2eb55668c 100644 (file)
@@ -3,19 +3,19 @@
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
   xmlns:context="http://www.springframework.org/schema/context"\r
   xmlns:mvc="http://www.springframework.org/schema/mvc"\r
-  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \r
+  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\r
                       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd\r
                       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">\r
 \r
   <context:component-scan base-package="org.opendaylight.controller.topology.web"/>\r
-  \r
+\r
   <mvc:resources mapping="/js/**" location="/js/" />\r
   <mvc:resources mapping="/css/**" location="/css/" />\r
   <mvc:resources mapping="/img/**" location="/img/" />\r
   <mvc:annotation-driven/>\r
-  \r
+\r
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">\r
-       <property name="prefix" value="/WEB-INF/jsp/"/>\r
-       <property name="suffix" value=".jsp"/>\r
+        <property name="prefix" value="/WEB-INF/jsp/"/>\r
+        <property name="suffix" value=".jsp"/>\r
   </bean>\r
 </beans>\r
index 274908caec7610ff8d541a36eed882ce7e8a57b4..c37fffe500402c9229337e38735781a7b55176e8 100644 (file)
@@ -1,78 +1,78 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>free access</web-resource-name>
-                       <url-pattern>/js/*</url-pattern>
-                       <url-pattern>/images/*</url-pattern>
-                       <url-pattern>/css/*</url-pattern>
-                       <url-pattern>/favicon.ico</url-pattern>
-               </web-resource-collection>
-       </security-constraint>
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>free access</web-resource-name>
+                        <url-pattern>/js/*</url-pattern>
+                        <url-pattern>/images/*</url-pattern>
+                        <url-pattern>/css/*</url-pattern>
+                        <url-pattern>/favicon.ico</url-pattern>
+                </web-resource-collection>
+        </security-constraint>
 
-       <security-constraint>
-               <display-name>TopologyApp</display-name>
-               <web-resource-collection>
-                       <web-resource-name>TopoGUI</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-constraint>
+                <display-name>TopologyApp</display-name>
+                <web-resource-collection>
+                        <web-resource-name>TopoGUI</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
-       <login-config>
-               <auth-method>FORM</auth-method>
-               <form-login-config>
-                       <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
-                       <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
-               </form-login-config>
-       </login-config>
+        <login-config>
+                <auth-method>FORM</auth-method>
+                <form-login-config>
+                        <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
+                        <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
+                </form-login-config>
+        </login-config>
 
     <error-page>
             <error-code>403</error-code>
             <location>/WEB-INF/jsp/autherror.jsp</location>
     </error-page>
 
-       <servlet>
-               <servlet-name>Topology</servlet-name>
-               <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
-               <load-on-startup>1</load-on-startup>
-       </servlet>
+        <servlet>
+                <servlet-name>Topology</servlet-name>
+                <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
+                <load-on-startup>1</load-on-startup>
+        </servlet>
 
 
 
-       <servlet-mapping>
-               <servlet-name>Topology</servlet-name>
-               <url-pattern>/</url-pattern>
-       </servlet-mapping>
+        <servlet-mapping>
+                <servlet-name>Topology</servlet-name>
+                <url-pattern>/</url-pattern>
+        </servlet-mapping>
 
-       <listener>
-               <listener-class>org.opendaylight.controller.web.ControllerUISessionManager</listener-class>
-       </listener>
+        <listener>
+                <listener-class>org.opendaylight.controller.web.ControllerUISessionManager</listener-class>
+        </listener>
 
-       <session-config>
-               <cookie-config>
-                       <path>/</path>
-               </cookie-config>
-       </session-config>
+        <session-config>
+                <cookie-config>
+                        <path>/</path>
+                </cookie-config>
+        </session-config>
 
 
 </web-app>
index e26e7c666b1a37a5ad1c3cf524162deb3548753c..e33af082b6f630b52e8c8bbed5211b5bcb082826 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved. 
+ * 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,
@@ -16,32 +16,32 @@ import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.utils.NodeCreator;
 import org.opendaylight.controller.switchmanager.SwitchConfig;
 import org.opendaylight.controller.topology.web.Topology.NodeBean;
-               
+
 public class TopologyTest {
 
-       @Test
-       public void testCreateNodeBean() {
-               Topology topology = new Topology();
-               Node node = NodeCreator.createOFNode(new Long(3));
-               String description = "foo";
-               
-               NodeBean bean = topology.createNodeBean(description, node);
-               
-               assertNotNull(bean);
-               assertEquals(bean.id, node.toString());
-               assertEquals(bean.name, "foo");
-               
-               bean = topology.createNodeBean(null, node);
-               
-               assertNotNull(bean);
-               assertEquals(bean.id, node.toString());
-               assertEquals(bean.name, bean.id);
-               
-               bean = topology.createNodeBean("   ", node);
-               
-               assertNotNull(bean);
-               assertEquals(bean.id, node.toString());
-               assertEquals(bean.name, bean.id);
-       }
+        @Test
+        public void testCreateNodeBean() {
+                Topology topology = new Topology();
+                Node node = NodeCreator.createOFNode(new Long(3));
+                String description = "foo";
+
+                NodeBean bean = topology.createNodeBean(description, node);
+
+                assertNotNull(bean);
+                assertEquals(bean.id, node.toString());
+                assertEquals(bean.name, "foo");
+
+                bean = topology.createNodeBean(null, node);
+
+                assertNotNull(bean);
+                assertEquals(bean.id, node.toString());
+                assertEquals(bean.name, bean.id);
+
+                bean = topology.createNodeBean("   ", node);
+
+                assertNotNull(bean);
+                assertEquals(bean.id, node.toString());
+                assertEquals(bean.name, bean.id);
+        }
 
 }
index f145c568b58b18bf62efdda84eadbadefb5934b7..bde4152f5bdfd59c3631a5a80fbaccfd5011343a 100644 (file)
@@ -231,10 +231,10 @@ public class Troubleshoot implements IDaylightWeb {
         Match match = flow.getMatch();
         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                 .getInstance(ISwitchManager.class, containerName, this);
-        String desc = (switchManager == null)? 
-                       "" : switchManager.getNodeDescription(node);
-        desc = (desc.isEmpty() || desc.equalsIgnoreCase("none"))? 
-                       node.toString(): desc;
+        String desc = (switchManager == null)?
+                        "" : switchManager.getNodeDescription(node);
+        desc = (desc.isEmpty() || desc.equalsIgnoreCase("none"))?
+                        node.toString(): desc;
         row.put("nodeName", desc);
         if (match.isPresent(MatchType.IN_PORT)) {
             row.put(MatchType.IN_PORT.id(), ((NodeConnector) flow.getMatch()
@@ -300,7 +300,7 @@ public class Troubleshoot implements IDaylightWeb {
             Short tpSrc = (Short) (flow.getMatch().getField(MatchType.TP_SRC)
                     .getValue());
             row.put(MatchType.TP_SRC.id(),
-                       String.valueOf(NetUtils.getUnsignedShort(tpSrc)));
+                        String.valueOf(NetUtils.getUnsignedShort(tpSrc)));
         } else {
             row.put(MatchType.TP_SRC.id(), "*");
         }
@@ -308,7 +308,7 @@ public class Troubleshoot implements IDaylightWeb {
             Short tpDst = (Short) (flow.getMatch().getField(MatchType.TP_DST)
                     .getValue());
             row.put(MatchType.TP_DST.id(),
-                       String.valueOf(NetUtils.getUnsignedShort(tpDst)));
+                        String.valueOf(NetUtils.getUnsignedShort(tpDst)));
         } else {
             row.put(MatchType.TP_DST.id(), "*");
         }
index 877617a97567704ee93e4b17e82dc432ec7db6c9..91e22f6dad05a7491979a83c728dafdcfec79811 100644 (file)
@@ -3,19 +3,19 @@
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
   xmlns:context="http://www.springframework.org/schema/context"\r
   xmlns:mvc="http://www.springframework.org/schema/mvc"\r
-  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \r
+  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\r
                       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd\r
                       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">\r
 \r
   <context:component-scan base-package="org.opendaylight.controller.troubleshoot.web"/>\r
-  \r
+\r
   <mvc:resources mapping="/js/**" location="/js/" />\r
   <mvc:resources mapping="/css/**" location="/css/" />\r
   <mvc:resources mapping="/img/**" location="/img/" />\r
   <mvc:annotation-driven/>\r
-  \r
+\r
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">\r
-       <property name="prefix" value="/WEB-INF/jsp/"/>\r
-       <property name="suffix" value=".jsp"/>\r
+        <property name="prefix" value="/WEB-INF/jsp/"/>\r
+        <property name="suffix" value=".jsp"/>\r
   </bean>\r
 </beans>\r
index 47d38f9a5379837eea18988565bc14b052e671c8..2d89e9d9753b464b0d7a6af4b23a57ac4449c20c 100644 (file)
@@ -1,81 +1,81 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-       version="3.0">
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+        version="3.0">
 
-       <servlet>
-               <servlet-name>Troubleshoot</servlet-name>
-               <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
-               <load-on-startup>1</load-on-startup>
-       </servlet>
+        <servlet>
+                <servlet-name>Troubleshoot</servlet-name>
+                <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
+                <load-on-startup>1</load-on-startup>
+        </servlet>
 
-       <servlet-mapping>
-               <servlet-name>Troubleshoot</servlet-name>
-               <url-pattern>/</url-pattern>
-       </servlet-mapping>
+        <servlet-mapping>
+                <servlet-name>Troubleshoot</servlet-name>
+                <url-pattern>/</url-pattern>
+        </servlet-mapping>
 
 
 
-       <security-constraint>
-               <web-resource-collection>
-                       <web-resource-name>free access</web-resource-name>
-                       <url-pattern>/js/*</url-pattern>
-                       <url-pattern>/images/*</url-pattern>
-                       <url-pattern>/css/*</url-pattern>
-                       <url-pattern>/favicon.ico</url-pattern>
-               </web-resource-collection>
-       </security-constraint>
+        <security-constraint>
+                <web-resource-collection>
+                        <web-resource-name>free access</web-resource-name>
+                        <url-pattern>/js/*</url-pattern>
+                        <url-pattern>/images/*</url-pattern>
+                        <url-pattern>/css/*</url-pattern>
+                        <url-pattern>/favicon.ico</url-pattern>
+                </web-resource-collection>
+        </security-constraint>
 
-       <security-constraint>
-               <display-name>TroubleShootApp</display-name>
-               <web-resource-collection>
-                       <web-resource-name>TroubleShootGUI</web-resource-name>
-                       <url-pattern>/*</url-pattern>
-               </web-resource-collection>
-               <auth-constraint>
-                       <role-name>System-Admin</role-name>
-                       <role-name>Network-Admin</role-name>
-                       <role-name>Network-Operator</role-name>
-                       <role-name>Container-User</role-name>
-               </auth-constraint>
-       </security-constraint>
+        <security-constraint>
+                <display-name>TroubleShootApp</display-name>
+                <web-resource-collection>
+                        <web-resource-name>TroubleShootGUI</web-resource-name>
+                        <url-pattern>/*</url-pattern>
+                </web-resource-collection>
+                <auth-constraint>
+                        <role-name>System-Admin</role-name>
+                        <role-name>Network-Admin</role-name>
+                        <role-name>Network-Operator</role-name>
+                        <role-name>Container-User</role-name>
+                </auth-constraint>
+        </security-constraint>
 
-       <security-role>
-               <role-name>System-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Admin</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Network-Operator</role-name>
-       </security-role>
-       <security-role>
-               <role-name>Container-User</role-name>
-       </security-role>
+        <security-role>
+                <role-name>System-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Admin</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Network-Operator</role-name>
+        </security-role>
+        <security-role>
+                <role-name>Container-User</role-name>
+        </security-role>
 
 
-       <login-config>
-               <auth-method>FORM</auth-method>
-               <form-login-config>
-                       <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
-                       <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
-               </form-login-config>
-       </login-config>
+        <login-config>
+                <auth-method>FORM</auth-method>
+                <form-login-config>
+                        <form-login-page>/WEB-INF/jsp/login.jsp</form-login-page>
+                        <form-error-page>/WEB-INF/jsp/error.jsp</form-error-page>
+                </form-login-config>
+        </login-config>
 
     <error-page>
             <error-code>403</error-code>
             <location>/WEB-INF/jsp/autherror.jsp</location>
     </error-page>
 
-       <listener>
-               <listener-class>org.opendaylight.controller.web.ControllerUISessionManager</listener-class>
-       </listener>
+        <listener>
+                <listener-class>org.opendaylight.controller.web.ControllerUISessionManager</listener-class>
+        </listener>
 
-       <session-config>
-               <cookie-config>
-                       <path>/</path>
-               </cookie-config>
-       </session-config>
+        <session-config>
+                <cookie-config>
+                        <path>/</path>
+                </cookie-config>
+        </session-config>