From b731e2f1dd0972409b136aebc7b463dd72c9cfad Mon Sep 17 00:00:00 2001 From: CNlucius Date: Tue, 13 Sep 2016 11:40:12 +0800 Subject: ONOSFW-171 O/S-SFC-ONOS scenario documentation Change-Id: I51ae1cf736ea24ab6680f8edca1b2bf5dd598365 Signed-off-by: CNlucius --- framework/src/onos/utils/catalyst/pom.xml | 62 -- .../java/org/onlab/catalyst/OnlabCatalyst.java | 7 - .../main/java/org/onlab/catalyst/package-info.java | 4 - framework/src/onos/utils/jdvue/bin/jdvue | 31 - framework/src/onos/utils/jdvue/bin/jdvue-scan | 12 - framework/src/onos/utils/jdvue/pom.xml | 108 -- .../src/main/java/org/onlab/jdvue/Catalog.java | 406 -------- .../src/main/java/org/onlab/jdvue/Dependency.java | 82 -- .../main/java/org/onlab/jdvue/DependencyCycle.java | 133 --- .../java/org/onlab/jdvue/DependencyViewer.java | 203 ---- .../src/main/java/org/onlab/jdvue/JavaEntity.java | 59 -- .../src/main/java/org/onlab/jdvue/JavaPackage.java | 94 -- .../src/main/java/org/onlab/jdvue/JavaSource.java | 115 --- .../main/java/org/onlab/jdvue/package-info.java | 20 - .../main/resources/org/onlab/jdvue/d3.v3.min.js | 5 - .../src/main/resources/org/onlab/jdvue/index.html | 371 ------- .../src/test/java/org/onlab/jdvue/CatalogTest.java | 58 -- .../java/org/onlab/jdvue/DependencyCycleTest.java | 62 -- .../test/java/org/onlab/jdvue/DependencyTest.java | 44 - .../java/org/onlab/jdvue/DependencyViewerTest.java | 46 - .../onos/utils/jdvue/src/test/resources/catalog.db | 33 - .../utils/jdvue/src/test/resources/catalog.html | 376 ------- .../utils/jdvue/src/test/resources/expected.html | 376 ------- framework/src/onos/utils/jnc/pom.xml | 102 -- framework/src/onos/utils/junit/pom.xml | 57 - .../main/java/org/onlab/junit/ExceptionTest.java | 55 - .../org/onlab/junit/ImmutableClassChecker.java | 168 --- .../main/java/org/onlab/junit/IntegrationTest.java | 25 - .../org/onlab/junit/NullScheduledExecutor.java | 135 --- .../src/main/java/org/onlab/junit/TestTools.java | 227 ---- .../src/main/java/org/onlab/junit/TestUtils.java | 207 ---- .../java/org/onlab/junit/UtilityClassChecker.java | 149 --- .../main/java/org/onlab/junit/package-info.java | 20 - .../controller/impl/ControllerTestKeystore.jks | Bin 1295 -> 0 bytes .../org/onlab/junit/ImmutableClassCheckerTest.java | 135 --- .../test/java/org/onlab/junit/TestToolsTest.java | 47 - .../test/java/org/onlab/junit/TestUtilsTest.java | 185 ---- .../org/onlab/junit/UtilityClassCheckerTest.java | 160 --- framework/src/onos/utils/misc/pom.xml | 87 -- .../main/java/org/onlab/graph/AbstractEdge.java | 76 -- .../org/onlab/graph/AbstractGraphPathSearch.java | 316 ------ .../java/org/onlab/graph/AdjacencyListsGraph.java | 122 --- .../org/onlab/graph/BellmanFordGraphSearch.java | 60 -- .../java/org/onlab/graph/BreadthFirstSearch.java | 79 -- .../java/org/onlab/graph/DefaultMutablePath.java | 136 --- .../src/main/java/org/onlab/graph/DefaultPath.java | 103 -- .../java/org/onlab/graph/DepthFirstSearch.java | 183 ---- .../java/org/onlab/graph/DijkstraGraphSearch.java | 97 -- .../java/org/onlab/graph/DisjointPathPair.java | 137 --- .../misc/src/main/java/org/onlab/graph/Edge.java | 39 - .../src/main/java/org/onlab/graph/EdgeWeight.java | 31 - .../src/main/java/org/onlab/graph/GAOrganism.java | 53 - .../main/java/org/onlab/graph/GAPopulation.java | 90 -- .../misc/src/main/java/org/onlab/graph/Graph.java | 59 -- .../main/java/org/onlab/graph/GraphPathSearch.java | 87 -- .../src/main/java/org/onlab/graph/GraphSearch.java | 43 - .../misc/src/main/java/org/onlab/graph/Heap.java | 211 ---- .../java/org/onlab/graph/KshortestPathSearch.java | 286 ----- .../onlab/graph/MutableAdjacencyListsGraph.java | 160 --- .../main/java/org/onlab/graph/MutableGraph.java | 59 -- .../src/main/java/org/onlab/graph/MutablePath.java | 62 -- .../misc/src/main/java/org/onlab/graph/Path.java | 45 - .../main/java/org/onlab/graph/SrlgGraphSearch.java | 253 ----- .../java/org/onlab/graph/SuurballeGraphSearch.java | 193 ---- .../java/org/onlab/graph/TarjanGraphSearch.java | 212 ---- .../misc/src/main/java/org/onlab/graph/Vertex.java | 22 - .../main/java/org/onlab/graph/package-info.java | 20 - .../main/java/org/onlab/metrics/EventMetric.java | 118 --- .../java/org/onlab/metrics/MetricsComponent.java | 60 -- .../onlab/metrics/MetricsComponentRegistry.java | 36 - .../java/org/onlab/metrics/MetricsFeature.java | 41 - .../java/org/onlab/metrics/MetricsManager.java | 304 ------ .../java/org/onlab/metrics/MetricsService.java | 178 ---- .../main/java/org/onlab/metrics/MetricsUtil.java | 56 - .../main/java/org/onlab/metrics/package-info.java | 20 - .../misc/src/main/java/org/onlab/packet/ARP.java | 439 -------- .../src/main/java/org/onlab/packet/BasePacket.java | 127 --- .../src/main/java/org/onlab/packet/ChassisId.java | 86 -- .../misc/src/main/java/org/onlab/packet/DHCP.java | 632 ------------ .../src/main/java/org/onlab/packet/DHCPOption.java | 136 --- .../main/java/org/onlab/packet/DHCPPacketType.java | 116 --- .../misc/src/main/java/org/onlab/packet/Data.java | 132 --- .../org/onlab/packet/DeserializationException.java | 32 - .../main/java/org/onlab/packet/Deserializer.java | 36 - .../misc/src/main/java/org/onlab/packet/EAP.java | 264 ----- .../misc/src/main/java/org/onlab/packet/EAPOL.java | 199 ---- .../src/main/java/org/onlab/packet/EthType.java | 159 --- .../src/main/java/org/onlab/packet/Ethernet.java | 718 ------------- .../misc/src/main/java/org/onlab/packet/ICMP.java | 223 ---- .../misc/src/main/java/org/onlab/packet/ICMP6.java | 366 ------- .../misc/src/main/java/org/onlab/packet/IGMP.java | 335 ------ .../src/main/java/org/onlab/packet/IGMPGroup.java | 98 -- .../main/java/org/onlab/packet/IGMPMembership.java | 158 --- .../src/main/java/org/onlab/packet/IGMPQuery.java | 202 ---- .../src/main/java/org/onlab/packet/IPacket.java | 89 -- .../misc/src/main/java/org/onlab/packet/IPv4.java | 733 ------------- .../misc/src/main/java/org/onlab/packet/IPv6.java | 384 ------- .../src/main/java/org/onlab/packet/Ip4Address.java | 174 ---- .../src/main/java/org/onlab/packet/Ip4Prefix.java | 104 -- .../src/main/java/org/onlab/packet/Ip6Address.java | 152 --- .../src/main/java/org/onlab/packet/Ip6Prefix.java | 93 -- .../src/main/java/org/onlab/packet/IpAddress.java | 559 ---------- .../src/main/java/org/onlab/packet/IpPrefix.java | 303 ------ .../misc/src/main/java/org/onlab/packet/LLC.java | 102 -- .../misc/src/main/java/org/onlab/packet/LLDP.java | 300 ------ .../org/onlab/packet/LLDPOrganizationalTLV.java | 225 ---- .../src/main/java/org/onlab/packet/LLDPTLV.java | 165 --- .../misc/src/main/java/org/onlab/packet/MPLS.java | 162 --- .../src/main/java/org/onlab/packet/MacAddress.java | 218 ---- .../src/main/java/org/onlab/packet/MplsLabel.java | 74 -- .../src/main/java/org/onlab/packet/ONOSLLDP.java | 185 ---- .../misc/src/main/java/org/onlab/packet/PIM.java | 299 ------ .../main/java/org/onlab/packet/PacketUtils.java | 84 -- .../src/main/java/org/onlab/packet/RADIUS.java | 423 -------- .../java/org/onlab/packet/RADIUSAttribute.java | 142 --- .../misc/src/main/java/org/onlab/packet/TCP.java | 462 --------- .../src/main/java/org/onlab/packet/TpPort.java | 104 -- .../misc/src/main/java/org/onlab/packet/UDP.java | 306 ------ .../src/main/java/org/onlab/packet/VlanId.java | 102 -- .../java/org/onlab/packet/ipv6/Authentication.java | 300 ------ .../java/org/onlab/packet/ipv6/BaseOptions.java | 260 ----- .../org/onlab/packet/ipv6/DestinationOptions.java | 29 - .../onlab/packet/ipv6/EncapSecurityPayload.java | 188 ---- .../main/java/org/onlab/packet/ipv6/Fragment.java | 253 ----- .../org/onlab/packet/ipv6/HopByHopOptions.java | 29 - .../org/onlab/packet/ipv6/IExtensionHeader.java | 37 - .../main/java/org/onlab/packet/ipv6/Routing.java | 291 ------ .../java/org/onlab/packet/ipv6/package-info.java | 20 - .../onlab/packet/ndp/NeighborAdvertisement.java | 278 ----- .../onlab/packet/ndp/NeighborDiscoveryOptions.java | 281 ----- .../org/onlab/packet/ndp/NeighborSolicitation.java | 192 ---- .../main/java/org/onlab/packet/ndp/Redirect.java | 225 ---- .../org/onlab/packet/ndp/RouterAdvertisement.java | 325 ------ .../org/onlab/packet/ndp/RouterSolicitation.java | 155 --- .../java/org/onlab/packet/ndp/package-info.java | 21 - .../main/java/org/onlab/packet/package-info.java | 21 - .../java/org/onlab/packet/pim/PIMAddrGroup.java | 259 ----- .../java/org/onlab/packet/pim/PIMAddrSource.java | 282 ----- .../java/org/onlab/packet/pim/PIMAddrUnicast.java | 185 ---- .../main/java/org/onlab/packet/pim/PIMHello.java | 118 --- .../java/org/onlab/packet/pim/PIMHelloOption.java | 147 --- .../java/org/onlab/packet/pim/PIMJoinPrune.java | 271 ----- .../java/org/onlab/packet/pim/package-info.java | 21 - .../java/org/onlab/util/AbstractAccumulator.java | 214 ---- .../src/main/java/org/onlab/util/Accumulator.java | 49 - .../src/main/java/org/onlab/util/Bandwidth.java | 149 --- .../main/java/org/onlab/util/BlockingBoolean.java | 97 -- .../java/org/onlab/util/BoundedThreadPool.java | 176 ---- .../org/onlab/util/ByteArraySizeHashPrinter.java | 69 -- .../misc/src/main/java/org/onlab/util/Counter.java | 139 --- .../src/main/java/org/onlab/util/DataRateUnit.java | 64 -- .../main/java/org/onlab/util/DefaultHashMap.java | 42 - .../src/main/java/org/onlab/util/Frequency.java | 181 ---- .../src/main/java/org/onlab/util/GeoLocation.java | 85 -- .../java/org/onlab/util/GroupedThreadFactory.java | 88 -- .../misc/src/main/java/org/onlab/util/HexDump.java | 57 - .../src/main/java/org/onlab/util/HexString.java | 148 --- .../java/org/onlab/util/ItemNotFoundException.java | 46 - .../main/java/org/onlab/util/KryoNamespace.java | 437 -------- .../java/org/onlab/util/NewConcurrentHashMap.java | 47 - .../util/PositionalParameterStringFormatter.java | 48 - .../main/java/org/onlab/util/RetryingFunction.java | 60 -- .../main/java/org/onlab/util/RichComparable.java | 45 - .../java/org/onlab/util/SharedExecutorService.java | 138 --- .../main/java/org/onlab/util/SharedExecutors.java | 123 --- .../java/org/onlab/util/SlidingWindowCounter.java | 129 --- .../src/main/java/org/onlab/util/Spectrum.java | 55 - .../misc/src/main/java/org/onlab/util/Timer.java | 52 - .../misc/src/main/java/org/onlab/util/Tools.java | 577 ----------- .../src/main/java/org/onlab/util/TriConsumer.java | 35 - .../src/main/java/org/onlab/util/package-info.java | 20 - .../java/org/onlab/graph/AbstractEdgeTest.java | 37 - .../onlab/graph/AbstractGraphPathSearchTest.java | 61 -- .../org/onlab/graph/AdjacencyListsGraphTest.java | 72 -- .../onlab/graph/BellmanFordGraphSearchTest.java | 77 -- .../org/onlab/graph/BreadthFirstSearchTest.java | 100 -- .../org/onlab/graph/DefaultMutablePathTest.java | 110 -- .../test/java/org/onlab/graph/DefaultPathTest.java | 57 - .../java/org/onlab/graph/DepthFirstSearchTest.java | 97 -- .../org/onlab/graph/DijkstraGraphSearchTest.java | 165 --- .../java/org/onlab/graph/DisjointPathPairTest.java | 43 - .../src/test/java/org/onlab/graph/GraphTest.java | 66 -- .../src/test/java/org/onlab/graph/HeapTest.java | 97 -- .../org/onlab/graph/KshortestPathSearchTest.java | 197 ---- .../java/org/onlab/graph/SrlgGraphSearchTest.java | 174 ---- .../org/onlab/graph/SuurballeGraphSearchTest.java | 154 --- .../org/onlab/graph/TarjanGraphSearchTest.java | 125 --- .../src/test/java/org/onlab/graph/TestEdge.java | 73 -- .../src/test/java/org/onlab/graph/TestVertex.java | 53 - .../src/test/java/org/onlab/packet/ArpTest.java | 88 -- .../src/test/java/org/onlab/packet/DhcpTest.java | 137 --- .../test/java/org/onlab/packet/EthernetTest.java | 103 -- .../src/test/java/org/onlab/packet/ICMP6Test.java | 110 -- .../src/test/java/org/onlab/packet/ICMPTest.java | 70 -- .../src/test/java/org/onlab/packet/IGMPTest.java | 96 -- .../src/test/java/org/onlab/packet/IPv4Test.java | 99 -- .../src/test/java/org/onlab/packet/IPv6Test.java | 154 --- .../test/java/org/onlab/packet/Ip4AddressTest.java | 432 -------- .../test/java/org/onlab/packet/Ip4PrefixTest.java | 534 ---------- .../test/java/org/onlab/packet/Ip6AddressTest.java | 499 --------- .../test/java/org/onlab/packet/Ip6PrefixTest.java | 568 ---------- .../test/java/org/onlab/packet/IpAddressTest.java | 946 ----------------- .../test/java/org/onlab/packet/IpPrefixTest.java | 1080 ------------------- .../src/test/java/org/onlab/packet/LLCTest.java | 70 -- .../src/test/java/org/onlab/packet/LLDPTest.java | 115 --- .../src/test/java/org/onlab/packet/MplsTest.java | 74 -- .../src/test/java/org/onlab/packet/PIMTest.java | 132 --- .../java/org/onlab/packet/PacketTestUtils.java | 98 -- .../src/test/java/org/onlab/packet/TCPTest.java | 163 --- .../src/test/java/org/onlab/packet/UDPTest.java | 134 --- .../src/test/java/org/onlab/packet/VlanIdTest.java | 53 - .../org/onlab/packet/ipv6/AuthenticationTest.java | 121 --- .../org/onlab/packet/ipv6/BaseOptionsTest.java | 115 --- .../onlab/packet/ipv6/DestinationOptionsTest.java | 37 - .../packet/ipv6/EncapSecurityPayloadTest.java | 104 -- .../java/org/onlab/packet/ipv6/FragmentTest.java | 113 -- .../org/onlab/packet/ipv6/HopByHopOptionsTest.java | 37 - .../java/org/onlab/packet/ipv6/RoutingTest.java | 128 --- .../packet/ndp/NeighborAdvertisementTest.java | 140 --- .../onlab/packet/ndp/NeighborSolicitationTest.java | 134 --- .../java/org/onlab/packet/ndp/RedirectTest.java | 147 --- .../onlab/packet/ndp/RouterAdvertisementTest.java | 140 --- .../onlab/packet/ndp/RouterSolicitationTest.java | 114 -- .../org/onlab/util/AbstractAccumulatorTest.java | 181 ---- .../test/java/org/onlab/util/BandwidthTest.java | 82 -- .../java/org/onlab/util/BlockingBooleanTest.java | 210 ---- .../java/org/onlab/util/BoundedThreadPoolTest.java | 227 ---- .../onlab/util/ByteArraySizeHashPrinterTest.java | 53 - .../src/test/java/org/onlab/util/CounterTest.java | 86 -- .../java/org/onlab/util/DefaultHashMapTest.java | 81 -- .../test/java/org/onlab/util/FrequencyTest.java | 107 -- .../test/java/org/onlab/util/GeoLocationTest.java | 38 - .../org/onlab/util/GroupedThreadFactoryTest.java | 53 - .../test/java/org/onlab/util/HexStringTest.java | 87 -- .../org/onlab/util/ManuallyAdvancingTimer.java | 522 ---------- .../org/onlab/util/ManuallyAdvancingTimerTest.java | 263 ----- .../PositionalParameterStringFormatterTest.java | 61 -- .../java/org/onlab/util/RetryingFunctionTest.java | 94 -- .../java/org/onlab/util/SharedExecutorsTest.java | 54 - .../org/onlab/util/SlidingWindowCounterTest.java | 105 -- .../src/test/java/org/onlab/util/ToolsTest.java | 76 -- framework/src/onos/utils/netty/pom.xml | 83 -- .../main/java/org/onlab/netty/DecoderState.java | 31 - .../main/java/org/onlab/netty/InternalMessage.java | 66 -- .../main/java/org/onlab/netty/MessageDecoder.java | 115 --- .../main/java/org/onlab/netty/MessageEncoder.java | 98 -- .../main/java/org/onlab/netty/NettyMessaging.java | 454 -------- .../main/java/org/onlab/netty/package-info.java | 20 - framework/src/onos/utils/nio/pom.xml | 58 -- .../main/java/org/onlab/nio/AbstractMessage.java | 30 - .../src/main/java/org/onlab/nio/AcceptorLoop.java | 123 --- .../nio/src/main/java/org/onlab/nio/IOLoop.java | 302 ------ .../nio/src/main/java/org/onlab/nio/Message.java | 30 - .../src/main/java/org/onlab/nio/MessageStream.java | 424 -------- .../src/main/java/org/onlab/nio/SelectorLoop.java | 175 ---- .../src/main/java/org/onlab/nio/package-info.java | 21 - .../java/org/onlab/nio/service/DefaultIOLoop.java | 66 -- .../java/org/onlab/nio/service/DefaultMessage.java | 104 -- .../onlab/nio/service/DefaultMessageStream.java | 139 --- .../org/onlab/nio/service/IOLoopMessaging.java | 334 ------ .../java/org/onlab/nio/service/package-info.java | 20 - .../test/java/org/onlab/nio/AbstractLoopTest.java | 60 -- .../test/java/org/onlab/nio/AcceptorLoopTest.java | 87 -- .../java/org/onlab/nio/IOLoopIntegrationTest.java | 82 -- .../test/java/org/onlab/nio/IOLoopTestClient.java | 324 ------ .../test/java/org/onlab/nio/IOLoopTestServer.java | 256 ----- .../test/java/org/onlab/nio/MessageStreamTest.java | 359 ------- .../src/test/java/org/onlab/nio/MockSelector.java | 85 -- .../src/test/java/org/onlab/nio/TestMessage.java | 56 - .../test/java/org/onlab/nio/TestMessageStream.java | 89 -- framework/src/onos/utils/osgi/pom.xml | 46 - .../org/onlab/osgi/DefaultServiceDirectory.java | 53 - .../main/java/org/onlab/osgi/ServiceDirectory.java | 34 - .../org/onlab/osgi/ServiceNotFoundException.java | 46 - .../src/main/java/org/onlab/osgi/package-info.java | 20 - .../org/onlab/osgi/ComponentContextAdapter.java | 118 --- .../java/org/onlab/osgi/TestServiceDirectory.java | 46 - framework/src/onos/utils/pom.xml | 69 -- framework/src/onos/utils/rest/pom.xml | 53 - .../src/main/java/org/onlab/rest/BaseResource.java | 57 - .../src/main/java/org/onlab/rest/package-info.java | 20 - framework/src/onos/utils/stc/bin/stc | 12 - framework/src/onos/utils/stc/bin/stc-launcher | 19 - framework/src/onos/utils/stc/pom.xml | 122 --- framework/src/onos/utils/stc/sample/scenario.xml | 20 - .../stc/src/main/java/org/onlab/stc/Compiler.java | 541 ---------- .../src/main/java/org/onlab/stc/Coordinator.java | 387 ------- .../src/main/java/org/onlab/stc/Dependency.java | 77 -- .../stc/src/main/java/org/onlab/stc/Group.java | 60 -- .../stc/src/main/java/org/onlab/stc/Main.java | 387 ------- .../stc/src/main/java/org/onlab/stc/Monitor.java | 154 --- .../main/java/org/onlab/stc/MonitorDelegate.java | 31 - .../src/main/java/org/onlab/stc/MonitorLayout.java | 307 ------ .../main/java/org/onlab/stc/MonitorWebSocket.java | 149 --- .../org/onlab/stc/MonitorWebSocketServlet.java | 137 --- .../src/main/java/org/onlab/stc/ProcessFlow.java | 37 - .../stc/src/main/java/org/onlab/stc/Scenario.java | 106 -- .../src/main/java/org/onlab/stc/ScenarioStore.java | 226 ---- .../stc/src/main/java/org/onlab/stc/Step.java | 129 --- .../stc/src/main/java/org/onlab/stc/StepEvent.java | 116 --- .../java/org/onlab/stc/StepProcessListener.java | 50 - .../src/main/java/org/onlab/stc/StepProcessor.java | 141 --- .../src/main/java/org/onlab/stc/package-info.java | 20 - .../onos/utils/stc/src/main/resources/data.json | 1087 -------------------- .../onos/utils/stc/src/main/resources/index.html | 29 - .../src/onos/utils/stc/src/main/resources/stc.css | 37 - .../src/onos/utils/stc/src/main/resources/stc.js | 148 --- .../src/test/java/org/onlab/stc/CompilerTest.java | 86 -- .../test/java/org/onlab/stc/CoordinatorTest.java | 83 -- .../test/java/org/onlab/stc/DependencyTest.java | 68 -- .../stc/src/test/java/org/onlab/stc/GroupTest.java | 54 - .../test/java/org/onlab/stc/MonitorLayoutTest.java | 146 --- .../src/test/java/org/onlab/stc/ScenarioTest.java | 44 - .../test/java/org/onlab/stc/StepProcessorTest.java | 84 -- .../stc/src/test/java/org/onlab/stc/StepTest.java | 62 -- .../resources/org/onlab/stc/layout-basic-nest.xml | 27 - .../test/resources/org/onlab/stc/layout-basic.xml | 25 - .../resources/org/onlab/stc/layout-deep-nest.xml | 41 - .../onlab/stc/layout-staggered-dependencies.xml | 30 - .../test/resources/org/onlab/stc/one-scenario.xml | 20 - .../src/test/resources/org/onlab/stc/scenario.xml | 54 - .../resources/org/onlab/stc/simple-scenario.xml | 26 - .../test/resources/org/onlab/stc/two-scenario.xml | 21 - framework/src/onos/utils/thirdparty/pom.xml | 115 --- .../java/org/onlab/thirdparty/OnlabThirdparty.java | 26 - 325 files changed, 47890 deletions(-) delete mode 100644 framework/src/onos/utils/catalyst/pom.xml delete mode 100644 framework/src/onos/utils/catalyst/src/main/java/org/onlab/catalyst/OnlabCatalyst.java delete mode 100644 framework/src/onos/utils/catalyst/src/main/java/org/onlab/catalyst/package-info.java delete mode 100755 framework/src/onos/utils/jdvue/bin/jdvue delete mode 100755 framework/src/onos/utils/jdvue/bin/jdvue-scan delete mode 100644 framework/src/onos/utils/jdvue/pom.xml delete mode 100644 framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/Catalog.java delete mode 100644 framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/Dependency.java delete mode 100644 framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/DependencyCycle.java delete mode 100644 framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/DependencyViewer.java delete mode 100644 framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaEntity.java delete mode 100644 framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaPackage.java delete mode 100644 framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaSource.java delete mode 100644 framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/package-info.java delete mode 100644 framework/src/onos/utils/jdvue/src/main/resources/org/onlab/jdvue/d3.v3.min.js delete mode 100644 framework/src/onos/utils/jdvue/src/main/resources/org/onlab/jdvue/index.html delete mode 100644 framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/CatalogTest.java delete mode 100644 framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyCycleTest.java delete mode 100644 framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyTest.java delete mode 100644 framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyViewerTest.java delete mode 100644 framework/src/onos/utils/jdvue/src/test/resources/catalog.db delete mode 100644 framework/src/onos/utils/jdvue/src/test/resources/catalog.html delete mode 100644 framework/src/onos/utils/jdvue/src/test/resources/expected.html delete mode 100644 framework/src/onos/utils/jnc/pom.xml delete mode 100644 framework/src/onos/utils/junit/pom.xml delete mode 100644 framework/src/onos/utils/junit/src/main/java/org/onlab/junit/ExceptionTest.java delete mode 100644 framework/src/onos/utils/junit/src/main/java/org/onlab/junit/ImmutableClassChecker.java delete mode 100644 framework/src/onos/utils/junit/src/main/java/org/onlab/junit/IntegrationTest.java delete mode 100644 framework/src/onos/utils/junit/src/main/java/org/onlab/junit/NullScheduledExecutor.java delete mode 100644 framework/src/onos/utils/junit/src/main/java/org/onlab/junit/TestTools.java delete mode 100644 framework/src/onos/utils/junit/src/main/java/org/onlab/junit/TestUtils.java delete mode 100644 framework/src/onos/utils/junit/src/main/java/org/onlab/junit/UtilityClassChecker.java delete mode 100644 framework/src/onos/utils/junit/src/main/java/org/onlab/junit/package-info.java delete mode 100644 framework/src/onos/utils/junit/src/main/resources/org/onosproject/openflow/controller/impl/ControllerTestKeystore.jks delete mode 100644 framework/src/onos/utils/junit/src/test/java/org/onlab/junit/ImmutableClassCheckerTest.java delete mode 100644 framework/src/onos/utils/junit/src/test/java/org/onlab/junit/TestToolsTest.java delete mode 100644 framework/src/onos/utils/junit/src/test/java/org/onlab/junit/TestUtilsTest.java delete mode 100644 framework/src/onos/utils/junit/src/test/java/org/onlab/junit/UtilityClassCheckerTest.java delete mode 100644 framework/src/onos/utils/misc/pom.xml delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AbstractEdge.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AbstractGraphPathSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AdjacencyListsGraph.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/BellmanFordGraphSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/BreadthFirstSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DefaultMutablePath.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DefaultPath.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DepthFirstSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DijkstraGraphSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DisjointPathPair.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Edge.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/EdgeWeight.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GAOrganism.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GAPopulation.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Graph.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GraphPathSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GraphSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Heap.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/KshortestPathSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutableAdjacencyListsGraph.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutableGraph.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutablePath.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Path.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/SrlgGraphSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/SuurballeGraphSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/TarjanGraphSearch.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Vertex.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/graph/package-info.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/EventMetric.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsComponent.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsComponentRegistry.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsFeature.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsManager.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsService.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsUtil.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/package-info.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ARP.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/BasePacket.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ChassisId.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCP.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCPOption.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCPPacketType.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Data.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DeserializationException.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Deserializer.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EAP.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EAPOL.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EthType.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ethernet.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ICMP.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ICMP6.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMP.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPGroup.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPMembership.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPQuery.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPacket.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPv4.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPv6.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip4Address.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip4Prefix.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip6Address.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip6Prefix.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IpAddress.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IpPrefix.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLC.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDP.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDPOrganizationalTLV.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDPTLV.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MPLS.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MacAddress.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MplsLabel.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ONOSLLDP.java delete mode 100755 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/PIM.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/PacketUtils.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/RADIUS.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/RADIUSAttribute.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/TCP.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/TpPort.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/UDP.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/VlanId.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Authentication.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/BaseOptions.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/DestinationOptions.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/EncapSecurityPayload.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Fragment.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/HopByHopOptions.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/IExtensionHeader.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Routing.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/package-info.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/NeighborAdvertisement.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/NeighborDiscoveryOptions.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/NeighborSolicitation.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/Redirect.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/RouterAdvertisement.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/RouterSolicitation.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/package-info.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/package-info.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/pim/PIMAddrGroup.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/pim/PIMAddrSource.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/pim/PIMAddrUnicast.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/pim/PIMHello.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/pim/PIMHelloOption.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/pim/PIMJoinPrune.java delete mode 100755 framework/src/onos/utils/misc/src/main/java/org/onlab/packet/pim/package-info.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/AbstractAccumulator.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/Accumulator.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/Bandwidth.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/BlockingBoolean.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/BoundedThreadPool.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/ByteArraySizeHashPrinter.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/Counter.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/DataRateUnit.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/DefaultHashMap.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/Frequency.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/GeoLocation.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/GroupedThreadFactory.java delete mode 100755 framework/src/onos/utils/misc/src/main/java/org/onlab/util/HexDump.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/HexString.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/ItemNotFoundException.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/KryoNamespace.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/NewConcurrentHashMap.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/PositionalParameterStringFormatter.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/RetryingFunction.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/RichComparable.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/SharedExecutorService.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/SharedExecutors.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/SlidingWindowCounter.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/Spectrum.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/Timer.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/Tools.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/TriConsumer.java delete mode 100644 framework/src/onos/utils/misc/src/main/java/org/onlab/util/package-info.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/AbstractEdgeTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/AbstractGraphPathSearchTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/AdjacencyListsGraphTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/BellmanFordGraphSearchTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/BreadthFirstSearchTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/DefaultMutablePathTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/DefaultPathTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/DepthFirstSearchTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/DijkstraGraphSearchTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/DisjointPathPairTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/GraphTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/HeapTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/KshortestPathSearchTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/SrlgGraphSearchTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/SuurballeGraphSearchTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/TarjanGraphSearchTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/TestEdge.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/graph/TestVertex.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ArpTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/DhcpTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/EthernetTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ICMP6Test.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ICMPTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/IGMPTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/IPv4Test.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/IPv6Test.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/Ip4AddressTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/Ip4PrefixTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/Ip6AddressTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/Ip6PrefixTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/IpAddressTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/IpPrefixTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/LLCTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/LLDPTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/MplsTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/PIMTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/PacketTestUtils.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/TCPTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/UDPTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/VlanIdTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ipv6/AuthenticationTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ipv6/BaseOptionsTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ipv6/DestinationOptionsTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ipv6/EncapSecurityPayloadTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ipv6/FragmentTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ipv6/HopByHopOptionsTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ipv6/RoutingTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ndp/NeighborAdvertisementTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ndp/NeighborSolicitationTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ndp/RedirectTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ndp/RouterAdvertisementTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/packet/ndp/RouterSolicitationTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/AbstractAccumulatorTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/BandwidthTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/BlockingBooleanTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/BoundedThreadPoolTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/ByteArraySizeHashPrinterTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/CounterTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/DefaultHashMapTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/FrequencyTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/GeoLocationTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/GroupedThreadFactoryTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/HexStringTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/ManuallyAdvancingTimer.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/ManuallyAdvancingTimerTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/PositionalParameterStringFormatterTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/RetryingFunctionTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/SharedExecutorsTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/SlidingWindowCounterTest.java delete mode 100644 framework/src/onos/utils/misc/src/test/java/org/onlab/util/ToolsTest.java delete mode 100644 framework/src/onos/utils/netty/pom.xml delete mode 100644 framework/src/onos/utils/netty/src/main/java/org/onlab/netty/DecoderState.java delete mode 100644 framework/src/onos/utils/netty/src/main/java/org/onlab/netty/InternalMessage.java delete mode 100644 framework/src/onos/utils/netty/src/main/java/org/onlab/netty/MessageDecoder.java delete mode 100644 framework/src/onos/utils/netty/src/main/java/org/onlab/netty/MessageEncoder.java delete mode 100644 framework/src/onos/utils/netty/src/main/java/org/onlab/netty/NettyMessaging.java delete mode 100644 framework/src/onos/utils/netty/src/main/java/org/onlab/netty/package-info.java delete mode 100644 framework/src/onos/utils/nio/pom.xml delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/AbstractMessage.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/AcceptorLoop.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/IOLoop.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/Message.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/MessageStream.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/SelectorLoop.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/package-info.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/service/DefaultIOLoop.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/service/DefaultMessage.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/service/DefaultMessageStream.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/service/IOLoopMessaging.java delete mode 100644 framework/src/onos/utils/nio/src/main/java/org/onlab/nio/service/package-info.java delete mode 100644 framework/src/onos/utils/nio/src/test/java/org/onlab/nio/AbstractLoopTest.java delete mode 100644 framework/src/onos/utils/nio/src/test/java/org/onlab/nio/AcceptorLoopTest.java delete mode 100644 framework/src/onos/utils/nio/src/test/java/org/onlab/nio/IOLoopIntegrationTest.java delete mode 100644 framework/src/onos/utils/nio/src/test/java/org/onlab/nio/IOLoopTestClient.java delete mode 100644 framework/src/onos/utils/nio/src/test/java/org/onlab/nio/IOLoopTestServer.java delete mode 100644 framework/src/onos/utils/nio/src/test/java/org/onlab/nio/MessageStreamTest.java delete mode 100644 framework/src/onos/utils/nio/src/test/java/org/onlab/nio/MockSelector.java delete mode 100644 framework/src/onos/utils/nio/src/test/java/org/onlab/nio/TestMessage.java delete mode 100644 framework/src/onos/utils/nio/src/test/java/org/onlab/nio/TestMessageStream.java delete mode 100644 framework/src/onos/utils/osgi/pom.xml delete mode 100644 framework/src/onos/utils/osgi/src/main/java/org/onlab/osgi/DefaultServiceDirectory.java delete mode 100644 framework/src/onos/utils/osgi/src/main/java/org/onlab/osgi/ServiceDirectory.java delete mode 100644 framework/src/onos/utils/osgi/src/main/java/org/onlab/osgi/ServiceNotFoundException.java delete mode 100644 framework/src/onos/utils/osgi/src/main/java/org/onlab/osgi/package-info.java delete mode 100644 framework/src/onos/utils/osgi/src/test/java/org/onlab/osgi/ComponentContextAdapter.java delete mode 100644 framework/src/onos/utils/osgi/src/test/java/org/onlab/osgi/TestServiceDirectory.java delete mode 100644 framework/src/onos/utils/pom.xml delete mode 100644 framework/src/onos/utils/rest/pom.xml delete mode 100644 framework/src/onos/utils/rest/src/main/java/org/onlab/rest/BaseResource.java delete mode 100644 framework/src/onos/utils/rest/src/main/java/org/onlab/rest/package-info.java delete mode 100755 framework/src/onos/utils/stc/bin/stc delete mode 100755 framework/src/onos/utils/stc/bin/stc-launcher delete mode 100644 framework/src/onos/utils/stc/pom.xml delete mode 100644 framework/src/onos/utils/stc/sample/scenario.xml delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/Compiler.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/Coordinator.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/Dependency.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/Group.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/Main.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/Monitor.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/MonitorDelegate.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/MonitorLayout.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/MonitorWebSocket.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/MonitorWebSocketServlet.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/ProcessFlow.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/Scenario.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/ScenarioStore.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/Step.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/StepEvent.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/StepProcessListener.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/StepProcessor.java delete mode 100644 framework/src/onos/utils/stc/src/main/java/org/onlab/stc/package-info.java delete mode 100644 framework/src/onos/utils/stc/src/main/resources/data.json delete mode 100644 framework/src/onos/utils/stc/src/main/resources/index.html delete mode 100644 framework/src/onos/utils/stc/src/main/resources/stc.css delete mode 100644 framework/src/onos/utils/stc/src/main/resources/stc.js delete mode 100644 framework/src/onos/utils/stc/src/test/java/org/onlab/stc/CompilerTest.java delete mode 100644 framework/src/onos/utils/stc/src/test/java/org/onlab/stc/CoordinatorTest.java delete mode 100644 framework/src/onos/utils/stc/src/test/java/org/onlab/stc/DependencyTest.java delete mode 100644 framework/src/onos/utils/stc/src/test/java/org/onlab/stc/GroupTest.java delete mode 100644 framework/src/onos/utils/stc/src/test/java/org/onlab/stc/MonitorLayoutTest.java delete mode 100644 framework/src/onos/utils/stc/src/test/java/org/onlab/stc/ScenarioTest.java delete mode 100644 framework/src/onos/utils/stc/src/test/java/org/onlab/stc/StepProcessorTest.java delete mode 100644 framework/src/onos/utils/stc/src/test/java/org/onlab/stc/StepTest.java delete mode 100644 framework/src/onos/utils/stc/src/test/resources/org/onlab/stc/layout-basic-nest.xml delete mode 100644 framework/src/onos/utils/stc/src/test/resources/org/onlab/stc/layout-basic.xml delete mode 100644 framework/src/onos/utils/stc/src/test/resources/org/onlab/stc/layout-deep-nest.xml delete mode 100644 framework/src/onos/utils/stc/src/test/resources/org/onlab/stc/layout-staggered-dependencies.xml delete mode 100644 framework/src/onos/utils/stc/src/test/resources/org/onlab/stc/one-scenario.xml delete mode 100644 framework/src/onos/utils/stc/src/test/resources/org/onlab/stc/scenario.xml delete mode 100644 framework/src/onos/utils/stc/src/test/resources/org/onlab/stc/simple-scenario.xml delete mode 100644 framework/src/onos/utils/stc/src/test/resources/org/onlab/stc/two-scenario.xml delete mode 100644 framework/src/onos/utils/thirdparty/pom.xml delete mode 100644 framework/src/onos/utils/thirdparty/src/main/java/org/onlab/thirdparty/OnlabThirdparty.java (limited to 'framework/src/onos/utils') diff --git a/framework/src/onos/utils/catalyst/pom.xml b/framework/src/onos/utils/catalyst/pom.xml deleted file mode 100644 index 8a504bbd..00000000 --- a/framework/src/onos/utils/catalyst/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - onlab-utils - org.onosproject - 1.4.0-rc1 - - 4.0.0 - - utils.catalyst - bundle - - ONLab catalyst dependency - - - - io.atomix.catalyst - catalyst-netty - 1.0.0-rc5 - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - io/atomix/catalyst/** - - - - - - package - - shade - - - - - - - org.apache.felix - maven-bundle-plugin - - - - io.atomix.catalyst.* - - - - - - - - \ No newline at end of file diff --git a/framework/src/onos/utils/catalyst/src/main/java/org/onlab/catalyst/OnlabCatalyst.java b/framework/src/onos/utils/catalyst/src/main/java/org/onlab/catalyst/OnlabCatalyst.java deleted file mode 100644 index c3ecc860..00000000 --- a/framework/src/onos/utils/catalyst/src/main/java/org/onlab/catalyst/OnlabCatalyst.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.onlab.catalyst; - -/** - * Created by admin on 11/24/15. - */ -public class OnlabCatalyst { -} diff --git a/framework/src/onos/utils/catalyst/src/main/java/org/onlab/catalyst/package-info.java b/framework/src/onos/utils/catalyst/src/main/java/org/onlab/catalyst/package-info.java deleted file mode 100644 index 1fdb9ea2..00000000 --- a/framework/src/onos/utils/catalyst/src/main/java/org/onlab/catalyst/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Created by admin on 11/24/15. - */ -package org.onlab.catalyst; \ No newline at end of file diff --git a/framework/src/onos/utils/jdvue/bin/jdvue b/framework/src/onos/utils/jdvue/bin/jdvue deleted file mode 100755 index db9d164b..00000000 --- a/framework/src/onos/utils/jdvue/bin/jdvue +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash -#------------------------------------------------------------------------------- -# Java Package Dependency viewer -# -# written by Thomas Vachuska -# -- Doobs -- -#------------------------------------------------------------------------------- - -JDVUE_ROOT=${JDVUE_ROOT:-$(dirname $0)/..} -cd $JDVUE_ROOT -VER=1.4.0-rc1 -JAR=$PWD/target/jdvue-${VER}.jar # start with the dev jar first -cd - >/dev/null - -# If the dev jar is not available, use one from .m2/repository -[ -f ${JAR} ] || JAR=~/.m2/repository/org/onlab/tools/jdvue/${VER}/jdvue-${VER}.jar - -# Assume default project to be the base-name of the argument or of current dir -name=$(basename ${1:-$PWD}) - -# If the -n option is specified use the next argument as the catalog name -[ "$1" = "-n" -a $# -ge 2 ] && name=$2 && shift 2 - -# Use the rest of the arguments as paths to scan for sources to build catalog -find "${@:-.}" -type f -name \*.java \ - | grep -v -E '/lost+found/|/target/|archetype-resources' \ - | xargs grep -E "^[ \t]*import .*;.*|^[ \t]*package .*;.*" \ - | tr -d '\r' > $name.db - -# Now run the Java Dependency Viewer jar on the catalog -java -jar ${JAR} $name && rm $name.db && open $name.html diff --git a/framework/src/onos/utils/jdvue/bin/jdvue-scan b/framework/src/onos/utils/jdvue/bin/jdvue-scan deleted file mode 100755 index 216c68d7..00000000 --- a/framework/src/onos/utils/jdvue/bin/jdvue-scan +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -#------------------------------------------------------------------------------- -# Java Package Dependency scanner -# -# written by Thomas Vachuska -# -- Doobs -- -#------------------------------------------------------------------------------- - -find "${@:-.}" -type f -name \*.java \ - | grep -v -E '/lost+found/|/target/' \ - | xargs grep -E "^[ \t]*import .*;.*|^[ \t]*package .*;.*" \ - | tr -d '\r' > jpd.db diff --git a/framework/src/onos/utils/jdvue/pom.xml b/framework/src/onos/utils/jdvue/pom.xml deleted file mode 100644 index 777eba3d..00000000 --- a/framework/src/onos/utils/jdvue/pom.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - 4.0.0 - - 3.0.4 - - - - org.onosproject - onlab-utils - 1.4.0-rc1 - ../pom.xml - - - jdvue - jar - - Java Package Dependency & Analyzer - - - - true - - - - - com.google.guava - guava - 18.0 - - - com.google.guava - guava-testlib - 18.0 - test - - - com.fasterxml.jackson.core - jackson-databind - 2.4.2 - compile - - - com.fasterxml.jackson.core - jackson-annotations - 2.4.2 - compile - - - org.onosproject - onlab-junit - test - - - - - - - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - - - org.onlab.jdvue.DependencyViewer - - - - - - - package - - shade - - - - - - - - diff --git a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/Catalog.java b/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/Catalog.java deleted file mode 100644 index 40cb99a3..00000000 --- a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/Catalog.java +++ /dev/null @@ -1,406 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static com.google.common.base.MoreObjects.toStringHelper; - -/** - * Produces a package & source catalogue. - * - * @author Thomas Vachuska - */ -public class Catalog { - - private static final String PACKAGE = "package"; - private static final String IMPORT = "import"; - private static final String STATIC = "static"; - private static final String SRC_ROOT = "src/main/java/"; - private static final String WILDCARD = "\\.*$"; - - private final Map sources = new HashMap<>(); - private final Map packages = new HashMap<>(); - private final Set cycles = new HashSet<>(); - private final Set cycleSegments = new HashSet<>(); - private final Map> packageCycles = new HashMap<>(); - private final Map> packageCycleSegments = new HashMap<>(); - - /** - * Loads the catalog from the specified catalog file. - * - * @param catalogPath catalog file path - * @throws IOException if unable to read the catalog file - */ - public void load(String catalogPath) throws IOException { - InputStream is = new FileInputStream(catalogPath); - BufferedReader br = new BufferedReader(new InputStreamReader(is)); - - String line; - while ((line = br.readLine()) != null) { - // Split the line into the two fields: path and pragmas - String fields[] = line.trim().split(":"); - if (fields.length <= 1) { - continue; - } - String path = fields[0]; - - // Now split the pragmas on whitespace and trim punctuation - String pragma[] = fields[1].trim().replaceAll("[;\n\r]", "").split("[\t ]"); - - // Locate (or create) Java source entity based on the path - JavaSource source = getOrCreateSource(path); - - // Now process the package or import statements - if (pragma[0].equals(PACKAGE)) { - processPackageDeclaration(source, pragma[1]); - - } else if (pragma[0].equals(IMPORT)) { - if (pragma[1].equals(STATIC)) { - processImportStatement(source, pragma[2]); - } else { - processImportStatement(source, pragma[1]); - } - } - } - } - - /** - * Analyzes the catalog by resolving imports and identifying circular - * package dependencies. - */ - public void analyze() { - resolveImports(); - findCircularDependencies(); - } - - /** - * Identifies circular package dependencies through what amounts to be a - * depth-first search rooted with each package. - */ - private void findCircularDependencies() { - cycles.clear(); - for (JavaPackage javaPackage : getPackages()) { - findCircularDependencies(javaPackage); - } - - cycleSegments.clear(); - packageCycles.clear(); - packageCycleSegments.clear(); - - for (DependencyCycle cycle : getCycles()) { - recordCycleForPackages(cycle); - cycleSegments.addAll(cycle.getCycleSegments()); - } - } - - /** - * Records the specified cycle into a set for each involved package. - * - * @param cycle cycle to record for involved packages - */ - private void recordCycleForPackages(DependencyCycle cycle) { - for (JavaPackage javaPackage : cycle.getCycle()) { - Set cset = packageCycles.get(javaPackage); - if (cset == null) { - cset = new HashSet<>(); - packageCycles.put(javaPackage, cset); - } - cset.add(cycle); - - Set sset = packageCycleSegments.get(javaPackage); - if (sset == null) { - sset = new HashSet<>(); - packageCycleSegments.put(javaPackage, sset); - } - sset.addAll(cycle.getCycleSegments()); - } - } - - /** - * Identifies circular dependencies in which this package participates - * using depth-first search. - * - * @param javaPackage Java package to inspect for dependency cycles - */ - private void findCircularDependencies(JavaPackage javaPackage) { - // Setup a depth trace anchored at the given java package. - List trace = newTrace(new ArrayList(), javaPackage); - - Set searched = new HashSet<>(); - searchDependencies(javaPackage, trace, searched); - } - - /** - * Generates a new trace using the previous one and a new element - * - * @param trace old search trace - * @param javaPackage package to add to the trace - * @return new search trace - */ - private List newTrace(List trace, - JavaPackage javaPackage) { - List newTrace = new ArrayList<>(trace); - newTrace.add(javaPackage); - return newTrace; - } - - - /** - * Recursive depth-first search through dependency tree - * - * @param javaPackage java package being searched currently - * @param trace search trace - * @param searched set of java packages already searched - */ - private void searchDependencies(JavaPackage javaPackage, - List trace, - Set searched) { - if (!searched.contains(javaPackage)) { - searched.add(javaPackage); - for (JavaPackage dependency : javaPackage.getDependencies()) { - if (trace.contains(dependency)) { - cycles.add(new DependencyCycle(trace, dependency)); - } else { - searchDependencies(dependency, newTrace(trace, dependency), searched); - } - } - } - } - - /** - * Resolves import names of Java sources into imports of entities known - * to this catalog. All other import names will be ignored. - */ - private void resolveImports() { - for (JavaPackage javaPackage : getPackages()) { - Set dependencies = new HashSet<>(); - for (JavaSource source : javaPackage.getSources()) { - Set imports = resolveImports(source); - source.setImports(imports); - dependencies.addAll(importedPackages(imports)); - } - javaPackage.setDependencies(dependencies); - } - } - - /** - * Produces a set of imported Java packages from the specified set of - * Java source entities. - * - * @param imports list of imported Java source entities - * @return list of imported Java packages - */ - private Set importedPackages(Set imports) { - Set packages = new HashSet<>(); - for (JavaEntity entity : imports) { - packages.add(entity instanceof JavaPackage ? (JavaPackage) entity : - ((JavaSource) entity).getPackage()); - } - return packages; - } - - /** - * Resolves import names of the specified Java source into imports of - * entities known to this catalog. All other import names will be ignored. - * - * @param source Java source - * @return list of resolved imports - */ - private Set resolveImports(JavaSource source) { - Set imports = new HashSet<>(); - for (String importName : source.getImportNames()) { - JavaEntity entity = importName.matches(WILDCARD) ? - getPackage(importName.replaceAll(WILDCARD, "")) : - getSource(importName); - if (entity != null) { - imports.add(entity); - } - } - return imports; - } - - /** - * Returns either an existing or a newly created Java package. - * - * @param packageName Java package name - * @return Java package - */ - private JavaPackage getOrCreatePackage(String packageName) { - JavaPackage javaPackage = packages.get(packageName); - if (javaPackage == null) { - javaPackage = new JavaPackage(packageName); - packages.put(packageName, javaPackage); - } - return javaPackage; - } - - /** - * Returns either an existing or a newly created Java source. - * - * @param path Java source path - * @return Java source - */ - private JavaSource getOrCreateSource(String path) { - String name = nameFromPath(path); - JavaSource source = sources.get(name); - if (source == null) { - source = new JavaSource(name, path); - sources.put(name, source); - } - return source; - } - - /** - * Extracts a fully qualified source class name from the given path. - *

- * For now, this implementation assumes standard Maven source structure - * and thus will look for start of package name under 'src/main/java/'. - * If it will not find such a prefix, it will simply return the path as - * the name. - * - * @param path source path - * @return source name - */ - private String nameFromPath(String path) { - int i = path.indexOf(SRC_ROOT); - String name = i < 0 ? path : path.substring(i + SRC_ROOT.length()); - return name.replaceAll("\\.java$", "").replace("/", "."); - } - - /** - * Processes the package declaration pragma for the given source. - * - * @param source Java source - * @param packageName Java package name - */ - private void processPackageDeclaration(JavaSource source, String packageName) { - JavaPackage javaPackage = getOrCreatePackage(packageName); - source.setPackage(javaPackage); - javaPackage.addSource(source); - } - - /** - * Processes the import pragma for the given source. - * - * @param source Java source - * @param name name of the Java entity being imported (class or package) - */ - private void processImportStatement(JavaSource source, String name) { - source.addImportName(name); - } - - /** - * Returns the collection of java sources. - * - * @return collection of java sources - */ - public Collection getSources() { - return Collections.unmodifiableCollection(sources.values()); - } - - /** - * Returns the Java source with the specified name. - * - * @param name Java source name - * @return Java source - */ - public JavaSource getSource(String name) { - return sources.get(name); - } - - /** - * Returns the collection of all Java packages. - * - * @return collection of java packages - */ - public Collection getPackages() { - return Collections.unmodifiableCollection(packages.values()); - } - - /** - * Returns the set of all Java package dependency cycles. - * - * @return set of dependency cycles - */ - public Set getCycles() { - return Collections.unmodifiableSet(cycles); - } - - /** - * Returns the set of all Java package dependency cycle segments. - * - * @return set of dependency cycle segments - */ - public Set getCycleSegments() { - return Collections.unmodifiableSet(cycleSegments); - } - - /** - * Returns the set of dependency cycles which involve the specified package. - * - * @param javaPackage java package - * @return set of dependency cycles - */ - public Set getPackageCycles(JavaPackage javaPackage) { - Set set = packageCycles.get(javaPackage); - return Collections.unmodifiableSet(set == null ? new HashSet() : set); - } - - /** - * Returns the set of dependency cycle segments which involve the specified package. - * - * @param javaPackage java package - * @return set of dependency cycle segments - */ - public Set getPackageCycleSegments(JavaPackage javaPackage) { - Set set = packageCycleSegments.get(javaPackage); - return Collections.unmodifiableSet(set == null ? new HashSet() : set); - } - - /** - * Returns the Java package with the specified name. - * - * @param name Java package name - * @return Java package - */ - public JavaPackage getPackage(String name) { - return packages.get(name); - } - - @Override - public String toString() { - return toStringHelper(this) - .add("packages", packages.size()) - .add("sources", sources.size()) - .add("cycles", cycles.size()) - .add("cycleSegments", cycleSegments.size()).toString(); - } - -} diff --git a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/Dependency.java b/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/Dependency.java deleted file mode 100644 index 21fae479..00000000 --- a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/Dependency.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - -import java.util.Objects; - -import static com.google.common.base.MoreObjects.toStringHelper; - -/** - * Abstraction of a dependency segment. - * - * @author Thomas Vachuska - */ -public class Dependency { - - private final JavaPackage source; - private final JavaPackage target; - - /** - * Creates a dependency from the specified source on the given target. - * - * @param source source of the dependency - * @param target target of the dependency - */ - public Dependency(JavaPackage source, JavaPackage target) { - this.source = source; - this.target = target; - } - - /** - * Returns the dependency source. - * - * @return source Java package - */ - public JavaPackage getSource() { - return source; - } - - /** - * Returns the dependency target. - * - * @return target Java package - */ - public JavaPackage getTarget() { - return target; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof Dependency) { - Dependency that = (Dependency) obj; - return Objects.equals(source, that.source) && - Objects.equals(target, that.target); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(source, target); - } - - @Override - public String toString() { - return toStringHelper(this) - .add("source", source).add("target", target).toString(); - } - -} diff --git a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/DependencyCycle.java b/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/DependencyCycle.java deleted file mode 100644 index 0fc761d4..00000000 --- a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/DependencyCycle.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -import static com.google.common.base.MoreObjects.toStringHelper; - -/** - * Simple representation of a Java package dependency cycle. - */ -public class DependencyCycle { - - private final List cycle; - - /** - * Creates a normalized dependency cycle represented by the specified list - * of Java packages, which are expected to be given in order of dependency. - * List is assumed to be non-empty. - * - * @param cycle list of Java packages in the dependency cycle - * @param cause Java package that caused the cycle - */ - DependencyCycle(List cycle, JavaPackage cause) { - this.cycle = normalize(cycle, cause); - } - - /** - * Produces a normalized dependency cycle list. Normalization is performed - * by rotating the list so that the package with the least lexicographic - * name is at the start of the list. - * - * @param cycle list of Java packages in the dependency cycle - * @param cause Java package that caused the cycle - * @return normalized cycle - */ - private List normalize(List cycle, JavaPackage cause) { - int start = cycle.indexOf(cause); - List clone = new ArrayList<>(cycle.subList(start, cycle.size())); - int leastIndex = findIndexOfLeastName(clone); - Collections.rotate(clone, -leastIndex); - return Collections.unmodifiableList(clone); - } - - /** - * Returns the index of the Java package with the least name. - * - * @param cycle list of Java packages in the dependency cycle - * @return index of the least Java package name - */ - private int findIndexOfLeastName(List cycle) { - int leastIndex = 0; - String leastName = cycle.get(leastIndex).name(); - for (int i = 1, n = cycle.size(); i < n; i++) { - JavaPackage javaPackage = cycle.get(i); - if (leastName.compareTo(javaPackage.name()) > 0) { - leastIndex = i; - leastName = javaPackage.name(); - } - } - return leastIndex; - } - - /** - * Returns the normalized Java package dependency cycle - * - * @return list of packages in the dependency cycle - */ - public List getCycle() { - return cycle; - } - - /** - * Returns the dependency cycle in form of individual dependencies. - * - * @return list of dependencies forming the cycle - */ - public List getCycleSegments() { - List dependencies = new ArrayList<>(); - for (int i = 0, n = cycle.size(); i < n; i++) { - dependencies.add(new Dependency(cycle.get(i), cycle.get(i < n - 1 ? i + 1 : 0))); - } - return dependencies; - } - - @Override - public boolean equals(Object o) { - if (o instanceof DependencyCycle) { - DependencyCycle that = (DependencyCycle) o; - return Objects.equals(cycle, that.cycle); - } - return false; - } - - @Override - public int hashCode() { - return cycle.hashCode(); - } - - @Override - public String toString() { - return toStringHelper(this).add("cycle", cycle).toString(); - } - - public String toShortString() { - StringBuilder sb = new StringBuilder("["); - for (JavaPackage javaPackage : cycle) { - sb.append(javaPackage.name()).append(", "); - } - if (sb.length() > 1) { - sb.delete(sb.length() - 2, sb.length()); - } - sb.append("]"); - return sb.toString(); - } - -} diff --git a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/DependencyViewer.java b/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/DependencyViewer.java deleted file mode 100644 index 32e9ef1c..00000000 --- a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/DependencyViewer.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import java.io.BufferedReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Set; - -/** - * Generator of a self-contained HTML file which serves as a GUI for - * visualizing Java package dependencies carried in the supplied catalog. - * - * The HTML file is an adaptation of D3.js Hierarchical Edge Bundling as - * shown at http://bl.ocks.org/mbostock/7607999. - * - * @author Thomas Vachuska - */ -public class DependencyViewer { - - private static final String JPD_EXT = ".db"; - private static final String HTML_EXT = ".html"; - - private static final String INDEX = "index.html"; - private static final String D3JS = "d3.v3.min.js"; - - private static final String TITLE_PLACEHOLDER = "TITLE_PLACEHOLDER"; - private static final String D3JS_PLACEHOLDER = "D3JS_PLACEHOLDER"; - private static final String DATA_PLACEHOLDER = "DATA_PLACEHOLDER"; - - private final Catalog catalog; - - /** - * Creates a Java package dependency viewer. - * - * @param catalog dependency catalog - */ - public DependencyViewer(Catalog catalog) { - this.catalog = catalog; - } - - /** - * Main program entry point. - * - * @param args command line arguments - */ - public static void main(String[] args) { - Catalog cat = new Catalog(); - DependencyViewer viewer = new DependencyViewer(cat); - try { - String path = args[0]; - cat.load(path + JPD_EXT); - cat.analyze(); - - System.err.println(cat); - viewer.dumpLongestCycle(cat); - viewer.writeHTMLFile(path); - } catch (IOException e) { - System.err.println("Unable to process catalog: " + e.getMessage()); - } - } - - /** - * Prints out the longest cycle; just for kicks. - * @param cat catalog - */ - private void dumpLongestCycle(Catalog cat) { - DependencyCycle longest = null; - for (DependencyCycle cycle : cat.getCycles()) { - if (longest == null || longest.getCycleSegments().size() < cycle.getCycleSegments().size()) { - longest = cycle; - } - } - - if (longest != null) { - for (Dependency dependency : longest.getCycleSegments()) { - System.out.println(dependency); - } - } - } - - /** - * Writes the HTML catalog file for the given viewer. - * - * @param path base file path - * @throws IOException if issues encountered writing the HTML file - */ - public void writeHTMLFile(String path) throws IOException { - String index = slurp(getClass().getResourceAsStream(INDEX)); - String d3js = slurp(getClass().getResourceAsStream(D3JS)); - - FileWriter fw = new FileWriter(path + HTML_EXT); - ObjectWriter writer = new ObjectMapper().writer(); // .writerWithDefaultPrettyPrinter(); - fw.write(index.replace(TITLE_PLACEHOLDER, path) - .replace(D3JS_PLACEHOLDER, d3js) - .replace(DATA_PLACEHOLDER, writer.writeValueAsString(toJson()))); - fw.close(); - } - - /** - * Slurps the specified input stream into a string. - * - * @param stream input stream to be read - * @return string containing the contents of the input stream - * @throws IOException if issues encountered reading from the stream - */ - static String slurp(InputStream stream) throws IOException { - StringBuilder sb = new StringBuilder(); - BufferedReader br = new BufferedReader(new InputStreamReader(stream)); - String line; - while ((line = br.readLine()) != null) { - sb.append(line).append(System.lineSeparator()); - } - br.close(); - return sb.toString(); - } - - // Produces a JSON structure designed to drive the hierarchical visual - // representation of Java package dependencies and any dependency cycles - private JsonNode toJson() { - ObjectMapper mapper = new ObjectMapper(); - ObjectNode root = mapper.createObjectNode(); - root.put("packages", jsonPackages(mapper)); - root.put("cycleSegments", jsonCycleSegments(mapper, catalog.getCycleSegments())); - root.put("summary", jsonSummary(mapper)); - return root; - } - - // Produces a JSON summary of dependencies - private JsonNode jsonSummary(ObjectMapper mapper) { - ObjectNode summary = mapper.createObjectNode(); - summary.put("packages", catalog.getPackages().size()); - summary.put("sources", catalog.getSources().size()); - summary.put("cycles", catalog.getCycles().size()); - summary.put("cycleSegments", catalog.getCycleSegments().size()); - return summary; - } - - // Produces a JSON structure with package dependency data - private JsonNode jsonPackages(ObjectMapper mapper) { - ArrayNode packages = mapper.createArrayNode(); - for (JavaPackage javaPackage : catalog.getPackages()) { - packages.add(json(mapper, javaPackage)); - } - return packages; - } - - // Produces a JSON structure with all cyclic segments - private JsonNode jsonCycleSegments(ObjectMapper mapper, - Set segments) { - ObjectNode cyclicSegments = mapper.createObjectNode(); - for (Dependency dependency : segments) { - String s = dependency.getSource().name(); - String t = dependency.getTarget().name(); - cyclicSegments.put(t + "-" + s, - mapper.createObjectNode().put("s", s).put("t", t)); - } - return cyclicSegments; - } - - // Produces a JSON object structure describing the specified Java package. - private JsonNode json(ObjectMapper mapper, JavaPackage javaPackage) { - ObjectNode node = mapper.createObjectNode(); - - ArrayNode imports = mapper.createArrayNode(); - for (JavaPackage dependency : javaPackage.getDependencies()) { - imports.add(dependency.name()); - } - - Set packageCycles = catalog.getPackageCycles(javaPackage); - Set packageCycleSegments = catalog.getPackageCycleSegments(javaPackage); - - node.put("name", javaPackage.name()); - node.put("size", javaPackage.getSources().size()); - node.put("imports", imports); - node.put("cycleSegments", jsonCycleSegments(mapper, packageCycleSegments)); - node.put("cycleCount", packageCycles.size()); - node.put("cycleSegmentCount", packageCycleSegments.size()); - return node; - } - -} diff --git a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaEntity.java b/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaEntity.java deleted file mode 100644 index e74bdc60..00000000 --- a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaEntity.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - -import java.util.Objects; - -/** - * Abstraction of a Java source entity. - */ -public abstract class JavaEntity { - - private final String name; - - /** - * Creates a new Java source entity with the given name. - * - * @param name source entity name - */ - JavaEntity(String name) { - this.name = name; - } - - /** - * Returns the Java source entity name. - * - * @return source entity name - */ - public String name() { - return name; - } - - @Override - public boolean equals(Object o) { - if (o instanceof JavaEntity) { - JavaEntity that = (JavaEntity) o; - return getClass().equals(that.getClass()) && - Objects.equals(name, that.name); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(name); - } -} diff --git a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaPackage.java b/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaPackage.java deleted file mode 100644 index a15cb4d3..00000000 --- a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaPackage.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import static com.google.common.base.MoreObjects.toStringHelper; - -/** - * Simple abstraction of a Java package for the purpose of tracking - * dependencies and requirements. - * - * @author Thomas Vachuska - */ -public class JavaPackage extends JavaEntity { - - private final Set sources = new HashSet<>(); - private Set dependencies; - - /** - * Creates a new Java package. - * - * @param name java package file name - */ - JavaPackage(String name) { - super(name); - } - - /** - * Returns the set of sources contained in this Java package. - * - * @return set of Java sources - */ - public Set getSources() { - return Collections.unmodifiableSet(sources); - } - - /** - * Adds the specified Java source to the package. Only possible if the - * Java package of the source is the same as this Java package. - * - * @param source Java source to be added - */ - void addSource(JavaSource source) { - if (source.getPackage().equals(this)) { - sources.add(source); - } - } - - /** - * Returns the set of packages directly required by this package. - * - * @return set of Java package dependencies - */ - Set getDependencies() { - return dependencies; - } - - /** - * Sets the set of resolved Java packages on which this package dependens. - * - * @param dependencies set of resolved Java packages - */ - void setDependencies(Set dependencies) { - if (this.dependencies == null) { - this.dependencies = Collections.unmodifiableSet(new HashSet<>(dependencies)); - } - } - - @Override - public String toString() { - return toStringHelper(this) - .add("name", name()) - .add("sources", sources.size()) - .add("dependencies", (dependencies != null ? dependencies.size() : 0)) - .toString(); - } - -} diff --git a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaSource.java b/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaSource.java deleted file mode 100644 index 1376cfee..00000000 --- a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/JavaSource.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - -import java.util.*; - -import static com.google.common.base.MoreObjects.toStringHelper; - -/** - * Simple abstraction of a Java source file for the purpose of tracking - * dependencies and requirements. - * - * @author Thomas Vachuska - */ -public class JavaSource extends JavaEntity { - - private String path; - private JavaPackage javaPackage; - - private final Set importNames = new HashSet<>(); - private Set imports; - - /** - * Creates a new Java source entity. - * - * @param name java source file name - * @param path source file path - */ - JavaSource(String name, String path) { - super(name); - this.path = path; - } - - /** - * Returns the Java package for this Java source. - * - * @return Java package - */ - public JavaPackage getPackage() { - return javaPackage; - } - - /** - * Sets the Java package for this Java source. - * - * @param javaPackage Java package - */ - void setPackage(JavaPackage javaPackage) { - if (this.javaPackage == null) { - this.javaPackage = javaPackage; - } - } - - /** - * Returns the set of resolved imports for this Java source - * - * @return set of imports - */ - public Set getImports() { - return imports; - } - - /** - * Sets the set of resolved imported Java entities for this source. - * - * @param imports set of resolved Java entities imported by this source - */ - void setImports(Set imports) { - if (this.imports == null) { - this.imports = Collections.unmodifiableSet(new HashSet<>(imports)); - } - } - - /** - * Adds a name of an imported, but unresolved, Java entity name. - * - * @param name name of an imported Java entity - */ - void addImportName(String name) { - importNames.add(name); - } - - /** - * Returns the set of imported, but unresolved, Java entity names. - * - * @return set of imported Java entity names - */ - Set getImportNames() { - return importNames; - } - - @Override - public String toString() { - return toStringHelper(this) - .add("name", name()) - .add("javaPackage", (javaPackage != null ? javaPackage.name() : "")) - .add("importNames", importNames.size()) - .add("imports", (imports != null ? imports.size() : 0)) - .toString(); - } - -} diff --git a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/package-info.java b/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/package-info.java deleted file mode 100644 index 2f77ef24..00000000 --- a/framework/src/onos/utils/jdvue/src/main/java/org/onlab/jdvue/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ - -/** - * Utility to analyze Java package dependencies. - */ -package org.onlab.jdvue; \ No newline at end of file diff --git a/framework/src/onos/utils/jdvue/src/main/resources/org/onlab/jdvue/d3.v3.min.js b/framework/src/onos/utils/jdvue/src/main/resources/org/onlab/jdvue/d3.v3.min.js deleted file mode 100644 index 4895e91b..00000000 --- a/framework/src/onos/utils/jdvue/src/main/resources/org/onlab/jdvue/d3.v3.min.js +++ /dev/null @@ -1,5 +0,0 @@ -!function(){function n(n,t){return t>n?-1:n>t?1:n>=t?0:0/0}function t(n){return null!=n&&!isNaN(n)}function e(n){return{left:function(t,e,r,u){for(arguments.length<3&&(r=0),arguments.length<4&&(u=t.length);u>r;){var i=r+u>>>1;n(t[i],e)<0?r=i+1:u=i}return r},right:function(t,e,r,u){for(arguments.length<3&&(r=0),arguments.length<4&&(u=t.length);u>r;){var i=r+u>>>1;n(t[i],e)>0?u=i:r=i+1}return r}}}function r(n){return n.length}function u(n){for(var t=1;n*t%1;)t*=10;return t}function i(n,t){try{for(var e in t)Object.defineProperty(n.prototype,e,{value:t[e],enumerable:!1})}catch(r){n.prototype=t}}function o(){}function a(n){return ia+n in this}function c(n){return n=ia+n,n in this&&delete this[n]}function s(){var n=[];return this.forEach(function(t){n.push(t)}),n}function l(){var n=0;for(var t in this)t.charCodeAt(0)===oa&&++n;return n}function f(){for(var n in this)if(n.charCodeAt(0)===oa)return!1;return!0}function h(){}function g(n,t,e){return function(){var r=e.apply(t,arguments);return r===t?n:r}}function p(n,t){if(t in n)return t;t=t.charAt(0).toUpperCase()+t.substring(1);for(var e=0,r=aa.length;r>e;++e){var u=aa[e]+t;if(u in n)return u}}function v(){}function d(){}function m(n){function t(){for(var t,r=e,u=-1,i=r.length;++ue;e++)for(var u,i=n[e],o=0,a=i.length;a>o;o++)(u=i[o])&&t(u,o,e);return n}function U(n){return sa(n,da),n}function j(n){var t,e;return function(r,u,i){var o,a=n[i].update,c=a.length;for(i!=e&&(e=i,t=0),u>=t&&(t=u+1);!(o=a[t])&&++t0&&(n=n.substring(0,a));var s=ya.get(n);return s&&(n=s,c=Y),a?t?u:r:t?v:i}function O(n,t){return function(e){var r=Zo.event;Zo.event=e,t[0]=this.__data__;try{n.apply(this,t)}finally{Zo.event=r}}}function Y(n,t){var e=O(n,t);return function(n){var t=this,r=n.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||e.call(t,n)}}function I(){var n=".dragsuppress-"+ ++Ma,t="click"+n,e=Zo.select(Wo).on("touchmove"+n,y).on("dragstart"+n,y).on("selectstart"+n,y);if(xa){var r=Bo.style,u=r[xa];r[xa]="none"}return function(i){function o(){e.on(t,null)}e.on(n,null),xa&&(r[xa]=u),i&&(e.on(t,function(){y(),o()},!0),setTimeout(o,0))}}function Z(n,t){t.changedTouches&&(t=t.changedTouches[0]);var e=n.ownerSVGElement||n;if(e.createSVGPoint){var r=e.createSVGPoint();if(0>_a&&(Wo.scrollX||Wo.scrollY)){e=Zo.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var u=e[0][0].getScreenCTM();_a=!(u.f||u.e),e.remove()}return _a?(r.x=t.pageX,r.y=t.pageY):(r.x=t.clientX,r.y=t.clientY),r=r.matrixTransform(n.getScreenCTM().inverse()),[r.x,r.y]}var i=n.getBoundingClientRect();return[t.clientX-i.left-n.clientLeft,t.clientY-i.top-n.clientTop]}function V(){return Zo.event.changedTouches[0].identifier}function X(){return Zo.event.target}function $(){return Wo}function B(n){return n>0?1:0>n?-1:0}function W(n,t,e){return(t[0]-n[0])*(e[1]-n[1])-(t[1]-n[1])*(e[0]-n[0])}function J(n){return n>1?0:-1>n?ba:Math.acos(n)}function G(n){return n>1?Sa:-1>n?-Sa:Math.asin(n)}function K(n){return((n=Math.exp(n))-1/n)/2}function Q(n){return((n=Math.exp(n))+1/n)/2}function nt(n){return((n=Math.exp(2*n))-1)/(n+1)}function tt(n){return(n=Math.sin(n/2))*n}function et(){}function rt(n,t,e){return this instanceof rt?(this.h=+n,this.s=+t,void(this.l=+e)):arguments.length<2?n instanceof rt?new rt(n.h,n.s,n.l):mt(""+n,yt,rt):new rt(n,t,e)}function ut(n,t,e){function r(n){return n>360?n-=360:0>n&&(n+=360),60>n?i+(o-i)*n/60:180>n?o:240>n?i+(o-i)*(240-n)/60:i}function u(n){return Math.round(255*r(n))}var i,o;return n=isNaN(n)?0:(n%=360)<0?n+360:n,t=isNaN(t)?0:0>t?0:t>1?1:t,e=0>e?0:e>1?1:e,o=.5>=e?e*(1+t):e+t-e*t,i=2*e-o,new gt(u(n+120),u(n),u(n-120))}function it(n,t,e){return this instanceof it?(this.h=+n,this.c=+t,void(this.l=+e)):arguments.length<2?n instanceof it?new it(n.h,n.c,n.l):n instanceof at?st(n.l,n.a,n.b):st((n=xt((n=Zo.rgb(n)).r,n.g,n.b)).l,n.a,n.b):new it(n,t,e)}function ot(n,t,e){return isNaN(n)&&(n=0),isNaN(t)&&(t=0),new at(e,Math.cos(n*=Aa)*t,Math.sin(n)*t)}function at(n,t,e){return this instanceof at?(this.l=+n,this.a=+t,void(this.b=+e)):arguments.length<2?n instanceof at?new at(n.l,n.a,n.b):n instanceof it?ot(n.l,n.c,n.h):xt((n=gt(n)).r,n.g,n.b):new at(n,t,e)}function ct(n,t,e){var r=(n+16)/116,u=r+t/500,i=r-e/200;return u=lt(u)*ja,r=lt(r)*Ha,i=lt(i)*Fa,new gt(ht(3.2404542*u-1.5371385*r-.4985314*i),ht(-.969266*u+1.8760108*r+.041556*i),ht(.0556434*u-.2040259*r+1.0572252*i))}function st(n,t,e){return n>0?new it(Math.atan2(e,t)*Ca,Math.sqrt(t*t+e*e),n):new it(0/0,0/0,n)}function lt(n){return n>.206893034?n*n*n:(n-4/29)/7.787037}function ft(n){return n>.008856?Math.pow(n,1/3):7.787037*n+4/29}function ht(n){return Math.round(255*(.00304>=n?12.92*n:1.055*Math.pow(n,1/2.4)-.055))}function gt(n,t,e){return this instanceof gt?(this.r=~~n,this.g=~~t,void(this.b=~~e)):arguments.length<2?n instanceof gt?new gt(n.r,n.g,n.b):mt(""+n,gt,ut):new gt(n,t,e)}function pt(n){return new gt(n>>16,255&n>>8,255&n)}function vt(n){return pt(n)+""}function dt(n){return 16>n?"0"+Math.max(0,n).toString(16):Math.min(255,n).toString(16)}function mt(n,t,e){var r,u,i,o=0,a=0,c=0;if(r=/([a-z]+)\((.*)\)/i.exec(n))switch(u=r[2].split(","),r[1]){case"hsl":return e(parseFloat(u[0]),parseFloat(u[1])/100,parseFloat(u[2])/100);case"rgb":return t(_t(u[0]),_t(u[1]),_t(u[2]))}return(i=Ia.get(n))?t(i.r,i.g,i.b):(null==n||"#"!==n.charAt(0)||isNaN(i=parseInt(n.substring(1),16))||(4===n.length?(o=(3840&i)>>4,o=o>>4|o,a=240&i,a=a>>4|a,c=15&i,c=c<<4|c):7===n.length&&(o=(16711680&i)>>16,a=(65280&i)>>8,c=255&i)),t(o,a,c))}function yt(n,t,e){var r,u,i=Math.min(n/=255,t/=255,e/=255),o=Math.max(n,t,e),a=o-i,c=(o+i)/2;return a?(u=.5>c?a/(o+i):a/(2-o-i),r=n==o?(t-e)/a+(e>t?6:0):t==o?(e-n)/a+2:(n-t)/a+4,r*=60):(r=0/0,u=c>0&&1>c?0:r),new rt(r,u,c)}function xt(n,t,e){n=Mt(n),t=Mt(t),e=Mt(e);var r=ft((.4124564*n+.3575761*t+.1804375*e)/ja),u=ft((.2126729*n+.7151522*t+.072175*e)/Ha),i=ft((.0193339*n+.119192*t+.9503041*e)/Fa);return at(116*u-16,500*(r-u),200*(u-i))}function Mt(n){return(n/=255)<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function _t(n){var t=parseFloat(n);return"%"===n.charAt(n.length-1)?Math.round(2.55*t):t}function bt(n){return"function"==typeof n?n:function(){return n}}function wt(n){return n}function St(n){return function(t,e,r){return 2===arguments.length&&"function"==typeof e&&(r=e,e=null),kt(t,e,n,r)}}function kt(n,t,e,r){function u(){var n,t=c.status;if(!t&&c.responseText||t>=200&&300>t||304===t){try{n=e.call(i,c)}catch(r){return o.error.call(i,r),void 0}o.load.call(i,n)}else o.error.call(i,c)}var i={},o=Zo.dispatch("beforesend","progress","load","error"),a={},c=new XMLHttpRequest,s=null;return!Wo.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(n)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=u:c.onreadystatechange=function(){c.readyState>3&&u()},c.onprogress=function(n){var t=Zo.event;Zo.event=n;try{o.progress.call(i,c)}finally{Zo.event=t}},i.header=function(n,t){return n=(n+"").toLowerCase(),arguments.length<2?a[n]:(null==t?delete a[n]:a[n]=t+"",i)},i.mimeType=function(n){return arguments.length?(t=null==n?null:n+"",i):t},i.responseType=function(n){return arguments.length?(s=n,i):s},i.response=function(n){return e=n,i},["get","post"].forEach(function(n){i[n]=function(){return i.send.apply(i,[n].concat(Xo(arguments)))}}),i.send=function(e,r,u){if(2===arguments.length&&"function"==typeof r&&(u=r,r=null),c.open(e,n,!0),null==t||"accept"in a||(a.accept=t+",*/*"),c.setRequestHeader)for(var l in a)c.setRequestHeader(l,a[l]);return null!=t&&c.overrideMimeType&&c.overrideMimeType(t),null!=s&&(c.responseType=s),null!=u&&i.on("error",u).on("load",function(n){u(null,n)}),o.beforesend.call(i,c),c.send(null==r?null:r),i},i.abort=function(){return c.abort(),i},Zo.rebind(i,o,"on"),null==r?i:i.get(Et(r))}function Et(n){return 1===n.length?function(t,e){n(null==t?e:null)}:n}function At(){var n=Ct(),t=Nt()-n;t>24?(isFinite(t)&&(clearTimeout($a),$a=setTimeout(At,t)),Xa=0):(Xa=1,Wa(At))}function Ct(){var n=Date.now();for(Ba=Za;Ba;)n>=Ba.t&&(Ba.f=Ba.c(n-Ba.t)),Ba=Ba.n;return n}function Nt(){for(var n,t=Za,e=1/0;t;)t.f?t=n?n.n=t.n:Za=t.n:(t.t8?function(n){return n/e}:function(n){return n*e},symbol:n}}function Tt(n){var t=n.decimal,e=n.thousands,r=n.grouping,u=n.currency,i=r?function(n){for(var t=n.length,u=[],i=0,o=r[0];t>0&&o>0;)u.push(n.substring(t-=o,t+o)),o=r[i=(i+1)%r.length];return u.reverse().join(e)}:wt;return function(n){var e=Ga.exec(n),r=e[1]||" ",o=e[2]||">",a=e[3]||"",c=e[4]||"",s=e[5],l=+e[6],f=e[7],h=e[8],g=e[9],p=1,v="",d="",m=!1;switch(h&&(h=+h.substring(1)),(s||"0"===r&&"="===o)&&(s=r="0",o="=",f&&(l-=Math.floor((l-1)/4))),g){case"n":f=!0,g="g";break;case"%":p=100,d="%",g="f";break;case"p":p=100,d="%",g="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+g.toLowerCase());case"c":case"d":m=!0,h=0;break;case"s":p=-1,g="r"}"$"===c&&(v=u[0],d=u[1]),"r"!=g||h||(g="g"),null!=h&&("g"==g?h=Math.max(1,Math.min(21,h)):("e"==g||"f"==g)&&(h=Math.max(0,Math.min(20,h)))),g=Ka.get(g)||qt;var y=s&&f;return function(n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):a;if(0>p){var c=Zo.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x=n.lastIndexOf("."),M=0>x?n:n.substring(0,x),_=0>x?"":t+n.substring(x+1);!s&&f&&(M=i(M));var b=v.length+M.length+_.length+(y?0:u.length),w=l>b?new Array(b=l-b+1).join(r):"";return y&&(M=i(w+M)),u+=v,n=M+_,("<"===o?u+n+w:">"===o?w+u+n:"^"===o?w.substring(0,b>>=1)+u+n+w.substring(b):u+(y?n:w+n))+e}}}function qt(n){return n+""}function Rt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Dt(n,t,e){function r(t){var e=n(t),r=i(e,1);return r-t>t-e?e:r}function u(e){return t(e=n(new nc(e-1)),1),e}function i(n,e){return t(n=new nc(+n),e),n}function o(n,r,i){var o=u(n),a=[];if(i>1)for(;r>o;)e(o)%i||a.push(new Date(+o)),t(o,1);else for(;r>o;)a.push(new Date(+o)),t(o,1);return a}function a(n,t,e){try{nc=Rt;var r=new Rt;return r._=n,o(r,t,e)}finally{nc=Date}}n.floor=n,n.round=r,n.ceil=u,n.offset=i,n.range=o;var c=n.utc=Pt(n);return c.floor=c,c.round=Pt(r),c.ceil=Pt(u),c.offset=Pt(i),c.range=a,n}function Pt(n){return function(t,e){try{nc=Rt;var r=new Rt;return r._=t,n(r,e)._}finally{nc=Date}}}function Ut(n){function t(n){function t(t){for(var e,u,i,o=[],a=-1,c=0;++aa;){if(r>=s)return-1;if(u=t.charCodeAt(a++),37===u){if(o=t.charAt(a++),i=N[o in ec?t.charAt(a++):o],!i||(r=i(n,e,r))<0)return-1}else if(u!=e.charCodeAt(r++))return-1}return r}function r(n,t,e){b.lastIndex=0;var r=b.exec(t.substring(e));return r?(n.w=w.get(r[0].toLowerCase()),e+r[0].length):-1}function u(n,t,e){M.lastIndex=0;var r=M.exec(t.substring(e));return r?(n.w=_.get(r[0].toLowerCase()),e+r[0].length):-1}function i(n,t,e){E.lastIndex=0;var r=E.exec(t.substring(e));return r?(n.m=A.get(r[0].toLowerCase()),e+r[0].length):-1}function o(n,t,e){S.lastIndex=0;var r=S.exec(t.substring(e));return r?(n.m=k.get(r[0].toLowerCase()),e+r[0].length):-1}function a(n,t,r){return e(n,C.c.toString(),t,r)}function c(n,t,r){return e(n,C.x.toString(),t,r)}function s(n,t,r){return e(n,C.X.toString(),t,r)}function l(n,t,e){var r=x.get(t.substring(e,e+=2).toLowerCase());return null==r?-1:(n.p=r,e)}var f=n.dateTime,h=n.date,g=n.time,p=n.periods,v=n.days,d=n.shortDays,m=n.months,y=n.shortMonths;t.utc=function(n){function e(n){try{nc=Rt;var t=new nc;return t._=n,r(t)}finally{nc=Date}}var r=t(n);return e.parse=function(n){try{nc=Rt;var t=r.parse(n);return t&&t._}finally{nc=Date}},e.toString=r.toString,e},t.multi=t.utc.multi=re;var x=Zo.map(),M=Ht(v),_=Ft(v),b=Ht(d),w=Ft(d),S=Ht(m),k=Ft(m),E=Ht(y),A=Ft(y);p.forEach(function(n,t){x.set(n.toLowerCase(),t)});var C={a:function(n){return d[n.getDay()]},A:function(n){return v[n.getDay()]},b:function(n){return y[n.getMonth()]},B:function(n){return m[n.getMonth()]},c:t(f),d:function(n,t){return jt(n.getDate(),t,2)},e:function(n,t){return jt(n.getDate(),t,2)},H:function(n,t){return jt(n.getHours(),t,2)},I:function(n,t){return jt(n.getHours()%12||12,t,2)},j:function(n,t){return jt(1+Qa.dayOfYear(n),t,3)},L:function(n,t){return jt(n.getMilliseconds(),t,3)},m:function(n,t){return jt(n.getMonth()+1,t,2)},M:function(n,t){return jt(n.getMinutes(),t,2)},p:function(n){return p[+(n.getHours()>=12)]},S:function(n,t){return jt(n.getSeconds(),t,2)},U:function(n,t){return jt(Qa.sundayOfYear(n),t,2)},w:function(n){return n.getDay()},W:function(n,t){return jt(Qa.mondayOfYear(n),t,2)},x:t(h),X:t(g),y:function(n,t){return jt(n.getFullYear()%100,t,2)},Y:function(n,t){return jt(n.getFullYear()%1e4,t,4)},Z:te,"%":function(){return"%"}},N={a:r,A:u,b:i,B:o,c:a,d:Wt,e:Wt,H:Gt,I:Gt,j:Jt,L:ne,m:Bt,M:Kt,p:l,S:Qt,U:Yt,w:Ot,W:It,x:c,X:s,y:Vt,Y:Zt,Z:Xt,"%":ee};return t}function jt(n,t,e){var r=0>n?"-":"",u=(r?-n:n)+"",i=u.length;return r+(e>i?new Array(e-i+1).join(t)+u:u)}function Ht(n){return new RegExp("^(?:"+n.map(Zo.requote).join("|")+")","i")}function Ft(n){for(var t=new o,e=-1,r=n.length;++e68?1900:2e3)}function Bt(n,t,e){rc.lastIndex=0;var r=rc.exec(t.substring(e,e+2));return r?(n.m=r[0]-1,e+r[0].length):-1}function Wt(n,t,e){rc.lastIndex=0;var r=rc.exec(t.substring(e,e+2));return r?(n.d=+r[0],e+r[0].length):-1}function Jt(n,t,e){rc.lastIndex=0;var r=rc.exec(t.substring(e,e+3));return r?(n.j=+r[0],e+r[0].length):-1}function Gt(n,t,e){rc.lastIndex=0;var r=rc.exec(t.substring(e,e+2));return r?(n.H=+r[0],e+r[0].length):-1}function Kt(n,t,e){rc.lastIndex=0;var r=rc.exec(t.substring(e,e+2));return r?(n.M=+r[0],e+r[0].length):-1}function Qt(n,t,e){rc.lastIndex=0;var r=rc.exec(t.substring(e,e+2));return r?(n.S=+r[0],e+r[0].length):-1}function ne(n,t,e){rc.lastIndex=0;var r=rc.exec(t.substring(e,e+3));return r?(n.L=+r[0],e+r[0].length):-1}function te(n){var t=n.getTimezoneOffset(),e=t>0?"-":"+",r=~~(ua(t)/60),u=ua(t)%60;return e+jt(r,"0",2)+jt(u,"0",2)}function ee(n,t,e){uc.lastIndex=0;var r=uc.exec(t.substring(e,e+1));return r?e+r[0].length:-1}function re(n){for(var t=n.length,e=-1;++e=0?1:-1,a=o*e,c=Math.cos(t),s=Math.sin(t),l=i*s,f=u*c+l*Math.cos(a),h=l*o*Math.sin(a);lc.add(Math.atan2(h,f)),r=n,u=c,i=s}var t,e,r,u,i;fc.point=function(o,a){fc.point=n,r=(t=o)*Aa,u=Math.cos(a=(e=a)*Aa/2+ba/4),i=Math.sin(a)},fc.lineEnd=function(){n(t,e)}}function le(n){var t=n[0],e=n[1],r=Math.cos(e);return[r*Math.cos(t),r*Math.sin(t),Math.sin(e)]}function fe(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]}function he(n,t){return[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]]}function ge(n,t){n[0]+=t[0],n[1]+=t[1],n[2]+=t[2]}function pe(n,t){return[n[0]*t,n[1]*t,n[2]*t]}function ve(n){var t=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);n[0]/=t,n[1]/=t,n[2]/=t}function de(n){return[Math.atan2(n[1],n[0]),G(n[2])]}function me(n,t){return ua(n[0]-t[0])a;++a)u.point((e=n[a])[0],e[1]);return u.lineEnd(),void 0}var c=new Ee(e,n,null,!0),s=new Ee(e,null,c,!1);c.o=s,i.push(c),o.push(s),c=new Ee(r,n,null,!1),s=new Ee(r,null,c,!0),c.o=s,i.push(c),o.push(s)}}),o.sort(t),ke(i),ke(o),i.length){for(var a=0,c=e,s=o.length;s>a;++a)o[a].e=c=!c;for(var l,f,h=i[0];;){for(var g=h,p=!0;g.v;)if((g=g.n)===h)return;l=g.z,u.lineStart();do{if(g.v=g.o.v=!0,g.e){if(p)for(var a=0,s=l.length;s>a;++a)u.point((f=l[a])[0],f[1]);else r(g.x,g.n.x,1,u);g=g.n}else{if(p){l=g.p.z;for(var a=l.length-1;a>=0;--a)u.point((f=l[a])[0],f[1])}else r(g.x,g.p.x,-1,u);g=g.p}g=g.o,l=g.z,p=!p}while(!g.v);u.lineEnd()}}}function ke(n){if(t=n.length){for(var t,e,r=0,u=n[0];++r0){for(_||(i.polygonStart(),_=!0),i.lineStart();++o1&&2&t&&e.push(e.pop().concat(e.shift())),g.push(e.filter(Ce))}var g,p,v,d=t(i),m=u.invert(r[0],r[1]),y={point:o,lineStart:c,lineEnd:s,polygonStart:function(){y.point=l,y.lineStart=f,y.lineEnd=h,g=[],p=[]},polygonEnd:function(){y.point=o,y.lineStart=c,y.lineEnd=s,g=Zo.merge(g);var n=Le(m,p);g.length?(_||(i.polygonStart(),_=!0),Se(g,ze,n,e,i)):n&&(_||(i.polygonStart(),_=!0),i.lineStart(),e(null,null,1,i),i.lineEnd()),_&&(i.polygonEnd(),_=!1),g=p=null},sphere:function(){i.polygonStart(),i.lineStart(),e(null,null,1,i),i.lineEnd(),i.polygonEnd()}},x=Ne(),M=t(x),_=!1;return y}}function Ce(n){return n.length>1}function Ne(){var n,t=[];return{lineStart:function(){t.push(n=[])},point:function(t,e){n.push([t,e])},lineEnd:v,buffer:function(){var e=t;return t=[],n=null,e},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function ze(n,t){return((n=n.x)[0]<0?n[1]-Sa-ka:Sa-n[1])-((t=t.x)[0]<0?t[1]-Sa-ka:Sa-t[1])}function Le(n,t){var e=n[0],r=n[1],u=[Math.sin(e),-Math.cos(e),0],i=0,o=0;lc.reset();for(var a=0,c=t.length;c>a;++a){var s=t[a],l=s.length;if(l)for(var f=s[0],h=f[0],g=f[1]/2+ba/4,p=Math.sin(g),v=Math.cos(g),d=1;;){d===l&&(d=0),n=s[d];var m=n[0],y=n[1]/2+ba/4,x=Math.sin(y),M=Math.cos(y),_=m-h,b=_>=0?1:-1,w=b*_,S=w>ba,k=p*x;if(lc.add(Math.atan2(k*b*Math.sin(w),v*M+k*Math.cos(w))),i+=S?_+b*wa:_,S^h>=e^m>=e){var E=he(le(f),le(n));ve(E);var A=he(u,E);ve(A);var C=(S^_>=0?-1:1)*G(A[2]);(r>C||r===C&&(E[0]||E[1]))&&(o+=S^_>=0?1:-1)}if(!d++)break;h=m,p=x,v=M,f=n}}return(-ka>i||ka>i&&0>lc)^1&o}function Te(n){var t,e=0/0,r=0/0,u=0/0;return{lineStart:function(){n.lineStart(),t=1},point:function(i,o){var a=i>0?ba:-ba,c=ua(i-e);ua(c-ba)0?Sa:-Sa),n.point(u,r),n.lineEnd(),n.lineStart(),n.point(a,r),n.point(i,r),t=0):u!==a&&c>=ba&&(ua(e-u)ka?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(e)-Math.sin(r)*(u=Math.cos(t))*Math.sin(n))/(u*i*o)):(t+r)/2}function Re(n,t,e,r){var u;if(null==n)u=e*Sa,r.point(-ba,u),r.point(0,u),r.point(ba,u),r.point(ba,0),r.point(ba,-u),r.point(0,-u),r.point(-ba,-u),r.point(-ba,0),r.point(-ba,u);else if(ua(n[0]-t[0])>ka){var i=n[0]i}function e(n){var e,i,c,s,l;return{lineStart:function(){s=c=!1,l=1},point:function(f,h){var g,p=[f,h],v=t(f,h),d=o?v?0:u(f,h):v?u(f+(0>f?ba:-ba),h):0;if(!e&&(s=c=v)&&n.lineStart(),v!==c&&(g=r(e,p),(me(e,g)||me(p,g))&&(p[0]+=ka,p[1]+=ka,v=t(p[0],p[1]))),v!==c)l=0,v?(n.lineStart(),g=r(p,e),n.point(g[0],g[1])):(g=r(e,p),n.point(g[0],g[1]),n.lineEnd()),e=g;else if(a&&e&&o^v){var m;d&i||!(m=r(p,e,!0))||(l=0,o?(n.lineStart(),n.point(m[0][0],m[0][1]),n.point(m[1][0],m[1][1]),n.lineEnd()):(n.point(m[1][0],m[1][1]),n.lineEnd(),n.lineStart(),n.point(m[0][0],m[0][1])))}!v||e&&me(e,p)||n.point(p[0],p[1]),e=p,c=v,i=d},lineEnd:function(){c&&n.lineEnd(),e=null},clean:function(){return l|(s&&c)<<1}}}function r(n,t,e){var r=le(n),u=le(t),o=[1,0,0],a=he(r,u),c=fe(a,a),s=a[0],l=c-s*s;if(!l)return!e&&n;var f=i*c/l,h=-i*s/l,g=he(o,a),p=pe(o,f),v=pe(a,h);ge(p,v);var d=g,m=fe(p,d),y=fe(d,d),x=m*m-y*(fe(p,p)-1);if(!(0>x)){var M=Math.sqrt(x),_=pe(d,(-m-M)/y);if(ge(_,p),_=de(_),!e)return _;var b,w=n[0],S=t[0],k=n[1],E=t[1];w>S&&(b=w,w=S,S=b);var A=S-w,C=ua(A-ba)A;if(!C&&k>E&&(b=k,k=E,E=b),N?C?k+E>0^_[1]<(ua(_[0]-w)ba^(w<=_[0]&&_[0]<=S)){var z=pe(d,(-m+M)/y);return ge(z,p),[_,de(z)]}}}function u(t,e){var r=o?n:ba-n,u=0;return-r>t?u|=1:t>r&&(u|=2),-r>e?u|=4:e>r&&(u|=8),u}var i=Math.cos(n),o=i>0,a=ua(i)>ka,c=sr(n,6*Aa);return Ae(t,e,c,o?[0,-n]:[-ba,n-ba])}function Pe(n,t,e,r){return function(u){var i,o=u.a,a=u.b,c=o.x,s=o.y,l=a.x,f=a.y,h=0,g=1,p=l-c,v=f-s;if(i=n-c,p||!(i>0)){if(i/=p,0>p){if(h>i)return;g>i&&(g=i)}else if(p>0){if(i>g)return;i>h&&(h=i)}if(i=e-c,p||!(0>i)){if(i/=p,0>p){if(i>g)return;i>h&&(h=i)}else if(p>0){if(h>i)return;g>i&&(g=i)}if(i=t-s,v||!(i>0)){if(i/=v,0>v){if(h>i)return;g>i&&(g=i)}else if(v>0){if(i>g)return;i>h&&(h=i)}if(i=r-s,v||!(0>i)){if(i/=v,0>v){if(i>g)return;i>h&&(h=i)}else if(v>0){if(h>i)return;g>i&&(g=i)}return h>0&&(u.a={x:c+h*p,y:s+h*v}),1>g&&(u.b={x:c+g*p,y:s+g*v}),u}}}}}}function Ue(n,t,e,r){function u(r,u){return ua(r[0]-n)0?0:3:ua(r[0]-e)0?2:1:ua(r[1]-t)0?1:0:u>0?3:2}function i(n,t){return o(n.x,t.x)}function o(n,t){var e=u(n,1),r=u(t,1);return e!==r?e-r:0===e?t[1]-n[1]:1===e?n[0]-t[0]:2===e?n[1]-t[1]:t[0]-n[0]}return function(a){function c(n){for(var t=0,e=d.length,r=n[1],u=0;e>u;++u)for(var i,o=1,a=d[u],c=a.length,s=a[0];c>o;++o)i=a[o],s[1]<=r?i[1]>r&&W(s,i,n)>0&&++t:i[1]<=r&&W(s,i,n)<0&&--t,s=i;return 0!==t}function s(i,a,c,s){var l=0,f=0;if(null==i||(l=u(i,c))!==(f=u(a,c))||o(i,a)<0^c>0){do s.point(0===l||3===l?n:e,l>1?r:t);while((l=(l+c+4)%4)!==f)}else s.point(a[0],a[1])}function l(u,i){return u>=n&&e>=u&&i>=t&&r>=i}function f(n,t){l(n,t)&&a.point(n,t)}function h(){N.point=p,d&&d.push(m=[]),S=!0,w=!1,_=b=0/0}function g(){v&&(p(y,x),M&&w&&A.rejoin(),v.push(A.buffer())),N.point=f,w&&a.lineEnd()}function p(n,t){n=Math.max(-kc,Math.min(kc,n)),t=Math.max(-kc,Math.min(kc,t));var e=l(n,t);if(d&&m.push([n,t]),S)y=n,x=t,M=e,S=!1,e&&(a.lineStart(),a.point(n,t));else if(e&&w)a.point(n,t);else{var r={a:{x:_,y:b},b:{x:n,y:t}};C(r)?(w||(a.lineStart(),a.point(r.a.x,r.a.y)),a.point(r.b.x,r.b.y),e||a.lineEnd(),k=!1):e&&(a.lineStart(),a.point(n,t),k=!1)}_=n,b=t,w=e}var v,d,m,y,x,M,_,b,w,S,k,E=a,A=Ne(),C=Pe(n,t,e,r),N={point:f,lineStart:h,lineEnd:g,polygonStart:function(){a=A,v=[],d=[],k=!0},polygonEnd:function(){a=E,v=Zo.merge(v);var t=c([n,r]),e=k&&t,u=v.length;(e||u)&&(a.polygonStart(),e&&(a.lineStart(),s(null,null,1,a),a.lineEnd()),u&&Se(v,i,t,s,a),a.polygonEnd()),v=d=m=null}};return N}}function je(n,t){function e(e,r){return e=n(e,r),t(e[0],e[1])}return n.invert&&t.invert&&(e.invert=function(e,r){return e=t.invert(e,r),e&&n.invert(e[0],e[1])}),e}function He(n){var t=0,e=ba/3,r=tr(n),u=r(t,e);return u.parallels=function(n){return arguments.length?r(t=n[0]*ba/180,e=n[1]*ba/180):[180*(t/ba),180*(e/ba)]},u}function Fe(n,t){function e(n,t){var e=Math.sqrt(i-2*u*Math.sin(t))/u;return[e*Math.sin(n*=u),o-e*Math.cos(n)]}var r=Math.sin(n),u=(r+Math.sin(t))/2,i=1+r*(2*u-r),o=Math.sqrt(i)/u;return e.invert=function(n,t){var e=o-t;return[Math.atan2(n,e)/u,G((i-(n*n+e*e)*u*u)/(2*u))]},e}function Oe(){function n(n,t){Ac+=u*n-r*t,r=n,u=t}var t,e,r,u;Tc.point=function(i,o){Tc.point=n,t=r=i,e=u=o},Tc.lineEnd=function(){n(t,e)}}function Ye(n,t){Cc>n&&(Cc=n),n>zc&&(zc=n),Nc>t&&(Nc=t),t>Lc&&(Lc=t)}function Ie(){function n(n,t){o.push("M",n,",",t,i)}function t(n,t){o.push("M",n,",",t),a.point=e}function e(n,t){o.push("L",n,",",t)}function r(){a.point=n}function u(){o.push("Z")}var i=Ze(4.5),o=[],a={point:n,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=u},polygonEnd:function(){a.lineEnd=r,a.point=n},pointRadius:function(n){return i=Ze(n),a},result:function(){if(o.length){var n=o.join("");return o=[],n}}};return a}function Ze(n){return"m0,"+n+"a"+n+","+n+" 0 1,1 0,"+-2*n+"a"+n+","+n+" 0 1,1 0,"+2*n+"z"}function Ve(n,t){pc+=n,vc+=t,++dc}function Xe(){function n(n,r){var u=n-t,i=r-e,o=Math.sqrt(u*u+i*i);mc+=o*(t+n)/2,yc+=o*(e+r)/2,xc+=o,Ve(t=n,e=r)}var t,e;Rc.point=function(r,u){Rc.point=n,Ve(t=r,e=u)}}function $e(){Rc.point=Ve}function Be(){function n(n,t){var e=n-r,i=t-u,o=Math.sqrt(e*e+i*i);mc+=o*(r+n)/2,yc+=o*(u+t)/2,xc+=o,o=u*n-r*t,Mc+=o*(r+n),_c+=o*(u+t),bc+=3*o,Ve(r=n,u=t)}var t,e,r,u;Rc.point=function(i,o){Rc.point=n,Ve(t=r=i,e=u=o)},Rc.lineEnd=function(){n(t,e)}}function We(n){function t(t,e){n.moveTo(t,e),n.arc(t,e,o,0,wa)}function e(t,e){n.moveTo(t,e),a.point=r}function r(t,e){n.lineTo(t,e)}function u(){a.point=t}function i(){n.closePath()}var o=4.5,a={point:t,lineStart:function(){a.point=e},lineEnd:u,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=u,a.point=t},pointRadius:function(n){return o=n,a},result:v};return a}function Je(n){function t(n){return(a?r:e)(n)}function e(t){return Qe(t,function(e,r){e=n(e,r),t.point(e[0],e[1])})}function r(t){function e(e,r){e=n(e,r),t.point(e[0],e[1])}function r(){x=0/0,S.point=i,t.lineStart()}function i(e,r){var i=le([e,r]),o=n(e,r);u(x,M,y,_,b,w,x=o[0],M=o[1],y=e,_=i[0],b=i[1],w=i[2],a,t),t.point(x,M)}function o(){S.point=e,t.lineEnd()}function c(){r(),S.point=s,S.lineEnd=l}function s(n,t){i(f=n,h=t),g=x,p=M,v=_,d=b,m=w,S.point=i}function l(){u(x,M,y,_,b,w,g,p,f,v,d,m,a,t),S.lineEnd=o,o()}var f,h,g,p,v,d,m,y,x,M,_,b,w,S={point:e,lineStart:r,lineEnd:o,polygonStart:function(){t.polygonStart(),S.lineStart=c},polygonEnd:function(){t.polygonEnd(),S.lineStart=r}};return S}function u(t,e,r,a,c,s,l,f,h,g,p,v,d,m){var y=l-t,x=f-e,M=y*y+x*x;if(M>4*i&&d--){var _=a+g,b=c+p,w=s+v,S=Math.sqrt(_*_+b*b+w*w),k=Math.asin(w/=S),E=ua(ua(w)-1)i||ua((y*z+x*L)/M-.5)>.3||o>a*g+c*p+s*v)&&(u(t,e,r,a,c,s,C,N,E,_/=S,b/=S,w,d,m),m.point(C,N),u(C,N,E,_,b,w,l,f,h,g,p,v,d,m))}}var i=.5,o=Math.cos(30*Aa),a=16; - return t.precision=function(n){return arguments.length?(a=(i=n*n)>0&&16,t):Math.sqrt(i)},t}function Ge(n){var t=Je(function(t,e){return n([t*Ca,e*Ca])});return function(n){return er(t(n))}}function Ke(n){this.stream=n}function Qe(n,t){return{point:t,sphere:function(){n.sphere()},lineStart:function(){n.lineStart()},lineEnd:function(){n.lineEnd()},polygonStart:function(){n.polygonStart()},polygonEnd:function(){n.polygonEnd()}}}function nr(n){return tr(function(){return n})()}function tr(n){function t(n){return n=a(n[0]*Aa,n[1]*Aa),[n[0]*h+c,s-n[1]*h]}function e(n){return n=a.invert((n[0]-c)/h,(s-n[1])/h),n&&[n[0]*Ca,n[1]*Ca]}function r(){a=je(o=ir(m,y,x),i);var n=i(v,d);return c=g-n[0]*h,s=p+n[1]*h,u()}function u(){return l&&(l.valid=!1,l=null),t}var i,o,a,c,s,l,f=Je(function(n,t){return n=i(n,t),[n[0]*h+c,s-n[1]*h]}),h=150,g=480,p=250,v=0,d=0,m=0,y=0,x=0,M=Sc,_=wt,b=null,w=null;return t.stream=function(n){return l&&(l.valid=!1),l=er(M(o,f(_(n)))),l.valid=!0,l},t.clipAngle=function(n){return arguments.length?(M=null==n?(b=n,Sc):De((b=+n)*Aa),u()):b},t.clipExtent=function(n){return arguments.length?(w=n,_=n?Ue(n[0][0],n[0][1],n[1][0],n[1][1]):wt,u()):w},t.scale=function(n){return arguments.length?(h=+n,r()):h},t.translate=function(n){return arguments.length?(g=+n[0],p=+n[1],r()):[g,p]},t.center=function(n){return arguments.length?(v=n[0]%360*Aa,d=n[1]%360*Aa,r()):[v*Ca,d*Ca]},t.rotate=function(n){return arguments.length?(m=n[0]%360*Aa,y=n[1]%360*Aa,x=n.length>2?n[2]%360*Aa:0,r()):[m*Ca,y*Ca,x*Ca]},Zo.rebind(t,f,"precision"),function(){return i=n.apply(this,arguments),t.invert=i.invert&&e,r()}}function er(n){return Qe(n,function(t,e){n.point(t*Aa,e*Aa)})}function rr(n,t){return[n,t]}function ur(n,t){return[n>ba?n-wa:-ba>n?n+wa:n,t]}function ir(n,t,e){return n?t||e?je(ar(n),cr(t,e)):ar(n):t||e?cr(t,e):ur}function or(n){return function(t,e){return t+=n,[t>ba?t-wa:-ba>t?t+wa:t,e]}}function ar(n){var t=or(n);return t.invert=or(-n),t}function cr(n,t){function e(n,t){var e=Math.cos(t),a=Math.cos(n)*e,c=Math.sin(n)*e,s=Math.sin(t),l=s*r+a*u;return[Math.atan2(c*i-l*o,a*r-s*u),G(l*i+c*o)]}var r=Math.cos(n),u=Math.sin(n),i=Math.cos(t),o=Math.sin(t);return e.invert=function(n,t){var e=Math.cos(t),a=Math.cos(n)*e,c=Math.sin(n)*e,s=Math.sin(t),l=s*i-c*o;return[Math.atan2(c*i+s*o,a*r+l*u),G(l*r-a*u)]},e}function sr(n,t){var e=Math.cos(n),r=Math.sin(n);return function(u,i,o,a){var c=o*t;null!=u?(u=lr(e,u),i=lr(e,i),(o>0?i>u:u>i)&&(u+=o*wa)):(u=n+o*wa,i=n-.5*c);for(var s,l=u;o>0?l>i:i>l;l-=c)a.point((s=de([e,-r*Math.cos(l),-r*Math.sin(l)]))[0],s[1])}}function lr(n,t){var e=le(t);e[0]-=n,ve(e);var r=J(-e[1]);return((-e[2]<0?-r:r)+2*Math.PI-ka)%(2*Math.PI)}function fr(n,t,e){var r=Zo.range(n,t-ka,e).concat(t);return function(n){return r.map(function(t){return[n,t]})}}function hr(n,t,e){var r=Zo.range(n,t-ka,e).concat(t);return function(n){return r.map(function(t){return[t,n]})}}function gr(n){return n.source}function pr(n){return n.target}function vr(n,t,e,r){var u=Math.cos(t),i=Math.sin(t),o=Math.cos(r),a=Math.sin(r),c=u*Math.cos(n),s=u*Math.sin(n),l=o*Math.cos(e),f=o*Math.sin(e),h=2*Math.asin(Math.sqrt(tt(r-t)+u*o*tt(e-n))),g=1/Math.sin(h),p=h?function(n){var t=Math.sin(n*=h)*g,e=Math.sin(h-n)*g,r=e*c+t*l,u=e*s+t*f,o=e*i+t*a;return[Math.atan2(u,r)*Ca,Math.atan2(o,Math.sqrt(r*r+u*u))*Ca]}:function(){return[n*Ca,t*Ca]};return p.distance=h,p}function dr(){function n(n,u){var i=Math.sin(u*=Aa),o=Math.cos(u),a=ua((n*=Aa)-t),c=Math.cos(a);Dc+=Math.atan2(Math.sqrt((a=o*Math.sin(a))*a+(a=r*i-e*o*c)*a),e*i+r*o*c),t=n,e=i,r=o}var t,e,r;Pc.point=function(u,i){t=u*Aa,e=Math.sin(i*=Aa),r=Math.cos(i),Pc.point=n},Pc.lineEnd=function(){Pc.point=Pc.lineEnd=v}}function mr(n,t){function e(t,e){var r=Math.cos(t),u=Math.cos(e),i=n(r*u);return[i*u*Math.sin(t),i*Math.sin(e)]}return e.invert=function(n,e){var r=Math.sqrt(n*n+e*e),u=t(r),i=Math.sin(u),o=Math.cos(u);return[Math.atan2(n*i,r*o),Math.asin(r&&e*i/r)]},e}function yr(n,t){function e(n,t){o>0?-Sa+ka>t&&(t=-Sa+ka):t>Sa-ka&&(t=Sa-ka);var e=o/Math.pow(u(t),i);return[e*Math.sin(i*n),o-e*Math.cos(i*n)]}var r=Math.cos(n),u=function(n){return Math.tan(ba/4+n/2)},i=n===t?Math.sin(n):Math.log(r/Math.cos(t))/Math.log(u(t)/u(n)),o=r*Math.pow(u(n),i)/i;return i?(e.invert=function(n,t){var e=o-t,r=B(i)*Math.sqrt(n*n+e*e);return[Math.atan2(n,e)/i,2*Math.atan(Math.pow(o/r,1/i))-Sa]},e):Mr}function xr(n,t){function e(n,t){var e=i-t;return[e*Math.sin(u*n),i-e*Math.cos(u*n)]}var r=Math.cos(n),u=n===t?Math.sin(n):(r-Math.cos(t))/(t-n),i=r/u+n;return ua(u)u;u++){for(;r>1&&W(n[e[r-2]],n[e[r-1]],n[u])<=0;)--r;e[r++]=u}return e.slice(0,r)}function Er(n,t){return n[0]-t[0]||n[1]-t[1]}function Ar(n,t,e){return(e[0]-t[0])*(n[1]-t[1])<(e[1]-t[1])*(n[0]-t[0])}function Cr(n,t,e,r){var u=n[0],i=e[0],o=t[0]-u,a=r[0]-i,c=n[1],s=e[1],l=t[1]-c,f=r[1]-s,h=(a*(c-s)-f*(u-i))/(f*o-a*l);return[u+h*o,c+h*l]}function Nr(n){var t=n[0],e=n[n.length-1];return!(t[0]-e[0]||t[1]-e[1])}function zr(){Gr(this),this.edge=this.site=this.circle=null}function Lr(n){var t=Bc.pop()||new zr;return t.site=n,t}function Tr(n){Yr(n),Vc.remove(n),Bc.push(n),Gr(n)}function qr(n){var t=n.circle,e=t.x,r=t.cy,u={x:e,y:r},i=n.P,o=n.N,a=[n];Tr(n);for(var c=i;c.circle&&ua(e-c.circle.x)l;++l)s=a[l],c=a[l-1],Br(s.edge,c.site,s.site,u);c=a[0],s=a[f-1],s.edge=Xr(c.site,s.site,null,u),Or(c),Or(s)}function Rr(n){for(var t,e,r,u,i=n.x,o=n.y,a=Vc._;a;)if(r=Dr(a,o)-i,r>ka)a=a.L;else{if(u=i-Pr(a,o),!(u>ka)){r>-ka?(t=a.P,e=a):u>-ka?(t=a,e=a.N):t=e=a;break}if(!a.R){t=a;break}a=a.R}var c=Lr(n);if(Vc.insert(t,c),t||e){if(t===e)return Yr(t),e=Lr(t.site),Vc.insert(c,e),c.edge=e.edge=Xr(t.site,c.site),Or(t),Or(e),void 0;if(!e)return c.edge=Xr(t.site,c.site),void 0;Yr(t),Yr(e);var s=t.site,l=s.x,f=s.y,h=n.x-l,g=n.y-f,p=e.site,v=p.x-l,d=p.y-f,m=2*(h*d-g*v),y=h*h+g*g,x=v*v+d*d,M={x:(d*y-g*x)/m+l,y:(h*x-v*y)/m+f};Br(e.edge,s,p,M),c.edge=Xr(s,n,null,M),e.edge=Xr(n,p,null,M),Or(t),Or(e)}}function Dr(n,t){var e=n.site,r=e.x,u=e.y,i=u-t;if(!i)return r;var o=n.P;if(!o)return-1/0;e=o.site;var a=e.x,c=e.y,s=c-t;if(!s)return a;var l=a-r,f=1/i-1/s,h=l/s;return f?(-h+Math.sqrt(h*h-2*f*(l*l/(-2*s)-c+s/2+u-i/2)))/f+r:(r+a)/2}function Pr(n,t){var e=n.N;if(e)return Dr(e,t);var r=n.site;return r.y===t?r.x:1/0}function Ur(n){this.site=n,this.edges=[]}function jr(n){for(var t,e,r,u,i,o,a,c,s,l,f=n[0][0],h=n[1][0],g=n[0][1],p=n[1][1],v=Zc,d=v.length;d--;)if(i=v[d],i&&i.prepare())for(a=i.edges,c=a.length,o=0;c>o;)l=a[o].end(),r=l.x,u=l.y,s=a[++o%c].start(),t=s.x,e=s.y,(ua(r-t)>ka||ua(u-e)>ka)&&(a.splice(o,0,new Wr($r(i.site,l,ua(r-f)ka?{x:f,y:ua(t-f)ka?{x:ua(e-p)ka?{x:h,y:ua(t-h)ka?{x:ua(e-g)=-Ea)){var g=c*c+s*s,p=l*l+f*f,v=(f*g-s*p)/h,d=(c*p-l*g)/h,f=d+a,m=Wc.pop()||new Fr;m.arc=n,m.site=u,m.x=v+o,m.y=f+Math.sqrt(v*v+d*d),m.cy=f,n.circle=m;for(var y=null,x=$c._;x;)if(m.yd||d>=a)return;if(h>p){if(i){if(i.y>=s)return}else i={x:d,y:c};e={x:d,y:s}}else{if(i){if(i.yr||r>1)if(h>p){if(i){if(i.y>=s)return}else i={x:(c-u)/r,y:c};e={x:(s-u)/r,y:s}}else{if(i){if(i.yg){if(i){if(i.x>=a)return}else i={x:o,y:r*o+u};e={x:a,y:r*a+u}}else{if(i){if(i.xi&&(u=t.substring(i,u),a[o]?a[o]+=u:a[++o]=u),(e=e[0])===(r=r[0])?a[o]?a[o]+=r:a[++o]=r:(a[++o]=null,c.push({i:o,x:lu(e,r)})),i=Kc.lastIndex;return ir;++r)a[(e=c[r]).i]=e.x(n);return a.join("")})}function hu(n,t){for(var e,r=Zo.interpolators.length;--r>=0&&!(e=Zo.interpolators[r](n,t)););return e}function gu(n,t){var e,r=[],u=[],i=n.length,o=t.length,a=Math.min(n.length,t.length);for(e=0;a>e;++e)r.push(hu(n[e],t[e]));for(;i>e;++e)u[e]=n[e];for(;o>e;++e)u[e]=t[e];return function(n){for(e=0;a>e;++e)u[e]=r[e](n);return u}}function pu(n){return function(t){return 0>=t?0:t>=1?1:n(t)}}function vu(n){return function(t){return 1-n(1-t)}}function du(n){return function(t){return.5*(.5>t?n(2*t):2-n(2-2*t))}}function mu(n){return n*n}function yu(n){return n*n*n}function xu(n){if(0>=n)return 0;if(n>=1)return 1;var t=n*n,e=t*n;return 4*(.5>n?e:3*(n-t)+e-.75)}function Mu(n){return function(t){return Math.pow(t,n)}}function _u(n){return 1-Math.cos(n*Sa)}function bu(n){return Math.pow(2,10*(n-1))}function wu(n){return 1-Math.sqrt(1-n*n)}function Su(n,t){var e;return arguments.length<2&&(t=.45),arguments.length?e=t/wa*Math.asin(1/n):(n=1,e=t/4),function(r){return 1+n*Math.pow(2,-10*r)*Math.sin((r-e)*wa/t)}}function ku(n){return n||(n=1.70158),function(t){return t*t*((n+1)*t-n)}}function Eu(n){return 1/2.75>n?7.5625*n*n:2/2.75>n?7.5625*(n-=1.5/2.75)*n+.75:2.5/2.75>n?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375}function Au(n,t){n=Zo.hcl(n),t=Zo.hcl(t);var e=n.h,r=n.c,u=n.l,i=t.h-e,o=t.c-r,a=t.l-u;return isNaN(o)&&(o=0,r=isNaN(r)?t.c:r),isNaN(i)?(i=0,e=isNaN(e)?t.h:e):i>180?i-=360:-180>i&&(i+=360),function(n){return ot(e+i*n,r+o*n,u+a*n)+""}}function Cu(n,t){n=Zo.hsl(n),t=Zo.hsl(t);var e=n.h,r=n.s,u=n.l,i=t.h-e,o=t.s-r,a=t.l-u;return isNaN(o)&&(o=0,r=isNaN(r)?t.s:r),isNaN(i)?(i=0,e=isNaN(e)?t.h:e):i>180?i-=360:-180>i&&(i+=360),function(n){return ut(e+i*n,r+o*n,u+a*n)+""}}function Nu(n,t){n=Zo.lab(n),t=Zo.lab(t);var e=n.l,r=n.a,u=n.b,i=t.l-e,o=t.a-r,a=t.b-u;return function(n){return ct(e+i*n,r+o*n,u+a*n)+""}}function zu(n,t){return t-=n,function(e){return Math.round(n+t*e)}}function Lu(n){var t=[n.a,n.b],e=[n.c,n.d],r=qu(t),u=Tu(t,e),i=qu(Ru(e,t,-u))||0;t[0]*e[1]180?l+=360:l-s>180&&(s+=360),u.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:lu(s,l)})):l&&r.push(r.pop()+"rotate("+l+")"),f!=h?u.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:lu(f,h)}):h&&r.push(r.pop()+"skewX("+h+")"),g[0]!=p[0]||g[1]!=p[1]?(e=r.push(r.pop()+"scale(",null,",",null,")"),u.push({i:e-4,x:lu(g[0],p[0])},{i:e-2,x:lu(g[1],p[1])})):(1!=p[0]||1!=p[1])&&r.push(r.pop()+"scale("+p+")"),e=u.length,function(n){for(var t,i=-1;++i=0;)e.push(u[r])}function Bu(n,t){for(var e=[n],r=[];null!=(n=e.pop());)if(r.push(n),(i=n.children)&&(u=i.length))for(var u,i,o=-1;++oe;++e)(t=n[e][1])>u&&(r=e,u=t);return r}function ii(n){return n.reduce(oi,0)}function oi(n,t){return n+t[1]}function ai(n,t){return ci(n,Math.ceil(Math.log(t.length)/Math.LN2+1))}function ci(n,t){for(var e=-1,r=+n[0],u=(n[1]-r)/t,i=[];++e<=t;)i[e]=u*e+r;return i}function si(n){return[Zo.min(n),Zo.max(n)]}function li(n,t){return n.value-t.value}function fi(n,t){var e=n._pack_next;n._pack_next=t,t._pack_prev=n,t._pack_next=e,e._pack_prev=t}function hi(n,t){n._pack_next=t,t._pack_prev=n}function gi(n,t){var e=t.x-n.x,r=t.y-n.y,u=n.r+t.r;return.999*u*u>e*e+r*r}function pi(n){function t(n){l=Math.min(n.x-n.r,l),f=Math.max(n.x+n.r,f),h=Math.min(n.y-n.r,h),g=Math.max(n.y+n.r,g)}if((e=n.children)&&(s=e.length)){var e,r,u,i,o,a,c,s,l=1/0,f=-1/0,h=1/0,g=-1/0;if(e.forEach(vi),r=e[0],r.x=-r.r,r.y=0,t(r),s>1&&(u=e[1],u.x=u.r,u.y=0,t(u),s>2))for(i=e[2],yi(r,u,i),t(i),fi(r,i),r._pack_prev=i,fi(i,u),u=r._pack_next,o=3;s>o;o++){yi(r,u,i=e[o]);var p=0,v=1,d=1;for(a=u._pack_next;a!==u;a=a._pack_next,v++)if(gi(a,i)){p=1;break}if(1==p)for(c=r._pack_prev;c!==a._pack_prev&&!gi(c,i);c=c._pack_prev,d++);p?(d>v||v==d&&u.ro;o++)i=e[o],i.x-=m,i.y-=y,x=Math.max(x,i.r+Math.sqrt(i.x*i.x+i.y*i.y));n.r=x,e.forEach(di)}}function vi(n){n._pack_next=n._pack_prev=n}function di(n){delete n._pack_next,delete n._pack_prev}function mi(n,t,e,r){var u=n.children;if(n.x=t+=r*n.x,n.y=e+=r*n.y,n.r*=r,u)for(var i=-1,o=u.length;++i=0;)t=u[i],t.z+=e,t.m+=e,e+=t.s+(r+=t.c)}function Si(n,t,e){return n.a.parent===t.parent?n.a:e}function ki(n){return 1+Zo.max(n,function(n){return n.y})}function Ei(n){return n.reduce(function(n,t){return n+t.x},0)/n.length}function Ai(n){var t=n.children;return t&&t.length?Ai(t[0]):n}function Ci(n){var t,e=n.children;return e&&(t=e.length)?Ci(e[t-1]):n}function Ni(n){return{x:n.x,y:n.y,dx:n.dx,dy:n.dy}}function zi(n,t){var e=n.x+t[3],r=n.y+t[0],u=n.dx-t[1]-t[3],i=n.dy-t[0]-t[2];return 0>u&&(e+=u/2,u=0),0>i&&(r+=i/2,i=0),{x:e,y:r,dx:u,dy:i}}function Li(n){var t=n[0],e=n[n.length-1];return e>t?[t,e]:[e,t]}function Ti(n){return n.rangeExtent?n.rangeExtent():Li(n.range())}function qi(n,t,e,r){var u=e(n[0],n[1]),i=r(t[0],t[1]);return function(n){return i(u(n))}}function Ri(n,t){var e,r=0,u=n.length-1,i=n[r],o=n[u];return i>o&&(e=r,r=u,u=e,e=i,i=o,o=e),n[r]=t.floor(i),n[u]=t.ceil(o),n}function Di(n){return n?{floor:function(t){return Math.floor(t/n)*n},ceil:function(t){return Math.ceil(t/n)*n}}:ss}function Pi(n,t,e,r){var u=[],i=[],o=0,a=Math.min(n.length,t.length)-1;for(n[a]2?Pi:qi,c=r?Uu:Pu;return o=u(n,t,c,e),a=u(t,n,c,hu),i}function i(n){return o(n)}var o,a;return i.invert=function(n){return a(n)},i.domain=function(t){return arguments.length?(n=t.map(Number),u()):n},i.range=function(n){return arguments.length?(t=n,u()):t},i.rangeRound=function(n){return i.range(n).interpolate(zu)},i.clamp=function(n){return arguments.length?(r=n,u()):r},i.interpolate=function(n){return arguments.length?(e=n,u()):e},i.ticks=function(t){return Oi(n,t)},i.tickFormat=function(t,e){return Yi(n,t,e)},i.nice=function(t){return Hi(n,t),u()},i.copy=function(){return Ui(n,t,e,r)},u()}function ji(n,t){return Zo.rebind(n,t,"range","rangeRound","interpolate","clamp")}function Hi(n,t){return Ri(n,Di(Fi(n,t)[2]))}function Fi(n,t){null==t&&(t=10);var e=Li(n),r=e[1]-e[0],u=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),i=t/r*u;return.15>=i?u*=10:.35>=i?u*=5:.75>=i&&(u*=2),e[0]=Math.ceil(e[0]/u)*u,e[1]=Math.floor(e[1]/u)*u+.5*u,e[2]=u,e}function Oi(n,t){return Zo.range.apply(Zo,Fi(n,t))}function Yi(n,t,e){var r=Fi(n,t);if(e){var u=Ga.exec(e);if(u.shift(),"s"===u[8]){var i=Zo.formatPrefix(Math.max(ua(r[0]),ua(r[1])));return u[7]||(u[7]="."+Ii(i.scale(r[2]))),u[8]="f",e=Zo.format(u.join("")),function(n){return e(i.scale(n))+i.symbol}}u[7]||(u[7]="."+Zi(u[8],r)),e=u.join("")}else e=",."+Ii(r[2])+"f";return Zo.format(e)}function Ii(n){return-Math.floor(Math.log(n)/Math.LN10+.01)}function Zi(n,t){var e=Ii(t[2]);return n in ls?Math.abs(e-Ii(Math.max(ua(t[0]),ua(t[1]))))+ +("e"!==n):e-2*("%"===n)}function Vi(n,t,e,r){function u(n){return(e?Math.log(0>n?0:n):-Math.log(n>0?0:-n))/Math.log(t)}function i(n){return e?Math.pow(t,n):-Math.pow(t,-n)}function o(t){return n(u(t))}return o.invert=function(t){return i(n.invert(t))},o.domain=function(t){return arguments.length?(e=t[0]>=0,n.domain((r=t.map(Number)).map(u)),o):r},o.base=function(e){return arguments.length?(t=+e,n.domain(r.map(u)),o):t},o.nice=function(){var t=Ri(r.map(u),e?Math:hs);return n.domain(t),r=t.map(i),o},o.ticks=function(){var n=Li(r),o=[],a=n[0],c=n[1],s=Math.floor(u(a)),l=Math.ceil(u(c)),f=t%1?2:t;if(isFinite(l-s)){if(e){for(;l>s;s++)for(var h=1;f>h;h++)o.push(i(s)*h);o.push(i(s))}else for(o.push(i(s));s++0;h--)o.push(i(s)*h);for(s=0;o[s]c;l--);o=o.slice(s,l)}return o},o.tickFormat=function(n,t){if(!arguments.length)return fs;arguments.length<2?t=fs:"function"!=typeof t&&(t=Zo.format(t));var r,a=Math.max(.1,n/o.ticks().length),c=e?(r=1e-12,Math.ceil):(r=-1e-12,Math.floor);return function(n){return n/i(c(u(n)+r))<=a?t(n):""}},o.copy=function(){return Vi(n.copy(),t,e,r)},ji(o,n)}function Xi(n,t,e){function r(t){return n(u(t))}var u=$i(t),i=$i(1/t);return r.invert=function(t){return i(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain((e=t.map(Number)).map(u)),r):e},r.ticks=function(n){return Oi(e,n)},r.tickFormat=function(n,t){return Yi(e,n,t)},r.nice=function(n){return r.domain(Hi(e,n))},r.exponent=function(o){return arguments.length?(u=$i(t=o),i=$i(1/t),n.domain(e.map(u)),r):t},r.copy=function(){return Xi(n.copy(),t,e)},ji(r,n)}function $i(n){return function(t){return 0>t?-Math.pow(-t,n):Math.pow(t,n)}}function Bi(n,t){function e(e){return i[((u.get(e)||("range"===t.t?u.set(e,n.push(e)):0/0))-1)%i.length]}function r(t,e){return Zo.range(n.length).map(function(n){return t+e*n})}var u,i,a;return e.domain=function(r){if(!arguments.length)return n;n=[],u=new o;for(var i,a=-1,c=r.length;++an?[0/0,0/0]:[n>0?o[n-1]:e[0],nt?0/0:t/i+n,[t,t+1/i]},r.copy=function(){return Ji(n,t,e)},u()}function Gi(n,t){function e(e){return e>=e?t[Zo.bisect(n,e)]:void 0}return e.domain=function(t){return arguments.length?(n=t,e):n},e.range=function(n){return arguments.length?(t=n,e):t},e.invertExtent=function(e){return e=t.indexOf(e),[n[e-1],n[e]]},e.copy=function(){return Gi(n,t)},e}function Ki(n){function t(n){return+n}return t.invert=t,t.domain=t.range=function(e){return arguments.length?(n=e.map(t),t):n},t.ticks=function(t){return Oi(n,t)},t.tickFormat=function(t,e){return Yi(n,t,e)},t.copy=function(){return Ki(n)},t}function Qi(n){return n.innerRadius}function no(n){return n.outerRadius}function to(n){return n.startAngle}function eo(n){return n.endAngle}function ro(n){function t(t){function o(){s.push("M",i(n(l),a))}for(var c,s=[],l=[],f=-1,h=t.length,g=bt(e),p=bt(r);++f1&&u.push("H",r[0]),u.join("")}function ao(n){for(var t=0,e=n.length,r=n[0],u=[r[0],",",r[1]];++t1){a=t[1],i=n[c],c++,r+="C"+(u[0]+o[0])+","+(u[1]+o[1])+","+(i[0]-a[0])+","+(i[1]-a[1])+","+i[0]+","+i[1];for(var s=2;s9&&(u=3*t/Math.sqrt(u),o[a]=u*e,o[a+1]=u*r));for(a=-1;++a<=c;)u=(n[Math.min(c,a+1)][0]-n[Math.max(0,a-1)][0])/(6*(1+o[a]*o[a])),i.push([u||0,o[a]*u||0]);return i}function So(n){return n.length<3?uo(n):n[0]+ho(n,wo(n))}function ko(n){for(var t,e,r,u=-1,i=n.length;++ue?s():(u.active=e,i.event&&i.event.start.call(n,l,t),i.tween.forEach(function(e,r){(r=r.call(n,l,t))&&v.push(r)}),Zo.timer(function(){return p.c=c(r||1)?we:c,1},0,a),void 0)}function c(r){if(u.active!==e)return s();for(var o=r/g,a=f(o),c=v.length;c>0;)v[--c].call(n,a); - return o>=1?(i.event&&i.event.end.call(n,l,t),s()):void 0}function s(){return--u.count?delete u[e]:delete n.__transition__,1}var l=n.__data__,f=i.ease,h=i.delay,g=i.duration,p=Ba,v=[];return p.t=h+a,r>=h?o(r-h):(p.c=o,void 0)},0,a)}}function Uo(n,t){n.attr("transform",function(n){return"translate("+t(n)+",0)"})}function jo(n,t){n.attr("transform",function(n){return"translate(0,"+t(n)+")"})}function Ho(n){return n.toISOString()}function Fo(n,t,e){function r(t){return n(t)}function u(n,e){var r=n[1]-n[0],u=r/e,i=Zo.bisect(Us,u);return i==Us.length?[t.year,Fi(n.map(function(n){return n/31536e6}),e)[2]]:i?t[u/Us[i-1]1?{floor:function(t){for(;e(t=n.floor(t));)t=Oo(t-1);return t},ceil:function(t){for(;e(t=n.ceil(t));)t=Oo(+t+1);return t}}:n))},r.ticks=function(n,t){var e=Li(r.domain()),i=null==n?u(e,10):"number"==typeof n?u(e,n):!n.range&&[{range:n},t];return i&&(n=i[0],t=i[1]),n.range(e[0],Oo(+e[1]+1),1>t?1:t)},r.tickFormat=function(){return e},r.copy=function(){return Fo(n.copy(),t,e)},ji(r,n)}function Oo(n){return new Date(n)}function Yo(n){return JSON.parse(n.responseText)}function Io(n){var t=$o.createRange();return t.selectNode($o.body),t.createContextualFragment(n.responseText)}var Zo={version:"3.4.11"};Date.now||(Date.now=function(){return+new Date});var Vo=[].slice,Xo=function(n){return Vo.call(n)},$o=document,Bo=$o.documentElement,Wo=window;try{Xo(Bo.childNodes)[0].nodeType}catch(Jo){Xo=function(n){for(var t=n.length,e=new Array(t);t--;)e[t]=n[t];return e}}try{$o.createElement("div").style.setProperty("opacity",0,"")}catch(Go){var Ko=Wo.Element.prototype,Qo=Ko.setAttribute,na=Ko.setAttributeNS,ta=Wo.CSSStyleDeclaration.prototype,ea=ta.setProperty;Ko.setAttribute=function(n,t){Qo.call(this,n,t+"")},Ko.setAttributeNS=function(n,t,e){na.call(this,n,t,e+"")},ta.setProperty=function(n,t,e){ea.call(this,n,t+"",e)}}Zo.ascending=n,Zo.descending=function(n,t){return n>t?-1:t>n?1:t>=n?0:0/0},Zo.min=function(n,t){var e,r,u=-1,i=n.length;if(1===arguments.length){for(;++u=e);)e=void 0;for(;++ur&&(e=r)}else{for(;++u=e);)e=void 0;for(;++ur&&(e=r)}return e},Zo.max=function(n,t){var e,r,u=-1,i=n.length;if(1===arguments.length){for(;++u=e);)e=void 0;for(;++ue&&(e=r)}else{for(;++u=e);)e=void 0;for(;++ue&&(e=r)}return e},Zo.extent=function(n,t){var e,r,u,i=-1,o=n.length;if(1===arguments.length){for(;++i=e);)e=u=void 0;for(;++ir&&(e=r),r>u&&(u=r))}else{for(;++i=e);)e=void 0;for(;++ir&&(e=r),r>u&&(u=r))}return[e,u]},Zo.sum=function(n,t){var e,r=0,u=n.length,i=-1;if(1===arguments.length)for(;++i1&&(e=e.map(r)),e=e.filter(t),e.length?Zo.quantile(e.sort(n),.5):void 0};var ra=e(n);Zo.bisectLeft=ra.left,Zo.bisect=Zo.bisectRight=ra.right,Zo.bisector=function(t){return e(1===t.length?function(e,r){return n(t(e),r)}:t)},Zo.shuffle=function(n){for(var t,e,r=n.length;r;)e=0|Math.random()*r--,t=n[r],n[r]=n[e],n[e]=t;return n},Zo.permute=function(n,t){for(var e=t.length,r=new Array(e);e--;)r[e]=n[t[e]];return r},Zo.pairs=function(n){for(var t,e=0,r=n.length-1,u=n[0],i=new Array(0>r?0:r);r>e;)i[e]=[t=u,u=n[++e]];return i},Zo.zip=function(){if(!(u=arguments.length))return[];for(var n=-1,t=Zo.min(arguments,r),e=new Array(t);++n=0;)for(r=n[u],t=r.length;--t>=0;)e[--o]=r[t];return e};var ua=Math.abs;Zo.range=function(n,t,e){if(arguments.length<3&&(e=1,arguments.length<2&&(t=n,n=0)),1/0===(t-n)/e)throw new Error("infinite range");var r,i=[],o=u(ua(e)),a=-1;if(n*=o,t*=o,e*=o,0>e)for(;(r=n+e*++a)>t;)i.push(r/o);else for(;(r=n+e*++a)=i.length)return r?r.call(u,a):e?a.sort(e):a;for(var s,l,f,h,g=-1,p=a.length,v=i[c++],d=new o;++g=i.length)return n;var r=[],u=a[e++];return n.forEach(function(n,u){r.push({key:n,values:t(u,e)})}),u?r.sort(function(n,t){return u(n.key,t.key)}):r}var e,r,u={},i=[],a=[];return u.map=function(t,e){return n(e,t,0)},u.entries=function(e){return t(n(Zo.map,e,0),0)},u.key=function(n){return i.push(n),u},u.sortKeys=function(n){return a[i.length-1]=n,u},u.sortValues=function(n){return e=n,u},u.rollup=function(n){return r=n,u},u},Zo.set=function(n){var t=new h;if(n)for(var e=0,r=n.length;r>e;++e)t.add(n[e]);return t},i(h,{has:a,add:function(n){return this[ia+n]=!0,n},remove:function(n){return n=ia+n,n in this&&delete this[n]},values:s,size:l,empty:f,forEach:function(n){for(var t in this)t.charCodeAt(0)===oa&&n.call(this,t.substring(1))}}),Zo.behavior={},Zo.rebind=function(n,t){for(var e,r=1,u=arguments.length;++r=0&&(r=n.substring(e+1),n=n.substring(0,e)),n)return arguments.length<2?this[n].on(r):this[n].on(r,t);if(2===arguments.length){if(null==t)for(n in this)this.hasOwnProperty(n)&&this[n].on(r,null);return this}},Zo.event=null,Zo.requote=function(n){return n.replace(ca,"\\$&")};var ca=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,sa={}.__proto__?function(n,t){n.__proto__=t}:function(n,t){for(var e in t)n[e]=t[e]},la=function(n,t){return t.querySelector(n)},fa=function(n,t){return t.querySelectorAll(n)},ha=Bo.matches||Bo[p(Bo,"matchesSelector")],ga=function(n,t){return ha.call(n,t)};"function"==typeof Sizzle&&(la=function(n,t){return Sizzle(n,t)[0]||null},fa=Sizzle,ga=Sizzle.matchesSelector),Zo.selection=function(){return ma};var pa=Zo.selection.prototype=[];pa.select=function(n){var t,e,r,u,i=[];n=b(n);for(var o=-1,a=this.length;++o=0&&(e=n.substring(0,t),n=n.substring(t+1)),va.hasOwnProperty(e)?{space:va[e],local:n}:n}},pa.attr=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node();return n=Zo.ns.qualify(n),n.local?e.getAttributeNS(n.space,n.local):e.getAttribute(n)}for(t in n)this.each(S(t,n[t]));return this}return this.each(S(n,t))},pa.classed=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node(),r=(n=A(n)).length,u=-1;if(t=e.classList){for(;++ur){if("string"!=typeof n){2>r&&(t="");for(e in n)this.each(z(e,n[e],t));return this}if(2>r)return Wo.getComputedStyle(this.node(),null).getPropertyValue(n);e=""}return this.each(z(n,t,e))},pa.property=function(n,t){if(arguments.length<2){if("string"==typeof n)return this.node()[n];for(t in n)this.each(L(t,n[t]));return this}return this.each(L(n,t))},pa.text=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.textContent=null==t?"":t}:null==n?function(){this.textContent=""}:function(){this.textContent=n}):this.node().textContent},pa.html=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.innerHTML=null==t?"":t}:null==n?function(){this.innerHTML=""}:function(){this.innerHTML=n}):this.node().innerHTML},pa.append=function(n){return n=T(n),this.select(function(){return this.appendChild(n.apply(this,arguments))})},pa.insert=function(n,t){return n=T(n),t=b(t),this.select(function(){return this.insertBefore(n.apply(this,arguments),t.apply(this,arguments)||null)})},pa.remove=function(){return this.each(function(){var n=this.parentNode;n&&n.removeChild(this)})},pa.data=function(n,t){function e(n,e){var r,u,i,a=n.length,f=e.length,h=Math.min(a,f),g=new Array(f),p=new Array(f),v=new Array(a);if(t){var d,m=new o,y=new o,x=[];for(r=-1;++rr;++r)p[r]=q(e[r]);for(;a>r;++r)v[r]=n[r]}p.update=g,p.parentNode=g.parentNode=v.parentNode=n.parentNode,c.push(p),s.push(g),l.push(v)}var r,u,i=-1,a=this.length;if(!arguments.length){for(n=new Array(a=(r=this[0]).length);++ii;i++){u.push(t=[]),t.parentNode=(e=this[i]).parentNode;for(var a=0,c=e.length;c>a;a++)(r=e[a])&&n.call(r,r.__data__,a,i)&&t.push(r)}return _(u)},pa.order=function(){for(var n=-1,t=this.length;++n=0;)(e=r[u])&&(i&&i!==e.nextSibling&&i.parentNode.insertBefore(e,i),i=e);return this},pa.sort=function(n){n=D.apply(this,arguments);for(var t=-1,e=this.length;++tn;n++)for(var e=this[n],r=0,u=e.length;u>r;r++){var i=e[r];if(i)return i}return null},pa.size=function(){var n=0;return this.each(function(){++n}),n};var da=[];Zo.selection.enter=U,Zo.selection.enter.prototype=da,da.append=pa.append,da.empty=pa.empty,da.node=pa.node,da.call=pa.call,da.size=pa.size,da.select=function(n){for(var t,e,r,u,i,o=[],a=-1,c=this.length;++ar){if("string"!=typeof n){2>r&&(t=!1);for(e in n)this.each(F(e,n[e],t));return this}if(2>r)return(r=this.node()["__on"+n])&&r._;e=!1}return this.each(F(n,t,e))};var ya=Zo.map({mouseenter:"mouseover",mouseleave:"mouseout"});ya.forEach(function(n){"on"+n in $o&&ya.remove(n)});var xa="onselectstart"in $o?null:p(Bo.style,"userSelect"),Ma=0;Zo.mouse=function(n){return Z(n,x())};var _a=/WebKit/.test(Wo.navigator.userAgent)?-1:0;Zo.touches=function(n,t){return arguments.length<2&&(t=x().touches),t?Xo(t).map(function(t){var e=Z(n,t);return e.identifier=t.identifier,e}):[]},Zo.behavior.drag=function(){function n(){this.on("mousedown.drag",u).on("touchstart.drag",i)}function t(n,t,u,i,o){return function(){function a(){var n,e,r=t(h,v);r&&(n=r[0]-x[0],e=r[1]-x[1],p|=n|e,x=r,g({type:"drag",x:r[0]+s[0],y:r[1]+s[1],dx:n,dy:e}))}function c(){t(h,v)&&(m.on(i+d,null).on(o+d,null),y(p&&Zo.event.target===f),g({type:"dragend"}))}var s,l=this,f=Zo.event.target,h=l.parentNode,g=e.of(l,arguments),p=0,v=n(),d=".drag"+(null==v?"":"-"+v),m=Zo.select(u()).on(i+d,a).on(o+d,c),y=I(),x=t(h,v);r?(s=r.apply(l,arguments),s=[s.x-x[0],s.y-x[1]]):s=[0,0],g({type:"dragstart"})}}var e=M(n,"drag","dragstart","dragend"),r=null,u=t(v,Zo.mouse,$,"mousemove","mouseup"),i=t(V,Zo.touch,X,"touchmove","touchend");return n.origin=function(t){return arguments.length?(r=t,n):r},Zo.rebind(n,e,"on")};var ba=Math.PI,wa=2*ba,Sa=ba/2,ka=1e-6,Ea=ka*ka,Aa=ba/180,Ca=180/ba,Na=Math.SQRT2,za=2,La=4;Zo.interpolateZoom=function(n,t){function e(n){var t=n*y;if(m){var e=Q(v),o=i/(za*h)*(e*nt(Na*t+v)-K(v));return[r+o*s,u+o*l,i*e/Q(Na*t+v)]}return[r+n*s,u+n*l,i*Math.exp(Na*t)]}var r=n[0],u=n[1],i=n[2],o=t[0],a=t[1],c=t[2],s=o-r,l=a-u,f=s*s+l*l,h=Math.sqrt(f),g=(c*c-i*i+La*f)/(2*i*za*h),p=(c*c-i*i-La*f)/(2*c*za*h),v=Math.log(Math.sqrt(g*g+1)-g),d=Math.log(Math.sqrt(p*p+1)-p),m=d-v,y=(m||Math.log(c/i))/Na;return e.duration=1e3*y,e},Zo.behavior.zoom=function(){function n(n){n.on(A,s).on(Ra+".zoom",f).on("dblclick.zoom",h).on(z,l)}function t(n){return[(n[0]-S.x)/S.k,(n[1]-S.y)/S.k]}function e(n){return[n[0]*S.k+S.x,n[1]*S.k+S.y]}function r(n){S.k=Math.max(E[0],Math.min(E[1],n))}function u(n,t){t=e(t),S.x+=n[0]-t[0],S.y+=n[1]-t[1]}function i(){_&&_.domain(x.range().map(function(n){return(n-S.x)/S.k}).map(x.invert)),w&&w.domain(b.range().map(function(n){return(n-S.y)/S.k}).map(b.invert))}function o(n){n({type:"zoomstart"})}function a(n){i(),n({type:"zoom",scale:S.k,translate:[S.x,S.y]})}function c(n){n({type:"zoomend"})}function s(){function n(){l=1,u(Zo.mouse(r),h),a(s)}function e(){f.on(C,null).on(N,null),g(l&&Zo.event.target===i),c(s)}var r=this,i=Zo.event.target,s=L.of(r,arguments),l=0,f=Zo.select(Wo).on(C,n).on(N,e),h=t(Zo.mouse(r)),g=I();H.call(r),o(s)}function l(){function n(){var n=Zo.touches(g);return h=S.k,n.forEach(function(n){n.identifier in v&&(v[n.identifier]=t(n))}),n}function e(){var t=Zo.event.target;Zo.select(t).on(M,i).on(_,f),b.push(t);for(var e=Zo.event.changedTouches,o=0,c=e.length;c>o;++o)v[e[o].identifier]=null;var s=n(),l=Date.now();if(1===s.length){if(500>l-m){var h=s[0],g=v[h.identifier];r(2*S.k),u(h,g),y(),a(p)}m=l}else if(s.length>1){var h=s[0],x=s[1],w=h[0]-x[0],k=h[1]-x[1];d=w*w+k*k}}function i(){for(var n,t,e,i,o=Zo.touches(g),c=0,s=o.length;s>c;++c,i=null)if(e=o[c],i=v[e.identifier]){if(t)break;n=e,t=i}if(i){var l=(l=e[0]-n[0])*l+(l=e[1]-n[1])*l,f=d&&Math.sqrt(l/d);n=[(n[0]+e[0])/2,(n[1]+e[1])/2],t=[(t[0]+i[0])/2,(t[1]+i[1])/2],r(f*h)}m=null,u(n,t),a(p)}function f(){if(Zo.event.touches.length){for(var t=Zo.event.changedTouches,e=0,r=t.length;r>e;++e)delete v[t[e].identifier];for(var u in v)return void n()}Zo.selectAll(b).on(x,null),w.on(A,s).on(z,l),k(),c(p)}var h,g=this,p=L.of(g,arguments),v={},d=0,x=".zoom-"+Zo.event.changedTouches[0].identifier,M="touchmove"+x,_="touchend"+x,b=[],w=Zo.select(g).on(A,null).on(z,e),k=I();H.call(g),e(),o(p)}function f(){var n=L.of(this,arguments);d?clearTimeout(d):(g=t(p=v||Zo.mouse(this)),H.call(this),o(n)),d=setTimeout(function(){d=null,c(n)},50),y(),r(Math.pow(2,.002*Ta())*S.k),u(p,g),a(n)}function h(){var n=L.of(this,arguments),e=Zo.mouse(this),i=t(e),s=Math.log(S.k)/Math.LN2;o(n),r(Math.pow(2,Zo.event.shiftKey?Math.ceil(s)-1:Math.floor(s)+1)),u(e,i),a(n),c(n)}var g,p,v,d,m,x,_,b,w,S={x:0,y:0,k:1},k=[960,500],E=qa,A="mousedown.zoom",C="mousemove.zoom",N="mouseup.zoom",z="touchstart.zoom",L=M(n,"zoomstart","zoom","zoomend");return n.event=function(n){n.each(function(){var n=L.of(this,arguments),t=S;Ss?Zo.select(this).transition().each("start.zoom",function(){S=this.__chart__||{x:0,y:0,k:1},o(n)}).tween("zoom:zoom",function(){var e=k[0],r=k[1],u=e/2,i=r/2,o=Zo.interpolateZoom([(u-S.x)/S.k,(i-S.y)/S.k,e/S.k],[(u-t.x)/t.k,(i-t.y)/t.k,e/t.k]);return function(t){var r=o(t),c=e/r[2];this.__chart__=S={x:u-r[0]*c,y:i-r[1]*c,k:c},a(n)}}).each("end.zoom",function(){c(n)}):(this.__chart__=S,o(n),a(n),c(n))})},n.translate=function(t){return arguments.length?(S={x:+t[0],y:+t[1],k:S.k},i(),n):[S.x,S.y]},n.scale=function(t){return arguments.length?(S={x:S.x,y:S.y,k:+t},i(),n):S.k},n.scaleExtent=function(t){return arguments.length?(E=null==t?qa:[+t[0],+t[1]],n):E},n.center=function(t){return arguments.length?(v=t&&[+t[0],+t[1]],n):v},n.size=function(t){return arguments.length?(k=t&&[+t[0],+t[1]],n):k},n.x=function(t){return arguments.length?(_=t,x=t.copy(),S={x:0,y:0,k:1},n):_},n.y=function(t){return arguments.length?(w=t,b=t.copy(),S={x:0,y:0,k:1},n):w},Zo.rebind(n,L,"on")};var Ta,qa=[0,1/0],Ra="onwheel"in $o?(Ta=function(){return-Zo.event.deltaY*(Zo.event.deltaMode?120:1)},"wheel"):"onmousewheel"in $o?(Ta=function(){return Zo.event.wheelDelta},"mousewheel"):(Ta=function(){return-Zo.event.detail},"MozMousePixelScroll");Zo.color=et,et.prototype.toString=function(){return this.rgb()+""},Zo.hsl=rt;var Da=rt.prototype=new et;Da.brighter=function(n){return n=Math.pow(.7,arguments.length?n:1),new rt(this.h,this.s,this.l/n)},Da.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new rt(this.h,this.s,n*this.l)},Da.rgb=function(){return ut(this.h,this.s,this.l)},Zo.hcl=it;var Pa=it.prototype=new et;Pa.brighter=function(n){return new it(this.h,this.c,Math.min(100,this.l+Ua*(arguments.length?n:1)))},Pa.darker=function(n){return new it(this.h,this.c,Math.max(0,this.l-Ua*(arguments.length?n:1)))},Pa.rgb=function(){return ot(this.h,this.c,this.l).rgb()},Zo.lab=at;var Ua=18,ja=.95047,Ha=1,Fa=1.08883,Oa=at.prototype=new et;Oa.brighter=function(n){return new at(Math.min(100,this.l+Ua*(arguments.length?n:1)),this.a,this.b)},Oa.darker=function(n){return new at(Math.max(0,this.l-Ua*(arguments.length?n:1)),this.a,this.b)},Oa.rgb=function(){return ct(this.l,this.a,this.b)},Zo.rgb=gt;var Ya=gt.prototype=new et;Ya.brighter=function(n){n=Math.pow(.7,arguments.length?n:1);var t=this.r,e=this.g,r=this.b,u=30;return t||e||r?(t&&u>t&&(t=u),e&&u>e&&(e=u),r&&u>r&&(r=u),new gt(Math.min(255,t/n),Math.min(255,e/n),Math.min(255,r/n))):new gt(u,u,u)},Ya.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new gt(n*this.r,n*this.g,n*this.b)},Ya.hsl=function(){return yt(this.r,this.g,this.b)},Ya.toString=function(){return"#"+dt(this.r)+dt(this.g)+dt(this.b)};var Ia=Zo.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});Ia.forEach(function(n,t){Ia.set(n,pt(t))}),Zo.functor=bt,Zo.xhr=St(wt),Zo.dsv=function(n,t){function e(n,e,i){arguments.length<3&&(i=e,e=null);var o=kt(n,t,null==e?r:u(e),i);return o.row=function(n){return arguments.length?o.response(null==(e=n)?r:u(n)):e},o}function r(n){return e.parse(n.responseText)}function u(n){return function(t){return e.parse(t.responseText,n)}}function i(t){return t.map(o).join(n)}function o(n){return a.test(n)?'"'+n.replace(/\"/g,'""')+'"':n}var a=new RegExp('["'+n+"\n]"),c=n.charCodeAt(0);return e.parse=function(n,t){var r;return e.parseRows(n,function(n,e){if(r)return r(n,e-1);var u=new Function("d","return {"+n.map(function(n,t){return JSON.stringify(n)+": d["+t+"]"}).join(",")+"}");r=t?function(n,e){return t(u(n),e)}:u})},e.parseRows=function(n,t){function e(){if(l>=s)return o;if(u)return u=!1,i;var t=l;if(34===n.charCodeAt(t)){for(var e=t;e++l;){var r=n.charCodeAt(l++),a=1;if(10===r)u=!0;else if(13===r)u=!0,10===n.charCodeAt(l)&&(++l,++a);else if(r!==c)continue;return n.substring(t,l-a)}return n.substring(t)}for(var r,u,i={},o={},a=[],s=n.length,l=0,f=0;(r=e())!==o;){for(var h=[];r!==i&&r!==o;)h.push(r),r=e();(!t||(h=t(h,f++)))&&a.push(h)}return a},e.format=function(t){if(Array.isArray(t[0]))return e.formatRows(t);var r=new h,u=[];return t.forEach(function(n){for(var t in n)r.has(t)||u.push(r.add(t))}),[u.map(o).join(n)].concat(t.map(function(t){return u.map(function(n){return o(t[n])}).join(n)})).join("\n")},e.formatRows=function(n){return n.map(i).join("\n")},e},Zo.csv=Zo.dsv(",","text/csv"),Zo.tsv=Zo.dsv(" ","text/tab-separated-values"),Zo.touch=function(n,t,e){if(arguments.length<3&&(e=t,t=x().changedTouches),t)for(var r,u=0,i=t.length;i>u;++u)if((r=t[u]).identifier===e)return Z(n,r)};var Za,Va,Xa,$a,Ba,Wa=Wo[p(Wo,"requestAnimationFrame")]||function(n){setTimeout(n,17)};Zo.timer=function(n,t,e){var r=arguments.length;2>r&&(t=0),3>r&&(e=Date.now());var u=e+t,i={c:n,t:u,f:!1,n:null};Va?Va.n=i:Za=i,Va=i,Xa||($a=clearTimeout($a),Xa=1,Wa(At))},Zo.timer.flush=function(){Ct(),Nt()},Zo.round=function(n,t){return t?Math.round(n*(t=Math.pow(10,t)))/t:Math.round(n)};var Ja=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Lt);Zo.formatPrefix=function(n,t){var e=0;return n&&(0>n&&(n*=-1),t&&(n=Zo.round(n,zt(n,t))),e=1+Math.floor(1e-12+Math.log(n)/Math.LN10),e=Math.max(-24,Math.min(24,3*Math.floor((e-1)/3)))),Ja[8+e/3]};var Ga=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Ka=Zo.map({b:function(n){return n.toString(2)},c:function(n){return String.fromCharCode(n)},o:function(n){return n.toString(8)},x:function(n){return n.toString(16)},X:function(n){return n.toString(16).toUpperCase()},g:function(n,t){return n.toPrecision(t)},e:function(n,t){return n.toExponential(t)},f:function(n,t){return n.toFixed(t)},r:function(n,t){return(n=Zo.round(n,zt(n,t))).toFixed(Math.max(0,Math.min(20,zt(n*(1+1e-15),t))))}}),Qa=Zo.time={},nc=Date;Rt.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){tc.setUTCDate.apply(this._,arguments)},setDay:function(){tc.setUTCDay.apply(this._,arguments)},setFullYear:function(){tc.setUTCFullYear.apply(this._,arguments)},setHours:function(){tc.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){tc.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){tc.setUTCMinutes.apply(this._,arguments)},setMonth:function(){tc.setUTCMonth.apply(this._,arguments)},setSeconds:function(){tc.setUTCSeconds.apply(this._,arguments)},setTime:function(){tc.setTime.apply(this._,arguments)}};var tc=Date.prototype;Qa.year=Dt(function(n){return n=Qa.day(n),n.setMonth(0,1),n},function(n,t){n.setFullYear(n.getFullYear()+t)},function(n){return n.getFullYear()}),Qa.years=Qa.year.range,Qa.years.utc=Qa.year.utc.range,Qa.day=Dt(function(n){var t=new nc(2e3,0);return t.setFullYear(n.getFullYear(),n.getMonth(),n.getDate()),t},function(n,t){n.setDate(n.getDate()+t)},function(n){return n.getDate()-1}),Qa.days=Qa.day.range,Qa.days.utc=Qa.day.utc.range,Qa.dayOfYear=function(n){var t=Qa.year(n);return Math.floor((n-t-6e4*(n.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(n,t){t=7-t;var e=Qa[n]=Dt(function(n){return(n=Qa.day(n)).setDate(n.getDate()-(n.getDay()+t)%7),n},function(n,t){n.setDate(n.getDate()+7*Math.floor(t))},function(n){var e=Qa.year(n).getDay();return Math.floor((Qa.dayOfYear(n)+(e+t)%7)/7)-(e!==t)});Qa[n+"s"]=e.range,Qa[n+"s"].utc=e.utc.range,Qa[n+"OfYear"]=function(n){var e=Qa.year(n).getDay();return Math.floor((Qa.dayOfYear(n)+(e+t)%7)/7)}}),Qa.week=Qa.sunday,Qa.weeks=Qa.sunday.range,Qa.weeks.utc=Qa.sunday.utc.range,Qa.weekOfYear=Qa.sundayOfYear;var ec={"-":"",_:" ",0:"0"},rc=/^\s*\d+/,uc=/^%/;Zo.locale=function(n){return{numberFormat:Tt(n),timeFormat:Ut(n)}};var ic=Zo.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});Zo.format=ic.numberFormat,Zo.geo={},ue.prototype={s:0,t:0,add:function(n){ie(n,this.t,oc),ie(oc.s,this.s,this),this.s?this.t+=oc.t:this.s=oc.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var oc=new ue;Zo.geo.stream=function(n,t){n&&ac.hasOwnProperty(n.type)?ac[n.type](n,t):oe(n,t)};var ac={Feature:function(n,t){oe(n.geometry,t)},FeatureCollection:function(n,t){for(var e=n.features,r=-1,u=e.length;++rn?4*ba+n:n,fc.lineStart=fc.lineEnd=fc.point=v}};Zo.geo.bounds=function(){function n(n,t){x.push(M=[l=n,h=n]),f>t&&(f=t),t>g&&(g=t)}function t(t,e){var r=le([t*Aa,e*Aa]);if(m){var u=he(m,r),i=[u[1],-u[0],0],o=he(i,u);ve(o),o=de(o);var c=t-p,s=c>0?1:-1,v=o[0]*Ca*s,d=ua(c)>180;if(d^(v>s*p&&s*t>v)){var y=o[1]*Ca;y>g&&(g=y)}else if(v=(v+360)%360-180,d^(v>s*p&&s*t>v)){var y=-o[1]*Ca;f>y&&(f=y)}else f>e&&(f=e),e>g&&(g=e);d?p>t?a(l,t)>a(l,h)&&(h=t):a(t,h)>a(l,h)&&(l=t):h>=l?(l>t&&(l=t),t>h&&(h=t)):t>p?a(l,t)>a(l,h)&&(h=t):a(t,h)>a(l,h)&&(l=t)}else n(t,e);m=r,p=t}function e(){_.point=t}function r(){M[0]=l,M[1]=h,_.point=n,m=null}function u(n,e){if(m){var r=n-p;y+=ua(r)>180?r+(r>0?360:-360):r}else v=n,d=e;fc.point(n,e),t(n,e)}function i(){fc.lineStart()}function o(){u(v,d),fc.lineEnd(),ua(y)>ka&&(l=-(h=180)),M[0]=l,M[1]=h,m=null}function a(n,t){return(t-=n)<0?t+360:t}function c(n,t){return n[0]-t[0]}function s(n,t){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:nlc?(l=-(h=180),f=-(g=90)):y>ka?g=90:-ka>y&&(f=-90),M[0]=l,M[1]=h}};return function(n){g=h=-(l=f=1/0),x=[],Zo.geo.stream(n,_);var t=x.length;if(t){x.sort(c);for(var e,r=1,u=x[0],i=[u];t>r;++r)e=x[r],s(e[0],u)||s(e[1],u)?(a(u[0],e[1])>a(u[0],u[1])&&(u[1]=e[1]),a(e[0],u[1])>a(u[0],u[1])&&(u[0]=e[0])):i.push(u=e); - for(var o,e,p=-1/0,t=i.length-1,r=0,u=i[t];t>=r;u=e,++r)e=i[r],(o=a(u[1],e[0]))>p&&(p=o,l=e[0],h=u[1])}return x=M=null,1/0===l||1/0===f?[[0/0,0/0],[0/0,0/0]]:[[l,f],[h,g]]}}(),Zo.geo.centroid=function(n){hc=gc=pc=vc=dc=mc=yc=xc=Mc=_c=bc=0,Zo.geo.stream(n,wc);var t=Mc,e=_c,r=bc,u=t*t+e*e+r*r;return Ea>u&&(t=mc,e=yc,r=xc,ka>gc&&(t=pc,e=vc,r=dc),u=t*t+e*e+r*r,Ea>u)?[0/0,0/0]:[Math.atan2(e,t)*Ca,G(r/Math.sqrt(u))*Ca]};var hc,gc,pc,vc,dc,mc,yc,xc,Mc,_c,bc,wc={sphere:v,point:ye,lineStart:Me,lineEnd:_e,polygonStart:function(){wc.lineStart=be},polygonEnd:function(){wc.lineStart=Me}},Sc=Ae(we,Te,Re,[-ba,-ba/2]),kc=1e9;Zo.geo.clipExtent=function(){var n,t,e,r,u,i,o={stream:function(n){return u&&(u.valid=!1),u=i(n),u.valid=!0,u},extent:function(a){return arguments.length?(i=Ue(n=+a[0][0],t=+a[0][1],e=+a[1][0],r=+a[1][1]),u&&(u.valid=!1,u=null),o):[[n,t],[e,r]]}};return o.extent([[0,0],[960,500]])},(Zo.geo.conicEqualArea=function(){return He(Fe)}).raw=Fe,Zo.geo.albers=function(){return Zo.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},Zo.geo.albersUsa=function(){function n(n){var i=n[0],o=n[1];return t=null,e(i,o),t||(r(i,o),t)||u(i,o),t}var t,e,r,u,i=Zo.geo.albers(),o=Zo.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=Zo.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),c={point:function(n,e){t=[n,e]}};return n.invert=function(n){var t=i.scale(),e=i.translate(),r=(n[0]-e[0])/t,u=(n[1]-e[1])/t;return(u>=.12&&.234>u&&r>=-.425&&-.214>r?o:u>=.166&&.234>u&&r>=-.214&&-.115>r?a:i).invert(n)},n.stream=function(n){var t=i.stream(n),e=o.stream(n),r=a.stream(n);return{point:function(n,u){t.point(n,u),e.point(n,u),r.point(n,u)},sphere:function(){t.sphere(),e.sphere(),r.sphere()},lineStart:function(){t.lineStart(),e.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),e.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),e.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),e.polygonEnd(),r.polygonEnd()}}},n.precision=function(t){return arguments.length?(i.precision(t),o.precision(t),a.precision(t),n):i.precision()},n.scale=function(t){return arguments.length?(i.scale(t),o.scale(.35*t),a.scale(t),n.translate(i.translate())):i.scale()},n.translate=function(t){if(!arguments.length)return i.translate();var s=i.scale(),l=+t[0],f=+t[1];return e=i.translate(t).clipExtent([[l-.455*s,f-.238*s],[l+.455*s,f+.238*s]]).stream(c).point,r=o.translate([l-.307*s,f+.201*s]).clipExtent([[l-.425*s+ka,f+.12*s+ka],[l-.214*s-ka,f+.234*s-ka]]).stream(c).point,u=a.translate([l-.205*s,f+.212*s]).clipExtent([[l-.214*s+ka,f+.166*s+ka],[l-.115*s-ka,f+.234*s-ka]]).stream(c).point,n},n.scale(1070)};var Ec,Ac,Cc,Nc,zc,Lc,Tc={point:v,lineStart:v,lineEnd:v,polygonStart:function(){Ac=0,Tc.lineStart=Oe},polygonEnd:function(){Tc.lineStart=Tc.lineEnd=Tc.point=v,Ec+=ua(Ac/2)}},qc={point:Ye,lineStart:v,lineEnd:v,polygonStart:v,polygonEnd:v},Rc={point:Ve,lineStart:Xe,lineEnd:$e,polygonStart:function(){Rc.lineStart=Be},polygonEnd:function(){Rc.point=Ve,Rc.lineStart=Xe,Rc.lineEnd=$e}};Zo.geo.path=function(){function n(n){return n&&("function"==typeof a&&i.pointRadius(+a.apply(this,arguments)),o&&o.valid||(o=u(i)),Zo.geo.stream(n,o)),i.result()}function t(){return o=null,n}var e,r,u,i,o,a=4.5;return n.area=function(n){return Ec=0,Zo.geo.stream(n,u(Tc)),Ec},n.centroid=function(n){return pc=vc=dc=mc=yc=xc=Mc=_c=bc=0,Zo.geo.stream(n,u(Rc)),bc?[Mc/bc,_c/bc]:xc?[mc/xc,yc/xc]:dc?[pc/dc,vc/dc]:[0/0,0/0]},n.bounds=function(n){return zc=Lc=-(Cc=Nc=1/0),Zo.geo.stream(n,u(qc)),[[Cc,Nc],[zc,Lc]]},n.projection=function(n){return arguments.length?(u=(e=n)?n.stream||Ge(n):wt,t()):e},n.context=function(n){return arguments.length?(i=null==(r=n)?new Ie:new We(n),"function"!=typeof a&&i.pointRadius(a),t()):r},n.pointRadius=function(t){return arguments.length?(a="function"==typeof t?t:(i.pointRadius(+t),+t),n):a},n.projection(Zo.geo.albersUsa()).context(null)},Zo.geo.transform=function(n){return{stream:function(t){var e=new Ke(t);for(var r in n)e[r]=n[r];return e}}},Ke.prototype={point:function(n,t){this.stream.point(n,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},Zo.geo.projection=nr,Zo.geo.projectionMutator=tr,(Zo.geo.equirectangular=function(){return nr(rr)}).raw=rr.invert=rr,Zo.geo.rotation=function(n){function t(t){return t=n(t[0]*Aa,t[1]*Aa),t[0]*=Ca,t[1]*=Ca,t}return n=ir(n[0]%360*Aa,n[1]*Aa,n.length>2?n[2]*Aa:0),t.invert=function(t){return t=n.invert(t[0]*Aa,t[1]*Aa),t[0]*=Ca,t[1]*=Ca,t},t},ur.invert=rr,Zo.geo.circle=function(){function n(){var n="function"==typeof r?r.apply(this,arguments):r,t=ir(-n[0]*Aa,-n[1]*Aa,0).invert,u=[];return e(null,null,1,{point:function(n,e){u.push(n=t(n,e)),n[0]*=Ca,n[1]*=Ca}}),{type:"Polygon",coordinates:[u]}}var t,e,r=[0,0],u=6;return n.origin=function(t){return arguments.length?(r=t,n):r},n.angle=function(r){return arguments.length?(e=sr((t=+r)*Aa,u*Aa),n):t},n.precision=function(r){return arguments.length?(e=sr(t*Aa,(u=+r)*Aa),n):u},n.angle(90)},Zo.geo.distance=function(n,t){var e,r=(t[0]-n[0])*Aa,u=n[1]*Aa,i=t[1]*Aa,o=Math.sin(r),a=Math.cos(r),c=Math.sin(u),s=Math.cos(u),l=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((e=f*o)*e+(e=s*l-c*f*a)*e),c*l+s*f*a)},Zo.geo.graticule=function(){function n(){return{type:"MultiLineString",coordinates:t()}}function t(){return Zo.range(Math.ceil(i/d)*d,u,d).map(h).concat(Zo.range(Math.ceil(s/m)*m,c,m).map(g)).concat(Zo.range(Math.ceil(r/p)*p,e,p).filter(function(n){return ua(n%d)>ka}).map(l)).concat(Zo.range(Math.ceil(a/v)*v,o,v).filter(function(n){return ua(n%m)>ka}).map(f))}var e,r,u,i,o,a,c,s,l,f,h,g,p=10,v=p,d=90,m=360,y=2.5;return n.lines=function(){return t().map(function(n){return{type:"LineString",coordinates:n}})},n.outline=function(){return{type:"Polygon",coordinates:[h(i).concat(g(c).slice(1),h(u).reverse().slice(1),g(s).reverse().slice(1))]}},n.extent=function(t){return arguments.length?n.majorExtent(t).minorExtent(t):n.minorExtent()},n.majorExtent=function(t){return arguments.length?(i=+t[0][0],u=+t[1][0],s=+t[0][1],c=+t[1][1],i>u&&(t=i,i=u,u=t),s>c&&(t=s,s=c,c=t),n.precision(y)):[[i,s],[u,c]]},n.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],a=+t[0][1],o=+t[1][1],r>e&&(t=r,r=e,e=t),a>o&&(t=a,a=o,o=t),n.precision(y)):[[r,a],[e,o]]},n.step=function(t){return arguments.length?n.majorStep(t).minorStep(t):n.minorStep()},n.majorStep=function(t){return arguments.length?(d=+t[0],m=+t[1],n):[d,m]},n.minorStep=function(t){return arguments.length?(p=+t[0],v=+t[1],n):[p,v]},n.precision=function(t){return arguments.length?(y=+t,l=fr(a,o,90),f=hr(r,e,y),h=fr(s,c,90),g=hr(i,u,y),n):y},n.majorExtent([[-180,-90+ka],[180,90-ka]]).minorExtent([[-180,-80-ka],[180,80+ka]])},Zo.geo.greatArc=function(){function n(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),e||u.apply(this,arguments)]}}var t,e,r=gr,u=pr;return n.distance=function(){return Zo.geo.distance(t||r.apply(this,arguments),e||u.apply(this,arguments))},n.source=function(e){return arguments.length?(r=e,t="function"==typeof e?null:e,n):r},n.target=function(t){return arguments.length?(u=t,e="function"==typeof t?null:t,n):u},n.precision=function(){return arguments.length?n:0},n},Zo.geo.interpolate=function(n,t){return vr(n[0]*Aa,n[1]*Aa,t[0]*Aa,t[1]*Aa)},Zo.geo.length=function(n){return Dc=0,Zo.geo.stream(n,Pc),Dc};var Dc,Pc={sphere:v,point:v,lineStart:dr,lineEnd:v,polygonStart:v,polygonEnd:v},Uc=mr(function(n){return Math.sqrt(2/(1+n))},function(n){return 2*Math.asin(n/2)});(Zo.geo.azimuthalEqualArea=function(){return nr(Uc)}).raw=Uc;var jc=mr(function(n){var t=Math.acos(n);return t&&t/Math.sin(t)},wt);(Zo.geo.azimuthalEquidistant=function(){return nr(jc)}).raw=jc,(Zo.geo.conicConformal=function(){return He(yr)}).raw=yr,(Zo.geo.conicEquidistant=function(){return He(xr)}).raw=xr;var Hc=mr(function(n){return 1/n},Math.atan);(Zo.geo.gnomonic=function(){return nr(Hc)}).raw=Hc,Mr.invert=function(n,t){return[n,2*Math.atan(Math.exp(t))-Sa]},(Zo.geo.mercator=function(){return _r(Mr)}).raw=Mr;var Fc=mr(function(){return 1},Math.asin);(Zo.geo.orthographic=function(){return nr(Fc)}).raw=Fc;var Oc=mr(function(n){return 1/(1+n)},function(n){return 2*Math.atan(n)});(Zo.geo.stereographic=function(){return nr(Oc)}).raw=Oc,br.invert=function(n,t){return[-t,2*Math.atan(Math.exp(n))-Sa]},(Zo.geo.transverseMercator=function(){var n=_r(br),t=n.center,e=n.rotate;return n.center=function(n){return n?t([-n[1],n[0]]):(n=t(),[n[1],-n[0]])},n.rotate=function(n){return n?e([n[0],n[1],n.length>2?n[2]+90:90]):(n=e(),[n[0],n[1],n[2]-90])},e([0,0,90])}).raw=br,Zo.geom={},Zo.geom.hull=function(n){function t(n){if(n.length<3)return[];var t,u=bt(e),i=bt(r),o=n.length,a=[],c=[];for(t=0;o>t;t++)a.push([+u.call(this,n[t],t),+i.call(this,n[t],t),t]);for(a.sort(Er),t=0;o>t;t++)c.push([a[t][0],-a[t][1]]);var s=kr(a),l=kr(c),f=l[0]===s[0],h=l[l.length-1]===s[s.length-1],g=[];for(t=s.length-1;t>=0;--t)g.push(n[a[s[t]][2]]);for(t=+f;t=r&&s.x<=i&&s.y>=u&&s.y<=o?[[r,o],[i,o],[i,u],[r,u]]:[];l.point=n[a]}),t}function e(n){return n.map(function(n,t){return{x:Math.round(i(n,t)/ka)*ka,y:Math.round(o(n,t)/ka)*ka,i:t}})}var r=wr,u=Sr,i=r,o=u,a=Jc;return n?t(n):(t.links=function(n){return tu(e(n)).edges.filter(function(n){return n.l&&n.r}).map(function(t){return{source:n[t.l.i],target:n[t.r.i]}})},t.triangles=function(n){var t=[];return tu(e(n)).cells.forEach(function(e,r){for(var u,i,o=e.site,a=e.edges.sort(Hr),c=-1,s=a.length,l=a[s-1].edge,f=l.l===o?l.r:l.l;++c=s,h=r>=l,g=(h<<1)+f;n.leaf=!1,n=n.nodes[g]||(n.nodes[g]=ou()),f?u=s:a=s,h?o=l:c=l,i(n,t,e,r,u,o,a,c)}var l,f,h,g,p,v,d,m,y,x=bt(a),M=bt(c);if(null!=t)v=t,d=e,m=r,y=u;else if(m=y=-(v=d=1/0),f=[],h=[],p=n.length,o)for(g=0;p>g;++g)l=n[g],l.xm&&(m=l.x),l.y>y&&(y=l.y),f.push(l.x),h.push(l.y);else for(g=0;p>g;++g){var _=+x(l=n[g],g),b=+M(l,g);v>_&&(v=_),d>b&&(d=b),_>m&&(m=_),b>y&&(y=b),f.push(_),h.push(b)}var w=m-v,S=y-d;w>S?y=d+w:m=v+S;var k=ou();if(k.add=function(n){i(k,n,+x(n,++g),+M(n,g),v,d,m,y)},k.visit=function(n){au(n,k,v,d,m,y)},g=-1,null==t){for(;++g=0?n.substring(0,t):n,r=t>=0?n.substring(t+1):"in";return e=ns.get(e)||Qc,r=ts.get(r)||wt,pu(r(e.apply(null,Vo.call(arguments,1))))},Zo.interpolateHcl=Au,Zo.interpolateHsl=Cu,Zo.interpolateLab=Nu,Zo.interpolateRound=zu,Zo.transform=function(n){var t=$o.createElementNS(Zo.ns.prefix.svg,"g");return(Zo.transform=function(n){if(null!=n){t.setAttribute("transform",n);var e=t.transform.baseVal.consolidate()}return new Lu(e?e.matrix:es)})(n)},Lu.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var es={a:1,b:0,c:0,d:1,e:0,f:0};Zo.interpolateTransform=Du,Zo.layout={},Zo.layout.bundle=function(){return function(n){for(var t=[],e=-1,r=n.length;++ea*a/d){if(p>c){var s=t.charge/c;n.px-=i*s,n.py-=o*s}return!0}if(t.point&&c&&p>c){var s=t.pointCharge/c;n.px-=i*s,n.py-=o*s}}return!t.charge}}function t(n){n.px=Zo.event.x,n.py=Zo.event.y,a.resume()}var e,r,u,i,o,a={},c=Zo.dispatch("start","tick","end"),s=[1,1],l=.9,f=rs,h=us,g=-30,p=is,v=.1,d=.64,m=[],y=[];return a.tick=function(){if((r*=.99)<.005)return c.end({type:"end",alpha:r=0}),!0;var t,e,a,f,h,p,d,x,M,_=m.length,b=y.length;for(e=0;b>e;++e)a=y[e],f=a.source,h=a.target,x=h.x-f.x,M=h.y-f.y,(p=x*x+M*M)&&(p=r*i[e]*((p=Math.sqrt(p))-u[e])/p,x*=p,M*=p,h.x-=x*(d=f.weight/(h.weight+f.weight)),h.y-=M*d,f.x+=x*(d=1-d),f.y+=M*d);if((d=r*v)&&(x=s[0]/2,M=s[1]/2,e=-1,d))for(;++e<_;)a=m[e],a.x+=(x-a.x)*d,a.y+=(M-a.y)*d;if(g)for(Vu(t=Zo.geom.quadtree(m),r,o),e=-1;++e<_;)(a=m[e]).fixed||t.visit(n(a));for(e=-1;++e<_;)a=m[e],a.fixed?(a.x=a.px,a.y=a.py):(a.x-=(a.px-(a.px=a.x))*l,a.y-=(a.py-(a.py=a.y))*l);c.tick({type:"tick",alpha:r})},a.nodes=function(n){return arguments.length?(m=n,a):m},a.links=function(n){return arguments.length?(y=n,a):y},a.size=function(n){return arguments.length?(s=n,a):s},a.linkDistance=function(n){return arguments.length?(f="function"==typeof n?n:+n,a):f},a.distance=a.linkDistance,a.linkStrength=function(n){return arguments.length?(h="function"==typeof n?n:+n,a):h},a.friction=function(n){return arguments.length?(l=+n,a):l},a.charge=function(n){return arguments.length?(g="function"==typeof n?n:+n,a):g},a.chargeDistance=function(n){return arguments.length?(p=n*n,a):Math.sqrt(p)},a.gravity=function(n){return arguments.length?(v=+n,a):v},a.theta=function(n){return arguments.length?(d=n*n,a):Math.sqrt(d)},a.alpha=function(n){return arguments.length?(n=+n,r?r=n>0?n:0:n>0&&(c.start({type:"start",alpha:r=n}),Zo.timer(a.tick)),a):r},a.start=function(){function n(n,r){if(!e){for(e=new Array(c),a=0;c>a;++a)e[a]=[];for(a=0;s>a;++a){var u=y[a];e[u.source.index].push(u.target),e[u.target.index].push(u.source)}}for(var i,o=e[t],a=-1,s=o.length;++at;++t)(r=m[t]).index=t,r.weight=0;for(t=0;l>t;++t)r=y[t],"number"==typeof r.source&&(r.source=m[r.source]),"number"==typeof r.target&&(r.target=m[r.target]),++r.source.weight,++r.target.weight;for(t=0;c>t;++t)r=m[t],isNaN(r.x)&&(r.x=n("x",p)),isNaN(r.y)&&(r.y=n("y",v)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(u=[],"function"==typeof f)for(t=0;l>t;++t)u[t]=+f.call(this,y[t],t);else for(t=0;l>t;++t)u[t]=f;if(i=[],"function"==typeof h)for(t=0;l>t;++t)i[t]=+h.call(this,y[t],t);else for(t=0;l>t;++t)i[t]=h;if(o=[],"function"==typeof g)for(t=0;c>t;++t)o[t]=+g.call(this,m[t],t);else for(t=0;c>t;++t)o[t]=g;return a.resume()},a.resume=function(){return a.alpha(.1)},a.stop=function(){return a.alpha(0)},a.drag=function(){return e||(e=Zo.behavior.drag().origin(wt).on("dragstart.force",Ou).on("drag.force",t).on("dragend.force",Yu)),arguments.length?(this.on("mouseover.force",Iu).on("mouseout.force",Zu).call(e),void 0):e},Zo.rebind(a,c,"on")};var rs=20,us=1,is=1/0;Zo.layout.hierarchy=function(){function n(u){var i,o=[u],a=[];for(u.depth=0;null!=(i=o.pop());)if(a.push(i),(s=e.call(n,i,i.depth))&&(c=s.length)){for(var c,s,l;--c>=0;)o.push(l=s[c]),l.parent=i,l.depth=i.depth+1;r&&(i.value=0),i.children=s}else r&&(i.value=+r.call(n,i,i.depth)||0),delete i.children;return Bu(u,function(n){var e,u;t&&(e=n.children)&&e.sort(t),r&&(u=n.parent)&&(u.value+=n.value)}),a}var t=Gu,e=Wu,r=Ju;return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&($u(t,function(n){n.children&&(n.value=0)}),Bu(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},Zo.layout.partition=function(){function n(t,e,r,u){var i=t.children;if(t.x=e,t.y=t.depth*u,t.dx=r,t.dy=u,i&&(o=i.length)){var o,a,c,s=-1;for(r=t.value?r/t.value:0;++sg;++g)for(u.call(n,s[0][g],p=v[g],l[0][g][1]),h=1;d>h;++h)u.call(n,s[h][g],p+=l[h-1][g][1],l[h][g][1]);return a}var t=wt,e=ei,r=ri,u=ti,i=Qu,o=ni;return n.values=function(e){return arguments.length?(t=e,n):t},n.order=function(t){return arguments.length?(e="function"==typeof t?t:as.get(t)||ei,n):e},n.offset=function(t){return arguments.length?(r="function"==typeof t?t:cs.get(t)||ri,n):r},n.x=function(t){return arguments.length?(i=t,n):i},n.y=function(t){return arguments.length?(o=t,n):o},n.out=function(t){return arguments.length?(u=t,n):u},n};var as=Zo.map({"inside-out":function(n){var t,e,r=n.length,u=n.map(ui),i=n.map(ii),o=Zo.range(r).sort(function(n,t){return u[n]-u[t]}),a=0,c=0,s=[],l=[];for(t=0;r>t;++t)e=o[t],c>a?(a+=i[e],s.push(e)):(c+=i[e],l.push(e));return l.reverse().concat(s)},reverse:function(n){return Zo.range(n.length).reverse()},"default":ei}),cs=Zo.map({silhouette:function(n){var t,e,r,u=n.length,i=n[0].length,o=[],a=0,c=[];for(e=0;i>e;++e){for(t=0,r=0;u>t;t++)r+=n[t][e][1];r>a&&(a=r),o.push(r)}for(e=0;i>e;++e)c[e]=(a-o[e])/2;return c},wiggle:function(n){var t,e,r,u,i,o,a,c,s,l=n.length,f=n[0],h=f.length,g=[];for(g[0]=c=s=0,e=1;h>e;++e){for(t=0,u=0;l>t;++t)u+=n[t][e][1];for(t=0,i=0,a=f[e][0]-f[e-1][0];l>t;++t){for(r=0,o=(n[t][e][1]-n[t][e-1][1])/(2*a);t>r;++r)o+=(n[r][e][1]-n[r][e-1][1])/a;i+=o*n[t][e][1]}g[e]=c-=u?i/u*a:0,s>c&&(s=c)}for(e=0;h>e;++e)g[e]-=s;return g},expand:function(n){var t,e,r,u=n.length,i=n[0].length,o=1/u,a=[];for(e=0;i>e;++e){for(t=0,r=0;u>t;t++)r+=n[t][e][1];if(r)for(t=0;u>t;t++)n[t][e][1]/=r;else for(t=0;u>t;t++)n[t][e][1]=o}for(e=0;i>e;++e)a[e]=0;return a},zero:ri});Zo.layout.histogram=function(){function n(n,i){for(var o,a,c=[],s=n.map(e,this),l=r.call(this,s,i),f=u.call(this,l,s,i),i=-1,h=s.length,g=f.length-1,p=t?1:1/h;++i0)for(i=-1;++i=l[0]&&a<=l[1]&&(o=c[Zo.bisect(f,a,1,g)-1],o.y+=p,o.push(n[i]));return c}var t=!0,e=Number,r=si,u=ai;return n.value=function(t){return arguments.length?(e=t,n):e},n.range=function(t){return arguments.length?(r=bt(t),n):r},n.bins=function(t){return arguments.length?(u="number"==typeof t?function(n){return ci(n,t)}:bt(t),n):u},n.frequency=function(e){return arguments.length?(t=!!e,n):t},n},Zo.layout.pack=function(){function n(n,i){var o=e.call(this,n,i),a=o[0],c=u[0],s=u[1],l=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(a.x=a.y=0,Bu(a,function(n){n.r=+l(n.value)}),Bu(a,pi),r){var f=r*(t?1:Math.max(2*a.r/c,2*a.r/s))/2;Bu(a,function(n){n.r+=f}),Bu(a,pi),Bu(a,function(n){n.r-=f})}return mi(a,c/2,s/2,t?1:1/Math.max(2*a.r/c,2*a.r/s)),o}var t,e=Zo.layout.hierarchy().sort(li),r=0,u=[1,1];return n.size=function(t){return arguments.length?(u=t,n):u},n.radius=function(e){return arguments.length?(t=null==e||"function"==typeof e?e:+e,n):t},n.padding=function(t){return arguments.length?(r=+t,n):r},Xu(n,e)},Zo.layout.tree=function(){function n(n,u){var l=o.call(this,n,u),f=l[0],h=t(f);if(Bu(h,e),h.parent.m=-h.z,$u(h,r),s)$u(f,i);else{var g=f,p=f,v=f;$u(f,function(n){n.xp.x&&(p=n),n.depth>v.depth&&(v=n)});var d=a(g,p)/2-g.x,m=c[0]/(p.x+a(p,g)/2+d),y=c[1]/(v.depth||1);$u(f,function(n){n.x=(n.x+d)*m,n.y=n.depth*y})}return l}function t(n){for(var t,e={A:null,children:[n]},r=[e];null!=(t=r.pop());)for(var u,i=t.children,o=0,a=i.length;a>o;++o)r.push((i[o]=u={_:i[o],parent:t,children:(u=i[o].children)&&u.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=u);return e.children[0]}function e(n){var t=n.children,e=n.parent.children,r=n.i?e[n.i-1]:null;if(t.length){wi(n);var i=(t[0].z+t[t.length-1].z)/2;r?(n.z=r.z+a(n._,r._),n.m=n.z-i):n.z=i}else r&&(n.z=r.z+a(n._,r._));n.parent.A=u(n,r,n.parent.A||e[0])}function r(n){n._.x=n.z+n.parent.m,n.m+=n.parent.m}function u(n,t,e){if(t){for(var r,u=n,i=n,o=t,c=u.parent.children[0],s=u.m,l=i.m,f=o.m,h=c.m;o=_i(o),u=Mi(u),o&&u;)c=Mi(c),i=_i(i),i.a=n,r=o.z+f-u.z-s+a(o._,u._),r>0&&(bi(Si(o,n,e),n,r),s+=r,l+=r),f+=o.m,s+=u.m,h+=c.m,l+=i.m;o&&!_i(i)&&(i.t=o,i.m+=f-l),u&&!Mi(c)&&(c.t=u,c.m+=s-h,e=n)}return e}function i(n){n.x*=c[0],n.y=n.depth*c[1]}var o=Zo.layout.hierarchy().sort(null).value(null),a=xi,c=[1,1],s=null;return n.separation=function(t){return arguments.length?(a=t,n):a},n.size=function(t){return arguments.length?(s=null==(c=t)?i:null,n):s?null:c},n.nodeSize=function(t){return arguments.length?(s=null==(c=t)?null:i,n):s?c:null},Xu(n,o)},Zo.layout.cluster=function(){function n(n,i){var o,a=t.call(this,n,i),c=a[0],s=0;Bu(c,function(n){var t=n.children;t&&t.length?(n.x=Ei(t),n.y=ki(t)):(n.x=o?s+=e(n,o):0,n.y=0,o=n)});var l=Ai(c),f=Ci(c),h=l.x-e(l,f)/2,g=f.x+e(f,l)/2;return Bu(c,u?function(n){n.x=(n.x-c.x)*r[0],n.y=(c.y-n.y)*r[1]}:function(n){n.x=(n.x-h)/(g-h)*r[0],n.y=(1-(c.y?n.y/c.y:1))*r[1]}),a}var t=Zo.layout.hierarchy().sort(null).value(null),e=xi,r=[1,1],u=!1;return n.separation=function(t){return arguments.length?(e=t,n):e},n.size=function(t){return arguments.length?(u=null==(r=t),n):u?null:r},n.nodeSize=function(t){return arguments.length?(u=null!=(r=t),n):u?r:null},Xu(n,t)},Zo.layout.treemap=function(){function n(n,t){for(var e,r,u=-1,i=n.length;++ut?0:t),e.area=isNaN(r)||0>=r?0:r}function t(e){var i=e.children;if(i&&i.length){var o,a,c,s=f(e),l=[],h=i.slice(),p=1/0,v="slice"===g?s.dx:"dice"===g?s.dy:"slice-dice"===g?1&e.depth?s.dy:s.dx:Math.min(s.dx,s.dy);for(n(h,s.dx*s.dy/e.value),l.area=0;(c=h.length)>0;)l.push(o=h[c-1]),l.area+=o.area,"squarify"!==g||(a=r(l,v))<=p?(h.pop(),p=a):(l.area-=l.pop().area,u(l,v,s,!1),v=Math.min(s.dx,s.dy),l.length=l.area=0,p=1/0);l.length&&(u(l,v,s,!0),l.length=l.area=0),i.forEach(t)}}function e(t){var r=t.children;if(r&&r.length){var i,o=f(t),a=r.slice(),c=[];for(n(a,o.dx*o.dy/t.value),c.area=0;i=a.pop();)c.push(i),c.area+=i.area,null!=i.z&&(u(c,i.z?o.dx:o.dy,o,!a.length),c.length=c.area=0);r.forEach(e)}}function r(n,t){for(var e,r=n.area,u=0,i=1/0,o=-1,a=n.length;++oe&&(i=e),e>u&&(u=e));return r*=r,t*=t,r?Math.max(t*u*p/r,r/(t*i*p)):1/0}function u(n,t,e,r){var u,i=-1,o=n.length,a=e.x,s=e.y,l=t?c(n.area/t):0;if(t==e.dx){for((r||l>e.dy)&&(l=e.dy);++ie.dx)&&(l=e.dx);++ie&&(t=1),1>e&&(n=0),function(){var e,r,u;do e=2*Math.random()-1,r=2*Math.random()-1,u=e*e+r*r;while(!u||u>1);return n+t*e*Math.sqrt(-2*Math.log(u)/u)}},logNormal:function(){var n=Zo.random.normal.apply(Zo,arguments);return function(){return Math.exp(n())}},bates:function(n){var t=Zo.random.irwinHall(n);return function(){return t()/n}},irwinHall:function(n){return function(){for(var t=0,e=0;n>e;e++)t+=Math.random();return t}}},Zo.scale={};var ss={floor:wt,ceil:wt};Zo.scale.linear=function(){return Ui([0,1],[0,1],hu,!1)};var ls={s:1,g:1,p:1,r:1,e:1};Zo.scale.log=function(){return Vi(Zo.scale.linear().domain([0,1]),10,!0,[1,10])};var fs=Zo.format(".0e"),hs={floor:function(n){return-Math.ceil(-n)},ceil:function(n){return-Math.floor(-n)}};Zo.scale.pow=function(){return Xi(Zo.scale.linear(),1,[0,1])},Zo.scale.sqrt=function(){return Zo.scale.pow().exponent(.5)},Zo.scale.ordinal=function(){return Bi([],{t:"range",a:[[]]})},Zo.scale.category10=function(){return Zo.scale.ordinal().range(gs)},Zo.scale.category20=function(){return Zo.scale.ordinal().range(ps)},Zo.scale.category20b=function(){return Zo.scale.ordinal().range(vs)},Zo.scale.category20c=function(){return Zo.scale.ordinal().range(ds)};var gs=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(vt),ps=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(vt),vs=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(vt),ds=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(vt);Zo.scale.quantile=function(){return Wi([],[])},Zo.scale.quantize=function(){return Ji(0,1,[0,1])},Zo.scale.threshold=function(){return Gi([.5],[0,1])},Zo.scale.identity=function(){return Ki([0,1])},Zo.svg={},Zo.svg.arc=function(){function n(){var n=t.apply(this,arguments),i=e.apply(this,arguments),o=r.apply(this,arguments)+ms,a=u.apply(this,arguments)+ms,c=(o>a&&(c=o,o=a,a=c),a-o),s=ba>c?"0":"1",l=Math.cos(o),f=Math.sin(o),h=Math.cos(a),g=Math.sin(a); - return c>=ys?n?"M0,"+i+"A"+i+","+i+" 0 1,1 0,"+-i+"A"+i+","+i+" 0 1,1 0,"+i+"M0,"+n+"A"+n+","+n+" 0 1,0 0,"+-n+"A"+n+","+n+" 0 1,0 0,"+n+"Z":"M0,"+i+"A"+i+","+i+" 0 1,1 0,"+-i+"A"+i+","+i+" 0 1,1 0,"+i+"Z":n?"M"+i*l+","+i*f+"A"+i+","+i+" 0 "+s+",1 "+i*h+","+i*g+"L"+n*h+","+n*g+"A"+n+","+n+" 0 "+s+",0 "+n*l+","+n*f+"Z":"M"+i*l+","+i*f+"A"+i+","+i+" 0 "+s+",1 "+i*h+","+i*g+"L0,0"+"Z"}var t=Qi,e=no,r=to,u=eo;return n.innerRadius=function(e){return arguments.length?(t=bt(e),n):t},n.outerRadius=function(t){return arguments.length?(e=bt(t),n):e},n.startAngle=function(t){return arguments.length?(r=bt(t),n):r},n.endAngle=function(t){return arguments.length?(u=bt(t),n):u},n.centroid=function(){var n=(t.apply(this,arguments)+e.apply(this,arguments))/2,i=(r.apply(this,arguments)+u.apply(this,arguments))/2+ms;return[Math.cos(i)*n,Math.sin(i)*n]},n};var ms=-Sa,ys=wa-ka;Zo.svg.line=function(){return ro(wt)};var xs=Zo.map({linear:uo,"linear-closed":io,step:oo,"step-before":ao,"step-after":co,basis:po,"basis-open":vo,"basis-closed":mo,bundle:yo,cardinal:fo,"cardinal-open":so,"cardinal-closed":lo,monotone:So});xs.forEach(function(n,t){t.key=n,t.closed=/-closed$/.test(n)});var Ms=[0,2/3,1/3,0],_s=[0,1/3,2/3,0],bs=[0,1/6,2/3,1/6];Zo.svg.line.radial=function(){var n=ro(ko);return n.radius=n.x,delete n.x,n.angle=n.y,delete n.y,n},ao.reverse=co,co.reverse=ao,Zo.svg.area=function(){return Eo(wt)},Zo.svg.area.radial=function(){var n=Eo(ko);return n.radius=n.x,delete n.x,n.innerRadius=n.x0,delete n.x0,n.outerRadius=n.x1,delete n.x1,n.angle=n.y,delete n.y,n.startAngle=n.y0,delete n.y0,n.endAngle=n.y1,delete n.y1,n},Zo.svg.chord=function(){function n(n,a){var c=t(this,i,n,a),s=t(this,o,n,a);return"M"+c.p0+r(c.r,c.p1,c.a1-c.a0)+(e(c,s)?u(c.r,c.p1,c.r,c.p0):u(c.r,c.p1,s.r,s.p0)+r(s.r,s.p1,s.a1-s.a0)+u(s.r,s.p1,c.r,c.p0))+"Z"}function t(n,t,e,r){var u=t.call(n,e,r),i=a.call(n,u,r),o=c.call(n,u,r)+ms,l=s.call(n,u,r)+ms;return{r:i,a0:o,a1:l,p0:[i*Math.cos(o),i*Math.sin(o)],p1:[i*Math.cos(l),i*Math.sin(l)]}}function e(n,t){return n.a0==t.a0&&n.a1==t.a1}function r(n,t,e){return"A"+n+","+n+" 0 "+ +(e>ba)+",1 "+t}function u(n,t,e,r){return"Q 0,0 "+r}var i=gr,o=pr,a=Ao,c=to,s=eo;return n.radius=function(t){return arguments.length?(a=bt(t),n):a},n.source=function(t){return arguments.length?(i=bt(t),n):i},n.target=function(t){return arguments.length?(o=bt(t),n):o},n.startAngle=function(t){return arguments.length?(c=bt(t),n):c},n.endAngle=function(t){return arguments.length?(s=bt(t),n):s},n},Zo.svg.diagonal=function(){function n(n,u){var i=t.call(this,n,u),o=e.call(this,n,u),a=(i.y+o.y)/2,c=[i,{x:i.x,y:a},{x:o.x,y:a},o];return c=c.map(r),"M"+c[0]+"C"+c[1]+" "+c[2]+" "+c[3]}var t=gr,e=pr,r=Co;return n.source=function(e){return arguments.length?(t=bt(e),n):t},n.target=function(t){return arguments.length?(e=bt(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},Zo.svg.diagonal.radial=function(){var n=Zo.svg.diagonal(),t=Co,e=n.projection;return n.projection=function(n){return arguments.length?e(No(t=n)):t},n},Zo.svg.symbol=function(){function n(n,r){return(ws.get(t.call(this,n,r))||To)(e.call(this,n,r))}var t=Lo,e=zo;return n.type=function(e){return arguments.length?(t=bt(e),n):t},n.size=function(t){return arguments.length?(e=bt(t),n):e},n};var ws=Zo.map({circle:To,cross:function(n){var t=Math.sqrt(n/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(n){var t=Math.sqrt(n/(2*As)),e=t*As;return"M0,"+-t+"L"+e+",0"+" 0,"+t+" "+-e+",0"+"Z"},square:function(n){var t=Math.sqrt(n)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(n){var t=Math.sqrt(n/Es),e=t*Es/2;return"M0,"+e+"L"+t+","+-e+" "+-t+","+-e+"Z"},"triangle-up":function(n){var t=Math.sqrt(n/Es),e=t*Es/2;return"M0,"+-e+"L"+t+","+e+" "+-t+","+e+"Z"}});Zo.svg.symbolTypes=ws.keys();var Ss,ks,Es=Math.sqrt(3),As=Math.tan(30*Aa),Cs=[],Ns=0;Cs.call=pa.call,Cs.empty=pa.empty,Cs.node=pa.node,Cs.size=pa.size,Zo.transition=function(n){return arguments.length?Ss?n.transition():n:ma.transition()},Zo.transition.prototype=Cs,Cs.select=function(n){var t,e,r,u=this.id,i=[];n=b(n);for(var o=-1,a=this.length;++oi;i++){u.push(t=[]);for(var e=this[i],a=0,c=e.length;c>a;a++)(r=e[a])&&n.call(r,r.__data__,a,i)&&t.push(r)}return qo(u,this.id)},Cs.tween=function(n,t){var e=this.id;return arguments.length<2?this.node().__transition__[e].tween.get(n):P(this,null==t?function(t){t.__transition__[e].tween.remove(n)}:function(r){r.__transition__[e].tween.set(n,t)})},Cs.attr=function(n,t){function e(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function u(n){return null==n?e:(n+="",function(){var t,e=this.getAttribute(a);return e!==n&&(t=o(e,n),function(n){this.setAttribute(a,t(n))})})}function i(n){return null==n?r:(n+="",function(){var t,e=this.getAttributeNS(a.space,a.local);return e!==n&&(t=o(e,n),function(n){this.setAttributeNS(a.space,a.local,t(n))})})}if(arguments.length<2){for(t in n)this.attr(t,n[t]);return this}var o="transform"==n?Du:hu,a=Zo.ns.qualify(n);return Ro(this,"attr."+n,t,a.local?i:u)},Cs.attrTween=function(n,t){function e(n,e){var r=t.call(this,n,e,this.getAttribute(u));return r&&function(n){this.setAttribute(u,r(n))}}function r(n,e){var r=t.call(this,n,e,this.getAttributeNS(u.space,u.local));return r&&function(n){this.setAttributeNS(u.space,u.local,r(n))}}var u=Zo.ns.qualify(n);return this.tween("attr."+n,u.local?r:e)},Cs.style=function(n,t,e){function r(){this.style.removeProperty(n)}function u(t){return null==t?r:(t+="",function(){var r,u=Wo.getComputedStyle(this,null).getPropertyValue(n);return u!==t&&(r=hu(u,t),function(t){this.style.setProperty(n,r(t),e)})})}var i=arguments.length;if(3>i){if("string"!=typeof n){2>i&&(t="");for(e in n)this.style(e,n[e],t);return this}e=""}return Ro(this,"style."+n,t,u)},Cs.styleTween=function(n,t,e){function r(r,u){var i=t.call(this,r,u,Wo.getComputedStyle(this,null).getPropertyValue(n));return i&&function(t){this.style.setProperty(n,i(t),e)}}return arguments.length<3&&(e=""),this.tween("style."+n,r)},Cs.text=function(n){return Ro(this,"text",n,Do)},Cs.remove=function(){return this.each("end.transition",function(){var n;this.__transition__.count<2&&(n=this.parentNode)&&n.removeChild(this)})},Cs.ease=function(n){var t=this.id;return arguments.length<1?this.node().__transition__[t].ease:("function"!=typeof n&&(n=Zo.ease.apply(Zo,arguments)),P(this,function(e){e.__transition__[t].ease=n}))},Cs.delay=function(n){var t=this.id;return arguments.length<1?this.node().__transition__[t].delay:P(this,"function"==typeof n?function(e,r,u){e.__transition__[t].delay=+n.call(e,e.__data__,r,u)}:(n=+n,function(e){e.__transition__[t].delay=n}))},Cs.duration=function(n){var t=this.id;return arguments.length<1?this.node().__transition__[t].duration:P(this,"function"==typeof n?function(e,r,u){e.__transition__[t].duration=Math.max(1,n.call(e,e.__data__,r,u))}:(n=Math.max(1,n),function(e){e.__transition__[t].duration=n}))},Cs.each=function(n,t){var e=this.id;if(arguments.length<2){var r=ks,u=Ss;Ss=e,P(this,function(t,r,u){ks=t.__transition__[e],n.call(t,t.__data__,r,u)}),ks=r,Ss=u}else P(this,function(r){var u=r.__transition__[e];(u.event||(u.event=Zo.dispatch("start","end"))).on(n,t)});return this},Cs.transition=function(){for(var n,t,e,r,u=this.id,i=++Ns,o=[],a=0,c=this.length;c>a;a++){o.push(n=[]);for(var t=this[a],s=0,l=t.length;l>s;s++)(e=t[s])&&(r=Object.create(e.__transition__[u]),r.delay+=r.duration,Po(e,s,i,r)),n.push(e)}return qo(o,i)},Zo.svg.axis=function(){function n(n){n.each(function(){var n,s=Zo.select(this),l=this.__chart__||e,f=this.__chart__=e.copy(),h=null==c?f.ticks?f.ticks.apply(f,a):f.domain():c,g=null==t?f.tickFormat?f.tickFormat.apply(f,a):wt:t,p=s.selectAll(".tick").data(h,f),v=p.enter().insert("g",".domain").attr("class","tick").style("opacity",ka),d=Zo.transition(p.exit()).style("opacity",ka).remove(),m=Zo.transition(p.order()).style("opacity",1),y=Ti(f),x=s.selectAll(".domain").data([0]),M=(x.enter().append("path").attr("class","domain"),Zo.transition(x));v.append("line"),v.append("text");var _=v.select("line"),b=m.select("line"),w=p.select("text").text(g),S=v.select("text"),k=m.select("text");switch(r){case"bottom":n=Uo,_.attr("y2",u),S.attr("y",Math.max(u,0)+o),b.attr("x2",0).attr("y2",u),k.attr("x",0).attr("y",Math.max(u,0)+o),w.attr("dy",".71em").style("text-anchor","middle"),M.attr("d","M"+y[0]+","+i+"V0H"+y[1]+"V"+i);break;case"top":n=Uo,_.attr("y2",-u),S.attr("y",-(Math.max(u,0)+o)),b.attr("x2",0).attr("y2",-u),k.attr("x",0).attr("y",-(Math.max(u,0)+o)),w.attr("dy","0em").style("text-anchor","middle"),M.attr("d","M"+y[0]+","+-i+"V0H"+y[1]+"V"+-i);break;case"left":n=jo,_.attr("x2",-u),S.attr("x",-(Math.max(u,0)+o)),b.attr("x2",-u).attr("y2",0),k.attr("x",-(Math.max(u,0)+o)).attr("y",0),w.attr("dy",".32em").style("text-anchor","end"),M.attr("d","M"+-i+","+y[0]+"H0V"+y[1]+"H"+-i);break;case"right":n=jo,_.attr("x2",u),S.attr("x",Math.max(u,0)+o),b.attr("x2",u).attr("y2",0),k.attr("x",Math.max(u,0)+o).attr("y",0),w.attr("dy",".32em").style("text-anchor","start"),M.attr("d","M"+i+","+y[0]+"H0V"+y[1]+"H"+i)}if(f.rangeBand){var E=f,A=E.rangeBand()/2;l=f=function(n){return E(n)+A}}else l.rangeBand?l=f:d.call(n,f);v.call(n,l),m.call(n,f)})}var t,e=Zo.scale.linear(),r=zs,u=6,i=6,o=3,a=[10],c=null;return n.scale=function(t){return arguments.length?(e=t,n):e},n.orient=function(t){return arguments.length?(r=t in Ls?t+"":zs,n):r},n.ticks=function(){return arguments.length?(a=arguments,n):a},n.tickValues=function(t){return arguments.length?(c=t,n):c},n.tickFormat=function(e){return arguments.length?(t=e,n):t},n.tickSize=function(t){var e=arguments.length;return e?(u=+t,i=+arguments[e-1],n):u},n.innerTickSize=function(t){return arguments.length?(u=+t,n):u},n.outerTickSize=function(t){return arguments.length?(i=+t,n):i},n.tickPadding=function(t){return arguments.length?(o=+t,n):o},n.tickSubdivide=function(){return arguments.length&&n},n};var zs="bottom",Ls={top:1,right:1,bottom:1,left:1};Zo.svg.brush=function(){function n(i){i.each(function(){var i=Zo.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",u).on("touchstart.brush",u),o=i.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),i.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=i.selectAll(".resize").data(p,wt);a.exit().remove(),a.enter().append("g").attr("class",function(n){return"resize "+n}).style("cursor",function(n){return Ts[n]}).append("rect").attr("x",function(n){return/[ew]$/.test(n)?-3:null}).attr("y",function(n){return/^[ns]/.test(n)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),a.style("display",n.empty()?"none":null);var l,f=Zo.transition(i),h=Zo.transition(o);c&&(l=Ti(c),h.attr("x",l[0]).attr("width",l[1]-l[0]),e(f)),s&&(l=Ti(s),h.attr("y",l[0]).attr("height",l[1]-l[0]),r(f)),t(f)})}function t(n){n.selectAll(".resize").attr("transform",function(n){return"translate("+l[+/e$/.test(n)]+","+f[+/^s/.test(n)]+")"})}function e(n){n.select(".extent").attr("x",l[0]),n.selectAll(".extent,.n>rect,.s>rect").attr("width",l[1]-l[0])}function r(n){n.select(".extent").attr("y",f[0]),n.selectAll(".extent,.e>rect,.w>rect").attr("height",f[1]-f[0])}function u(){function u(){32==Zo.event.keyCode&&(C||(x=null,z[0]-=l[1],z[1]-=f[1],C=2),y())}function p(){32==Zo.event.keyCode&&2==C&&(z[0]+=l[1],z[1]+=f[1],C=0,y())}function v(){var n=Zo.mouse(_),u=!1;M&&(n[0]+=M[0],n[1]+=M[1]),C||(Zo.event.altKey?(x||(x=[(l[0]+l[1])/2,(f[0]+f[1])/2]),z[0]=l[+(n[0]p?(u=r,r=p):u=p),v[0]!=r||v[1]!=u?(e?o=null:i=null,v[0]=r,v[1]=u,!0):void 0}function m(){v(),S.style("pointer-events","all").selectAll(".resize").style("display",n.empty()?"none":null),Zo.select("body").style("cursor",null),L.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),N(),w({type:"brushend"})}var x,M,_=this,b=Zo.select(Zo.event.target),w=a.of(_,arguments),S=Zo.select(_),k=b.datum(),E=!/^(n|s)$/.test(k)&&c,A=!/^(e|w)$/.test(k)&&s,C=b.classed("extent"),N=I(),z=Zo.mouse(_),L=Zo.select(Wo).on("keydown.brush",u).on("keyup.brush",p);if(Zo.event.changedTouches?L.on("touchmove.brush",v).on("touchend.brush",m):L.on("mousemove.brush",v).on("mouseup.brush",m),S.interrupt().selectAll("*").interrupt(),C)z[0]=l[0]-z[0],z[1]=f[0]-z[1];else if(k){var T=+/w$/.test(k),q=+/^n/.test(k);M=[l[1-T]-z[0],f[1-q]-z[1]],z[0]=l[T],z[1]=f[q]}else Zo.event.altKey&&(x=z.slice());S.style("pointer-events","none").selectAll(".resize").style("display",null),Zo.select("body").style("cursor",b.style("cursor")),w({type:"brushstart"}),v()}var i,o,a=M(n,"brushstart","brush","brushend"),c=null,s=null,l=[0,0],f=[0,0],h=!0,g=!0,p=qs[0];return n.event=function(n){n.each(function(){var n=a.of(this,arguments),t={x:l,y:f,i:i,j:o},e=this.__chart__||t;this.__chart__=t,Ss?Zo.select(this).transition().each("start.brush",function(){i=e.i,o=e.j,l=e.x,f=e.y,n({type:"brushstart"})}).tween("brush:brush",function(){var e=gu(l,t.x),r=gu(f,t.y);return i=o=null,function(u){l=t.x=e(u),f=t.y=r(u),n({type:"brush",mode:"resize"})}}).each("end.brush",function(){i=t.i,o=t.j,n({type:"brush",mode:"resize"}),n({type:"brushend"})}):(n({type:"brushstart"}),n({type:"brush",mode:"resize"}),n({type:"brushend"}))})},n.x=function(t){return arguments.length?(c=t,p=qs[!c<<1|!s],n):c},n.y=function(t){return arguments.length?(s=t,p=qs[!c<<1|!s],n):s},n.clamp=function(t){return arguments.length?(c&&s?(h=!!t[0],g=!!t[1]):c?h=!!t:s&&(g=!!t),n):c&&s?[h,g]:c?h:s?g:null},n.extent=function(t){var e,r,u,a,h;return arguments.length?(c&&(e=t[0],r=t[1],s&&(e=e[0],r=r[0]),i=[e,r],c.invert&&(e=c(e),r=c(r)),e>r&&(h=e,e=r,r=h),(e!=l[0]||r!=l[1])&&(l=[e,r])),s&&(u=t[0],a=t[1],c&&(u=u[1],a=a[1]),o=[u,a],s.invert&&(u=s(u),a=s(a)),u>a&&(h=u,u=a,a=h),(u!=f[0]||a!=f[1])&&(f=[u,a])),n):(c&&(i?(e=i[0],r=i[1]):(e=l[0],r=l[1],c.invert&&(e=c.invert(e),r=c.invert(r)),e>r&&(h=e,e=r,r=h))),s&&(o?(u=o[0],a=o[1]):(u=f[0],a=f[1],s.invert&&(u=s.invert(u),a=s.invert(a)),u>a&&(h=u,u=a,a=h))),c&&s?[[e,u],[r,a]]:c?[e,r]:s&&[u,a])},n.clear=function(){return n.empty()||(l=[0,0],f=[0,0],i=o=null),n},n.empty=function(){return!!c&&l[0]==l[1]||!!s&&f[0]==f[1]},Zo.rebind(n,a,"on")};var Ts={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},qs=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Rs=Qa.format=ic.timeFormat,Ds=Rs.utc,Ps=Ds("%Y-%m-%dT%H:%M:%S.%LZ");Rs.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ho:Ps,Ho.parse=function(n){var t=new Date(n);return isNaN(t)?null:t},Ho.toString=Ps.toString,Qa.second=Dt(function(n){return new nc(1e3*Math.floor(n/1e3))},function(n,t){n.setTime(n.getTime()+1e3*Math.floor(t))},function(n){return n.getSeconds()}),Qa.seconds=Qa.second.range,Qa.seconds.utc=Qa.second.utc.range,Qa.minute=Dt(function(n){return new nc(6e4*Math.floor(n/6e4))},function(n,t){n.setTime(n.getTime()+6e4*Math.floor(t))},function(n){return n.getMinutes()}),Qa.minutes=Qa.minute.range,Qa.minutes.utc=Qa.minute.utc.range,Qa.hour=Dt(function(n){var t=n.getTimezoneOffset()/60;return new nc(36e5*(Math.floor(n/36e5-t)+t))},function(n,t){n.setTime(n.getTime()+36e5*Math.floor(t))},function(n){return n.getHours()}),Qa.hours=Qa.hour.range,Qa.hours.utc=Qa.hour.utc.range,Qa.month=Dt(function(n){return n=Qa.day(n),n.setDate(1),n},function(n,t){n.setMonth(n.getMonth()+t)},function(n){return n.getMonth()}),Qa.months=Qa.month.range,Qa.months.utc=Qa.month.utc.range;var Us=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],js=[[Qa.second,1],[Qa.second,5],[Qa.second,15],[Qa.second,30],[Qa.minute,1],[Qa.minute,5],[Qa.minute,15],[Qa.minute,30],[Qa.hour,1],[Qa.hour,3],[Qa.hour,6],[Qa.hour,12],[Qa.day,1],[Qa.day,2],[Qa.week,1],[Qa.month,1],[Qa.month,3],[Qa.year,1]],Hs=Rs.multi([[".%L",function(n){return n.getMilliseconds()}],[":%S",function(n){return n.getSeconds()}],["%I:%M",function(n){return n.getMinutes()}],["%I %p",function(n){return n.getHours()}],["%a %d",function(n){return n.getDay()&&1!=n.getDate()}],["%b %d",function(n){return 1!=n.getDate()}],["%B",function(n){return n.getMonth()}],["%Y",we]]),Fs={range:function(n,t,e){return Zo.range(Math.ceil(n/e)*e,+t,e).map(Oo)},floor:wt,ceil:wt};js.year=Qa.year,Qa.scale=function(){return Fo(Zo.scale.linear(),js,Hs)};var Os=js.map(function(n){return[n[0].utc,n[1]]}),Ys=Ds.multi([[".%L",function(n){return n.getUTCMilliseconds()}],[":%S",function(n){return n.getUTCSeconds()}],["%I:%M",function(n){return n.getUTCMinutes()}],["%I %p",function(n){return n.getUTCHours()}],["%a %d",function(n){return n.getUTCDay()&&1!=n.getUTCDate()}],["%b %d",function(n){return 1!=n.getUTCDate()}],["%B",function(n){return n.getUTCMonth()}],["%Y",we]]);Os.year=Qa.year.utc,Qa.scale.utc=function(){return Fo(Zo.scale.linear(),Os,Ys)},Zo.text=St(function(n){return n.responseText}),Zo.json=function(n,t){return kt(n,"application/json",Yo,t)},Zo.html=function(n,t){return kt(n,"text/html",Io,t)},Zo.xml=St(function(n){return n.responseXML}),"function"==typeof define&&define.amd?define(Zo):"object"==typeof module&&module.exports&&(module.exports=Zo),this.d3=Zo}(); \ No newline at end of file diff --git a/framework/src/onos/utils/jdvue/src/main/resources/org/onlab/jdvue/index.html b/framework/src/onos/utils/jdvue/src/main/resources/org/onlab/jdvue/index.html deleted file mode 100644 index be0b581c..00000000 --- a/framework/src/onos/utils/jdvue/src/main/resources/org/onlab/jdvue/index.html +++ /dev/null @@ -1,371 +0,0 @@ - - - - - TITLE_PLACEHOLDER - - - -

-
Project TITLE_PLACEHOLDER
- - - - - - - - - - - - - - - - - -
Sources:
Packages:
Cyclic Segments:
Cycles:
-

-
Highlight cycles
-
-
-
-
Package Details
- - - - - - - - - - - - - - - - - -
Sources:
Dependents:
Cyclic Segments:
Cycles:
-
- - - diff --git a/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/CatalogTest.java b/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/CatalogTest.java deleted file mode 100644 index b792abcc..00000000 --- a/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/CatalogTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - -import org.junit.Test; -import org.onlab.jdvue.Catalog; -import org.onlab.jdvue.JavaPackage; -import org.onlab.jdvue.JavaSource; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * Unit test for the source catalog. - * - * @author Thomas Vachuska - */ -public class CatalogTest { - - @Test - public void basics() throws IOException { - Catalog cat = new Catalog(); - cat.load("src/test/resources/catalog.db"); - cat.analyze(); - - assertEquals("incorrect package count", 12, cat.getPackages().size()); - assertEquals("incorrect source count", 14, cat.getSources().size()); - - JavaPackage pkg = cat.getPackage("k"); - assertNotNull("package should be found", pkg); - - JavaSource src = cat.getSource("k.K"); - assertNotNull("source should be found", src); - - assertEquals("incorrect package source count", 1, pkg.getSources().size()); - assertEquals("incorrect package dependency count", 1, pkg.getDependencies().size()); - assertEquals("incorrect package cycle count", 3, cat.getPackageCycles(pkg).size()); - - assertEquals("incorrect segment count", 11, cat.getCycleSegments().size()); - assertEquals("incorrect cycle count", 5, cat.getCycles().size()); - } - -} diff --git a/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyCycleTest.java b/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyCycleTest.java deleted file mode 100644 index 895c713f..00000000 --- a/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyCycleTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - -import org.junit.Test; -import org.onlab.jdvue.DependencyCycle; -import org.onlab.jdvue.JavaPackage; - -import java.util.Arrays; - -import static org.junit.Assert.*; - -/** - * Unit test for the dependency cycle entity. - * - * @author Thomas Vachuska - */ -public class DependencyCycleTest { - - @Test - public void normalize() { - JavaPackage x = new JavaPackage("x"); - JavaPackage y = new JavaPackage("y"); - JavaPackage z = new JavaPackage("z"); - - DependencyCycle a = new DependencyCycle(Arrays.asList(new JavaPackage[] {x, y, z}), x); - DependencyCycle b = new DependencyCycle(Arrays.asList(new JavaPackage[] {y, z, x}), y); - DependencyCycle c = new DependencyCycle(Arrays.asList(new JavaPackage[] {z, x, y}), z); - - assertEquals("incorrect normalization", a, b); - assertEquals("incorrect normalization", a, c); - } - - @Test - public void testToString() { - JavaPackage x = new JavaPackage("x"); - JavaPackage y = new JavaPackage("y"); - JavaPackage z = new JavaPackage("z"); - - DependencyCycle a = new DependencyCycle(Arrays.asList(new JavaPackage[] {x, y, z}), x); - assertEquals("incorrect toString", "[x, y, z]", a.toShortString()); - assertEquals("incorrect toString", - "DependencyCycle{cycle=[" + - "JavaPackage{name=x, sources=0, dependencies=0}, " + - "JavaPackage{name=y, sources=0, dependencies=0}, " + - "JavaPackage{name=z, sources=0, dependencies=0}]}", - a.toString()); - } -} diff --git a/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyTest.java b/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyTest.java deleted file mode 100644 index 94740dae..00000000 --- a/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - -import com.google.common.testing.EqualsTester; -import org.junit.Test; -import org.onlab.jdvue.Dependency; -import org.onlab.jdvue.JavaPackage; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -/** - * Unit test for the dependency entity. - * - * @author Thomas Vachuska - */ -public class DependencyTest { - - @Test - public void basics() { - JavaPackage x = new JavaPackage("x"); - JavaPackage y = new JavaPackage("y"); - - new EqualsTester() - .addEqualityGroup(new Dependency(x, y), new Dependency(x, y)) - .addEqualityGroup(new Dependency(y, x), new Dependency(y, x)) - .testEquals(); - } - -} diff --git a/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyViewerTest.java b/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyViewerTest.java deleted file mode 100644 index 0937c068..00000000 --- a/framework/src/onos/utils/jdvue/src/test/java/org/onlab/jdvue/DependencyViewerTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.jdvue; - -import org.junit.Test; -import org.onlab.jdvue.DependencyViewer; - -import java.io.FileInputStream; -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.onlab.jdvue.DependencyViewer.slurp; - -/** - * Unit test for the dependency viewer. - * - * @author Thomas Vachuska - */ -public class DependencyViewerTest { - - @Test - public void basics() throws IOException { - DependencyViewer.main(new String[]{"src/test/resources/catalog"}); - - String expected = slurp(new FileInputStream("src/test/resources/expected.html")); - String actual = slurp(new FileInputStream("src/test/resources/catalog.html")); - - // FIXME: add more manageable assertions here -// assertEquals("incorrect html", expected, actual); - } - -} diff --git a/framework/src/onos/utils/jdvue/src/test/resources/catalog.db b/framework/src/onos/utils/jdvue/src/test/resources/catalog.db deleted file mode 100644 index 156eeec9..00000000 --- a/framework/src/onos/utils/jdvue/src/test/resources/catalog.db +++ /dev/null @@ -1,33 +0,0 @@ -src/main/java/a/A.java:package a; -src/main/java/a/A.java:import b.B; -src/main/java/a/A2.java:package a; -src/main/java/a/A2.java:import c.C; -src/main/java/b/B.java:package b; -src/main/java/b/B.java:import c.C; -src/main/java/c/C.java:package c; - -src/main/java/x/X.java:package x; -src/main/java/x/X.java:import y.Y; -src/main/java/y/Y.java:package y; -src/main/java/y/Y.java:import z.Z; -src/main/java/z/Z.java:package z; -src/main/java/z/Z.java:import x.X; - -src/main/java/u/U.java:package u; -src/main/java/u/U.java:import v.V; -src/main/java/u/U2.java:package u; -src/main/java/u/U2.java:import v.V; -src/main/java/v/V.java:package v; -src/main/java/v/V.java:import u.U; - -src/main/java/k/K.java:package k; -src/main/java/k/K.java:import l.L; -src/main/java/l/L.java:package l; -src/main/java/l/L.java:import k.K; -src/main/java/l/L.java:import m.M; -src/main/java/l/L.java:import n.N; -src/main/java/m/M.java:package m; -src/main/java/m/M.java:import n.N; -src/main/java/n/N.java:package n; -src/main/java/n/N.java:import k.K; - diff --git a/framework/src/onos/utils/jdvue/src/test/resources/catalog.html b/framework/src/onos/utils/jdvue/src/test/resources/catalog.html deleted file mode 100644 index f3813596..00000000 --- a/framework/src/onos/utils/jdvue/src/test/resources/catalog.html +++ /dev/null @@ -1,376 +0,0 @@ - - - - - src/test/resources/catalog - - - -
-
Project src/test/resources/catalog
- - - - - - - - - - - - - - - - - -
Sources:
Packages:
Cyclic Segments:
Cycles:
-

-
Highlight cycles
-
-
-
-
Package Details
- - - - - - - - - - - - - - - - - -
Sources:
Dependents:
Cyclic Segments:
Cycles:
-
- - - diff --git a/framework/src/onos/utils/jdvue/src/test/resources/expected.html b/framework/src/onos/utils/jdvue/src/test/resources/expected.html deleted file mode 100644 index a98573e9..00000000 --- a/framework/src/onos/utils/jdvue/src/test/resources/expected.html +++ /dev/null @@ -1,376 +0,0 @@ - - - - - src/test/resources/catalog - - - -
-
Project src/test/resources/catalog
- - - - - - - - - - - - - - - - - -
Sources:
Packages:
Cyclic Segments:
Cycles:
-

-
Highlight cycles
-
-
-
-
Package Details
- - - - - - - - - - - - - - - - - -
Sources:
Dependents:
Cyclic Segments:
Cycles:
-
- - - diff --git a/framework/src/onos/utils/jnc/pom.xml b/framework/src/onos/utils/jnc/pom.xml deleted file mode 100644 index 3fd83b3d..00000000 --- a/framework/src/onos/utils/jnc/pom.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - - 4.0.0 - - - org.onosproject - onlab-utils - 1.4.0-rc1 - ../pom.xml - - - onlab-jnc-osgi - bundle - - TailF JNC and Ganymed SSH2 packaged as OSGi bundle - - - - ch.ethz.ganymed - ganymed-ssh2 - 262 - - - - - org.onosproject - jnc - 1.0 - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - - - com.google.guava:guava - - ** - - - - - - - package - - shade - - - - - - org.apache.felix - maven-bundle-plugin - - - - com.tailf.jnc, - ch.ethz.ssh2, - ch.ethz.ssh2.auth, - ch.ethz.ssh2.channel, - ch.ethz.ssh2.crypto, - ch.ethz.ssh2.crypto.cipher, - ch.ethz.ssh2.crypto.dh, - ch.ethz.ssh2.crypto.digest, - ch.ethz.ssh2.log, - ch.ethz.ssh2.packets, - ch.ethz.ssh2.server, - ch.ethz.ssh2.sftp, - ch.ethz.ssh2.signature, - ch.ethz.ssh2.transport, - ch.ethz.ssh2.util - - - - - - - - diff --git a/framework/src/onos/utils/junit/pom.xml b/framework/src/onos/utils/junit/pom.xml deleted file mode 100644 index da99f46d..00000000 --- a/framework/src/onos/utils/junit/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - 4.0.0 - - - org.onosproject - onlab-utils - 1.4.0-rc1 - ../pom.xml - - - onlab-junit - bundle - - ON.Lab JUnit test utilities - - - - junit - junit - compile - - - com.google.guava - guava-testlib - compile - - - org.hamcrest - hamcrest-core - compile - - - org.hamcrest - hamcrest-library - compile - - - - diff --git a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/ExceptionTest.java b/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/ExceptionTest.java deleted file mode 100644 index 09b3fe37..00000000 --- a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/ExceptionTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.junit; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; - -/** - * Base for exception tests. - */ -public abstract class ExceptionTest { - - protected static final Throwable CAUSE = new RuntimeException("boom"); - protected static final String MESSAGE = "Uh oh.... boom"; - - protected abstract Exception getDefault(); - protected abstract Exception getWithMessage(); - protected abstract Exception getWithMessageAndCause(); - - @Test - public void noMessageNoCause() { - Exception e = getDefault(); - assertEquals("incorrect message", null, e.getMessage()); - assertEquals("incorrect cause", null, e.getCause()); - } - - @Test - public void withMessage() { - Exception e = getWithMessage(); - assertEquals("incorrect message", MESSAGE, e.getMessage()); - assertEquals("incorrect cause", null, e.getCause()); - } - - @Test - public void withCause() { - Exception e = getWithMessageAndCause(); - assertEquals("incorrect message", MESSAGE, e.getMessage()); - assertSame("incorrect cause", CAUSE, e.getCause()); - } -} diff --git a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/ImmutableClassChecker.java b/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/ImmutableClassChecker.java deleted file mode 100644 index 80aa2cb1..00000000 --- a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/ImmutableClassChecker.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.junit; - -import org.hamcrest.Description; -import org.hamcrest.StringDescription; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * Hamcrest style class for verifying that a class follows the - * accepted rules for immutable classes. - * - * The rules that are enforced for immutable classes: - * - the class must be declared final - * - all data members of the class must be declared private and final - * - the class must not define any setter methods - */ - -public class ImmutableClassChecker { - - private String failureReason = ""; - - /** - * Method to determine if a given class is a properly specified - * immutable class. - * - * @param clazz the class to check - * @return true if the given class is a properly specified immutable class. - */ - private boolean isImmutableClass(Class clazz, boolean allowNonFinalClass) { - // class must be declared final - if (!allowNonFinalClass && !Modifier.isFinal(clazz.getModifiers())) { - failureReason = "a class that is not final"; - return false; - } - - // class must have only final and private data members - for (final Field field : clazz.getDeclaredFields()) { - if (field.getName().startsWith("_") || - field.getName().startsWith("$")) { - // eclipse generated code may insert switch table - ignore - // cobertura sticks these fields into classes - ignore them - continue; - } - if (!Modifier.isFinal(field.getModifiers())) { - failureReason = "a field named '" + field.getName() + - "' that is not final"; - return false; - } - if (!Modifier.isPrivate(field.getModifiers())) { - // - // NOTE: We relax the recommended rules for defining immutable - // objects and allow "static final" fields that are not - // private. The "final" check was already done above so we - // don't repeat it here. - // - if (!Modifier.isStatic(field.getModifiers())) { - failureReason = "a field named '" + field.getName() + - "' that is not private and is not static"; - return false; - } - } - } - - // class must not define any setters - for (final Method method : clazz.getMethods()) { - if (method.getDeclaringClass().equals(clazz)) { - if (method.getName().startsWith("set")) { - failureReason = "a class with a setter named '" + method.getName() + "'"; - return false; - } - } - } - - return true; - } - - /** - * Describe why an error was reported. Uses Hamcrest style Description - * interfaces. - * - * @param description the Description object to use for reporting the - * mismatch - */ - public void describeMismatch(Description description) { - description.appendText(failureReason); - } - - /** - * Describe the source object that caused an error, using a Hamcrest - * Matcher style interface. In this case, it always returns - * that we are looking for a properly defined utility class. - * - * @param description the Description object to use to report the "to" - * object - */ - public void describeTo(Description description) { - description.appendText("a properly defined immutable class"); - } - - /** - * Assert that the given class adheres to the immutable class rules. - * - * @param clazz the class to check - * - * @throws java.lang.AssertionError if the class is not an - * immutable class - */ - public static void assertThatClassIsImmutable(Class clazz) { - final ImmutableClassChecker checker = new ImmutableClassChecker(); - if (!checker.isImmutableClass(clazz, false)) { - final Description toDescription = new StringDescription(); - final Description mismatchDescription = new StringDescription(); - - checker.describeTo(toDescription); - checker.describeMismatch(mismatchDescription); - final String reason = - "\n" + - "Expected: is \"" + toDescription.toString() + "\"\n" + - " but : was \"" + mismatchDescription.toString() + "\""; - - throw new AssertionError(reason); - } - } - - /** - * Assert that the given class adheres to the immutable class rules, but - * is not declared final. Classes that need to be inherited from cannot be - * declared final. - * - * @param clazz the class to check - * - * @throws java.lang.AssertionError if the class is not an - * immutable class - */ - public static void assertThatClassIsImmutableBaseClass(Class clazz) { - final ImmutableClassChecker checker = new ImmutableClassChecker(); - if (!checker.isImmutableClass(clazz, true)) { - final Description toDescription = new StringDescription(); - final Description mismatchDescription = new StringDescription(); - - checker.describeTo(toDescription); - checker.describeMismatch(mismatchDescription); - final String reason = - "\n" + - "Expected: is \"" + toDescription.toString() + "\"\n" + - " but : was \"" + mismatchDescription.toString() + "\""; - - throw new AssertionError(reason); - } - } -} diff --git a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/IntegrationTest.java b/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/IntegrationTest.java deleted file mode 100644 index a033802f..00000000 --- a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/IntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.junit; - -/** - * Marker interface used to separate unit tests from integration tests. All - * integration tests should be marked with: - * {@literal @Category}(IntegrationTest.class) - * so that they can be run separately. - */ -public interface IntegrationTest { -} diff --git a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/NullScheduledExecutor.java b/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/NullScheduledExecutor.java deleted file mode 100644 index 6d959703..00000000 --- a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/NullScheduledExecutor.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.junit; - -import java.util.Collection; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * A scheduled executor service that does not do any of the work scheduled to it. - *

- * This is useful for testing when you want to disable a background scheduled - * task. - *

- */ -public class NullScheduledExecutor implements ScheduledExecutorService { - @Override - public ScheduledFuture schedule(Runnable command, long delay, - TimeUnit unit) { - return null; - } - - @Override - public ScheduledFuture schedule(Callable callable, long delay, - TimeUnit unit) { - return null; - } - - @Override - public ScheduledFuture scheduleAtFixedRate(Runnable command, - long initialDelay, - long period, TimeUnit unit) { - return null; - } - - @Override - public ScheduledFuture scheduleWithFixedDelay(Runnable command, - long initialDelay, - long delay, - TimeUnit unit) { - return null; - } - - @Override - public void shutdown() { - - } - - @Override - public List shutdownNow() { - return null; - } - - @Override - public boolean isShutdown() { - return false; - } - - @Override - public boolean isTerminated() { - return false; - } - - @Override - public boolean awaitTermination(long timeout, TimeUnit unit) - throws InterruptedException { - return false; - } - - @Override - public Future submit(Callable task) { - return null; - } - - @Override - public Future submit(Runnable task, T result) { - return null; - } - - @Override - public Future submit(Runnable task) { - return null; - } - - @Override - public List> invokeAll( - Collection> tasks) - throws InterruptedException { - return null; - } - - @Override - public List> invokeAll( - Collection> tasks, long timeout, - TimeUnit unit) throws InterruptedException { - return null; - } - - @Override - public T invokeAny(Collection> tasks) - throws InterruptedException, ExecutionException { - return null; - } - - @Override - public T invokeAny(Collection> tasks, - long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - return null; - } - - @Override - public void execute(Runnable command) { - - } -} diff --git a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/TestTools.java b/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/TestTools.java deleted file mode 100644 index 40e8686c..00000000 --- a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/TestTools.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.junit; - -import com.google.common.collect.ImmutableList; -import com.google.common.io.Files; - -import java.io.File; -import java.io.IOException; -import java.net.ServerSocket; -import java.util.List; -import java.util.Random; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.junit.Assert.fail; - -/** - * Utilities to aid in producing JUnit tests. - */ -public final class TestTools { - - private static final Random RANDOM = new Random(); - - // Prohibit construction - private TestTools() { - } - - public static void print(String msg) { - System.out.print(msg); - } - - /** - * Suspends the current thread for a specified number of millis. - * - * @param ms number of millis - */ - public static void delay(int ms) { - try { - Thread.sleep(ms); - } catch (InterruptedException e) { - fail("test interrupted"); - } - } - - /** - * Returns the current time in millis since epoch. - * - * @return current time - */ - public static long now() { - return System.currentTimeMillis(); - } - - /** - * Runs the specified runnable until it completes successfully or until the - * specified time expires. If the latter occurs, the first encountered - * assertion on the last attempt will be re-thrown. Errors other than - * assertion errors will be propagated immediately. - *

- * Assertions attempts will not be closer than 10 millis apart and no - * further than 50 millis. - *

- * - * @param delay number of millis to delay before the first attempt - * @param duration number of milliseconds beyond the current time - * @param assertions test assertions runnable - */ - public static void assertAfter(int delay, int duration, Runnable assertions) { - checkArgument(delay < duration, "delay >= duration"); - long start = now(); - int step = Math.max(Math.min((duration - delay) / 100, 50), 10); - - // Is there an initial delay? - if (delay > 0) { - delay(delay); - } - - // Keep going until the assertions succeed or until time runs-out. - while (true) { - try { - assertions.run(); - break; - } catch (AssertionError e) { - // If there was an error and time ran out, re-throw it. - if (now() - start > duration) { - throw e; - } - } - delay(step); - } - } - - /** - * Runs the specified runnable until it completes successfully or until the - * specified time expires. If the latter occurs, the first encountered - * assertion on the last attempt will be re-thrown. Errors other than - * assertion errors will be propagated immediately. - *

- * Assertions attempts will not be closer than 10 millis apart and no - * further than 50 millis. - *

- * - * @param duration number of milliseconds beyond the current time - * @param assertions test assertions runnable - */ - public static void assertAfter(int duration, Runnable assertions) { - assertAfter(0, duration, assertions); - } - - - /** - * Creates a directory tree of test files. To signify creating a directory - * file path should end with '/'. - * - * @param paths list of file paths - * @return list of created files - * @throws java.io.IOException if there is an issue - */ - public static List createTestFiles(List paths) throws IOException { - return createTestFiles(paths, 32, 1024); - } - - /** - * Creates a directory tree of test files. To signify creating a directory - * file path should end with '/'. - * - * @param paths list of file paths - * @param minSize minimum file size in bytes - * @param maxSize maximum file size in bytes - * @return list of created files - * @throws java.io.IOException if there is an issue - */ - public static List createTestFiles(List paths, - int minSize, int maxSize) throws IOException { - ImmutableList.Builder files = ImmutableList.builder(); - for (String p : paths) { - File f = new File(p); - if (p.endsWith("/")) { - if (f.mkdirs()) { - files.add(f); - } - } else { - Files.createParentDirs(f); - if (f.createNewFile()) { - writeRandomFile(f, minSize, maxSize); - files.add(f); - } - } - } - return files.build(); - } - - /** - * Writes random binary content into the specified file. The number of - * bytes will be random between the given minimum and maximum. - * - * @param file file to write data to - * @param minSize minimum number of bytes to write - * @param maxSize maximum number of bytes to write - * @throws IOException if there is an issue - */ - public static void writeRandomFile(File file, int minSize, int maxSize) throws IOException { - int size = minSize + (minSize == maxSize ? 0 : RANDOM.nextInt(maxSize - minSize)); - byte[] data = new byte[size]; - tweakBytes(RANDOM, data, size / 4); - Files.write(data, file); - } - - - /** - * Tweaks the given number of bytes in a byte array. - * - * @param random random number generator - * @param data byte array to be tweaked - * @param count number of bytes to tweak - */ - public static void tweakBytes(Random random, byte[] data, int count) { - tweakBytes(random, data, count, 0, data.length); - } - - /** - * Tweaks the given number of bytes in the specified range of a byte array. - * - * @param random random number generator - * @param data byte array to be tweaked - * @param count number of bytes to tweak - * @param start index at beginning of range (inclusive) - * @param end index at end of range (exclusive) - */ - public static void tweakBytes(Random random, byte[] data, int count, - int start, int end) { - int len = end - start; - for (int i = 0; i < count; i++) { - data[start + random.nextInt(len)] = (byte) random.nextInt(); - } - } - - /* - * Finds an available port that a test can bind to. - */ - public static int findAvailablePort(int defaultPort) { - try { - ServerSocket socket = new ServerSocket(0); - socket.setReuseAddress(true); - int port = socket.getLocalPort(); - socket.close(); - return port; - } catch (IOException ex) { - return defaultPort; - } - } - - -} diff --git a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/TestUtils.java b/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/TestUtils.java deleted file mode 100644 index 686a9a59..00000000 --- a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/TestUtils.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.junit; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - - -/** - * Utilities for testing. - */ -public final class TestUtils { - - /** - * Sets the field, bypassing scope restriction. - * - * @param subject Object where the field belongs - * @param fieldName name of the field to set - * @param value value to set to the field. - * @param subject type - * @param value type - * @throws TestUtilsException if there are reflection errors while setting - * the field - */ - public static void setField(T subject, String fieldName, U value) - throws TestUtilsException { - @SuppressWarnings("unchecked") - Class clazz = subject.getClass(); - try { - while (clazz != null) { - try { - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - field.set(subject, value); - break; - } catch (NoSuchFieldException ex) { - if (clazz == clazz.getSuperclass()) { - break; - } - clazz = clazz.getSuperclass(); - } - } - } catch (SecurityException | IllegalArgumentException | - IllegalAccessException e) { - throw new TestUtilsException("setField failed", e); - } - } - - /** - * Gets the field, bypassing scope restriction. - * - * @param subject Object where the field belongs - * @param fieldName name of the field to get - * @param subject type - * @param fieldO value type - * @return value of the field. - * @throws TestUtilsException if there are reflection errors while getting - * the field - */ - public static U getField(T subject, String fieldName) - throws TestUtilsException { - try { - NoSuchFieldException exception = null; - @SuppressWarnings("unchecked") - Class clazz = subject.getClass(); - while (clazz != null) { - try { - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - - @SuppressWarnings("unchecked") - U result = (U) field.get(subject); - return result; - } catch (NoSuchFieldException e) { - exception = e; - if (clazz == clazz.getSuperclass()) { - break; - } - clazz = clazz.getSuperclass(); - } - } - throw new TestUtilsException("Field not found. " + fieldName, exception); - - } catch (SecurityException | - IllegalArgumentException | IllegalAccessException e) { - throw new TestUtilsException("getField failed", e); - } - } - - /** - * Calls the method, bypassing scope restriction. - * - * @param subject Object where the method belongs - * @param methodName name of the method to call - * @param paramTypes formal parameter type array - * @param args arguments - * @return return value or null if void - * @param subject type - * @param return value type - * @throws TestUtilsException if there are reflection errors while calling - * the method - */ - public static U callMethod(T subject, String methodName, - Class[] paramTypes, Object...args) throws TestUtilsException { - - try { - @SuppressWarnings("unchecked") - Class clazz = (Class) subject.getClass(); - final Method method; - if (paramTypes == null || paramTypes.length == 0) { - method = clazz.getDeclaredMethod(methodName); - } else { - method = clazz.getDeclaredMethod(methodName, paramTypes); - } - method.setAccessible(true); - - @SuppressWarnings("unchecked") - U result = (U) method.invoke(subject, args); - return result; - } catch (NoSuchMethodException | SecurityException | - IllegalAccessException | IllegalArgumentException | - InvocationTargetException e) { - throw new TestUtilsException("callMethod failed", e); - } - } - - /** - * Calls the method, bypassing scope restriction. - * - * @param subject Object where the method belongs - * @param methodName name of the method to call - * @param paramType formal parameter type - * @param arg argument - * @return return value or null if void - * @param subject type - * @param return value type - * @throws TestUtilsException if there are reflection errors while calling - * the method - */ - public static U callMethod(T subject, String methodName, - Class paramType, Object arg) throws TestUtilsException { - return callMethod(subject, methodName, new Class[]{paramType}, arg); - } - - /** - * Triggers an allocation of an object of type T and forces a call to - * the private constructor. - * - * @param constructor Constructor to call - * @param type of the object to create - * @return created object of type T - * @throws TestUtilsException if there are reflection errors while calling - * the constructor - */ - public static T callConstructor(Constructor constructor) - throws TestUtilsException { - try { - constructor.setAccessible(true); - return constructor.newInstance(); - } catch (InstantiationException | IllegalAccessException | - InvocationTargetException error) { - throw new TestUtilsException("callConstructor failed", error); - } - } - - /** - * Avoid instantiation. - */ - private TestUtils() {} - - /** - * Exception that can be thrown if problems are encountered while executing - * the utility method. These are usually problems accessing fields/methods - * through reflection. The original exception can be found by examining the - * cause. - */ - public static class TestUtilsException extends Exception { - - private static final long serialVersionUID = 1L; - - /** - * Constructs a new exception with the specified detail message and - * cause. - * - * @param message the detail message - * @param cause the original cause of this exception - */ - public TestUtilsException(String message, Throwable cause) { - super(message, cause); - } - } -} diff --git a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/UtilityClassChecker.java b/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/UtilityClassChecker.java deleted file mode 100644 index 9c623cee..00000000 --- a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/UtilityClassChecker.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.junit; - -import org.hamcrest.Description; -import org.hamcrest.StringDescription; -import org.onlab.junit.TestUtils.TestUtilsException; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - - -/** - * Hamcrest style class for verifying that a class follows the - * accepted rules for utility classes. - * - * The rules that are enforced for utility classes: - * - the class must be declared final - * - the class must have only one constructor - * - the constructor must be private and inaccessible to callers - * - the class must have only static methods - */ - -public class UtilityClassChecker { - - private String failureReason = ""; - - /** - * Method to determine if a given class is a properly specified - * utility class. In addition to checking that the class meets the criteria - * for utility classes, an object of the class type is allocated to force - * test code coverage onto the class constructor. - * - * @param clazz the class to check - * @return true if the given class is a properly specified utility class. - */ - private boolean isProperlyDefinedUtilityClass(Class clazz) { - // class must be declared final - if (!Modifier.isFinal(clazz.getModifiers())) { - failureReason = "a class that is not final"; - return false; - } - - // class must have only one constructor - final Constructor[] constructors = clazz.getDeclaredConstructors(); - if (constructors.length != 1) { - failureReason = "a class with more than one constructor"; - return false; - } - - // constructor must not be accessible outside of the class - final Constructor constructor = constructors[0]; - if (constructor.isAccessible()) { - failureReason = "a class with an accessible default constructor"; - return false; - } - - // constructor must be private - if (!Modifier.isPrivate(constructor.getModifiers())) { - failureReason = "a class with a default constructor that is not private"; - return false; - } - - // class must have only static methods - for (final Method method : clazz.getMethods()) { - if (method.getDeclaringClass().equals(clazz)) { - if (!Modifier.isStatic(method.getModifiers())) { - failureReason = "a class with one or more non-static methods"; - return false; - } - } - - } - - try { - final Object newObject = TestUtils.callConstructor(constructor); - if (newObject == null) { - failureReason = "could not instantiate a new object"; - return false; - } - } catch (TestUtilsException e) { - failureReason = "could not instantiate a new object"; - return false; - } - return true; - } - - /** - * Describe why an error was reported. Uses Hamcrest style Description - * interfaces. - * - * @param description the Description object to use for reporting the - * mismatch - */ - public void describeMismatch(Description description) { - description.appendText(failureReason); - } - - /** - * Describe the source object that caused an error, using a Hamcrest - * Matcher style interface. In this case, it always returns - * that we are looking for a properly defined utility class. - * - * @param description the Description object to use to report the "to" - * object - */ - public void describeTo(Description description) { - description.appendText("a properly defined utility class"); - } - - /** - * Assert that the given class adheres to the utility class rules. - * - * @param clazz the class to check - * - * @throws java.lang.AssertionError if the class is not a valid - * utility class - */ - public static void assertThatClassIsUtility(Class clazz) { - final UtilityClassChecker checker = new UtilityClassChecker(); - if (!checker.isProperlyDefinedUtilityClass(clazz)) { - final Description toDescription = new StringDescription(); - final Description mismatchDescription = new StringDescription(); - - checker.describeTo(toDescription); - checker.describeMismatch(mismatchDescription); - final String reason = - "\n" + - "Expected: is \"" + toDescription.toString() + "\"\n" + - " but : was \"" + mismatchDescription.toString() + "\""; - - throw new AssertionError(reason); - } - } -} diff --git a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/package-info.java b/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/package-info.java deleted file mode 100644 index 379e4a04..00000000 --- a/framework/src/onos/utils/junit/src/main/java/org/onlab/junit/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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. - */ - -/** - * Utilities to assist in developing JUnit tests. - */ -package org.onlab.junit; diff --git a/framework/src/onos/utils/junit/src/main/resources/org/onosproject/openflow/controller/impl/ControllerTestKeystore.jks b/framework/src/onos/utils/junit/src/main/resources/org/onosproject/openflow/controller/impl/ControllerTestKeystore.jks deleted file mode 100644 index ba750519..00000000 Binary files a/framework/src/onos/utils/junit/src/main/resources/org/onosproject/openflow/controller/impl/ControllerTestKeystore.jks and /dev/null differ diff --git a/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/ImmutableClassCheckerTest.java b/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/ImmutableClassCheckerTest.java deleted file mode 100644 index cd5a8c1a..00000000 --- a/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/ImmutableClassCheckerTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.junit; - -import org.junit.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; - -/** - * Set of unit tests to check the implementation of the immutable class - * checker. - */ -public class ImmutableClassCheckerTest { - /** - * Test class for non final class check. - */ - // CHECKSTYLE IGNORE FinalClass FOR NEXT 1 LINES - static class NonFinal { - private NonFinal() { } - } - - /** - * Check that a non final class correctly produces an error. - * @throws Exception if any of the reflection lookups fail. - */ - @Test - public void testNonFinalClass() throws Exception { - boolean gotException = false; - try { - assertThatClassIsImmutable(NonFinal.class); - } catch (AssertionError assertion) { - assertThat(assertion.getMessage(), - containsString("is not final")); - gotException = true; - } - assertThat(gotException, is(true)); - } - - /** - * Test class for non private member class check. - */ - static final class FinalProtectedMember { - protected final int x = 0; - } - - /** - * Check that a final class with a non-private member is properly detected. - * - * @throws Exception if any of the reflection lookups fail. - */ - @Test - public void testFinalProtectedMember() throws Exception { - boolean gotException = false; - try { - assertThatClassIsImmutable(FinalProtectedMember.class); - } catch (AssertionError assertion) { - assertThat(assertion.getMessage(), - containsString("a field named 'x' that is not private")); - gotException = true; - } - assertThat(gotException, is(true)); - } - - /** - * Test class for non private member class check. - */ - static final class NotFinalPrivateMember { - private int x = 0; - } - - /** - * Check that a final class with a non-final private - * member is properly detected. - * - * @throws Exception if any of the reflection lookups fail. - */ - @Test - public void testNotFinalPrivateMember() throws Exception { - boolean gotException = false; - try { - assertThatClassIsImmutable(NotFinalPrivateMember.class); - } catch (AssertionError assertion) { - assertThat(assertion.getMessage(), - containsString("a field named 'x' that is not final")); - gotException = true; - } - assertThat(gotException, is(true)); - } - - /** - * Test class for non private member class check. - */ - static final class ClassWithSetter { - private final int x = 0; - public void setX(int newX) { - } - } - - /** - * Check that a final class with a final private - * member that is modifyable by a setter is properly detected. - * - * @throws Exception if any of the reflection lookups fail. - */ - @Test - public void testClassWithSetter() throws Exception { - boolean gotException = false; - try { - assertThatClassIsImmutable(ClassWithSetter.class); - } catch (AssertionError assertion) { - assertThat(assertion.getMessage(), - containsString("a class with a setter named 'setX'")); - gotException = true; - } - assertThat(gotException, is(true)); - } - -} - diff --git a/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/TestToolsTest.java b/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/TestToolsTest.java deleted file mode 100644 index d11cea0b..00000000 --- a/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/TestToolsTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.junit; - -import org.junit.Test; - -import static org.junit.Assert.*; -import static org.onlab.junit.TestTools.assertAfter; - -public class TestToolsTest { - - @Test - public void testSuccess() { - assertAfter(10, 100, new Runnable() { - int count = 0; - @Override - public void run() { - if (count++ < 3) { - assertTrue(false); - } - } - }); - } - - @Test(expected = AssertionError.class) - public void testFailure() { - assertAfter(100, new Runnable() { - @Override - public void run() { - assertTrue(false); - } - }); - } -} diff --git a/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/TestUtilsTest.java b/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/TestUtilsTest.java deleted file mode 100644 index 68e407fc..00000000 --- a/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/TestUtilsTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.junit; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.junit.Before; -import org.junit.Test; -import org.onlab.junit.TestUtils.TestUtilsException; - -/** - * Test and usage examples for TestUtils. - */ -public class TestUtilsTest { - - /** - * Test data. - */ - private static final class TestClass { - - @SuppressWarnings("unused") - private int privateField = 42; - - @SuppressWarnings("unused") - protected int protectedField = 2501; // CHECKSTYLE IGNORE THIS LINE - - /** - * Protected method with multiple argument. - * - * @param x simply returns - * @param y not used - * @return x - */ - @SuppressWarnings("unused") - private int privateMethod(Number x, Long y) { - return x.intValue(); - } - - /** - * Protected method with no argument. - * - * @return int - */ - @SuppressWarnings("unused") - protected int protectedMethod() { - return 42; - } - - /** - * Method returning array. - * - * @param ary random array - * @return ary - */ - @SuppressWarnings("unused") - private int[] arrayReturnMethod(int[] ary) { - return ary; - } - - /** - * Method without return value. - * - * @param s ignored - */ - @SuppressWarnings("unused") - private void voidMethod(String s) { - System.out.println(s); - } - } - - private TestClass test; - - /** - * Sets up the test fixture. - */ - @Before - public void setUp() { - test = new TestClass(); - } - - /** - * Example to access private field. - * - * @throws TestUtilsException TestUtils error - */ - @Test - public void testSetGetPrivateField() throws TestUtilsException { - - assertEquals(42, (int) TestUtils.getField(test, "privateField")); - TestUtils.setField(test, "privateField", 0xDEAD); - assertEquals(0xDEAD, (int) TestUtils.getField(test, "privateField")); - } - - /** - * Example to access protected field. - * - * @throws TestUtilsException TestUtils error - */ - @Test - public void testSetGetProtectedField() throws TestUtilsException { - - assertEquals(2501, (int) TestUtils.getField(test, "protectedField")); - TestUtils.setField(test, "protectedField", 0xBEEF); - assertEquals(0xBEEF, (int) TestUtils.getField(test, "protectedField")); - } - - /** - * Example to call private method and multiple parameters. - *

- * It also illustrates that paramTypes must match declared type, - * not the runtime types of arguments. - * - * @throws TestUtilsException TestUtils error - */ - @Test - public void testCallPrivateMethod() throws TestUtilsException { - - int result = TestUtils.callMethod(test, "privateMethod", - new Class[] {Number.class, Long.class}, - Long.valueOf(42), Long.valueOf(32)); - assertEquals(42, result); - } - - /** - * Example to call protected method and no parameters. - * - * @throws TestUtilsException TestUtils error - */ - @Test - public void testCallProtectedMethod() throws TestUtilsException { - - int result = TestUtils.callMethod(test, "protectedMethod", - new Class[] {}); - assertEquals(42, result); - } - - /** - * Example to call method returning array. - *

- * Note: It is not required to receive as Object. - * Following is just verifying it is not Boxed arrays. - * - * @throws TestUtilsException TestUtils error - */ - @Test - public void testCallArrayReturnMethod() throws TestUtilsException { - - int[] array = {1, 2, 3}; - Object aryResult = TestUtils.callMethod(test, "arrayReturnMethod", - new Class[] {int[].class}, array); - assertEquals(int[].class, aryResult.getClass()); - assertArrayEquals(array, (int[]) aryResult); - } - - - /** - * Example to call void returning method. - *

- * Note: Return value will be null for void methods. - * - * @throws TestUtilsException TestUtils error - */ - @Test - public void testCallVoidReturnMethod() throws TestUtilsException { - - Object voidResult = TestUtils.callMethod(test, "voidMethod", - String.class, "foobar"); - assertNull(voidResult); - } -} diff --git a/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/UtilityClassCheckerTest.java b/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/UtilityClassCheckerTest.java deleted file mode 100644 index 8c2c5532..00000000 --- a/framework/src/onos/utils/junit/src/test/java/org/onlab/junit/UtilityClassCheckerTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.junit; - -import org.junit.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.onlab.junit.UtilityClassChecker.assertThatClassIsUtility; - -/** - * Set of unit tests to check the implementation of the utility class - * checker. - */ -public class UtilityClassCheckerTest { - - // CHECKSTYLE:OFF test data intentionally not final - /** - * Test class for non final class check. - */ - static class NonFinal { - private NonFinal() { } - } - // CHECKSTYLE:ON - - /** - * Check that a non final class correctly produces an error. - * @throws Exception if any of the reflection lookups fail. - */ - @Test - public void testNonFinalClass() throws Exception { - boolean gotException = false; - try { - assertThatClassIsUtility(NonFinal.class); - } catch (AssertionError assertion) { - assertThat(assertion.getMessage(), - containsString("is not final")); - gotException = true; - } - assertThat(gotException, is(true)); - } - - /** - * Test class for final no constructor class check. - */ - static final class FinalNoConstructor { - } - - /** - * Check that a final class with no declared constructor correctly produces - * an error. In this case, the compiler generates a default constructor - * for you, but the constructor is 'protected' and will fail the check. - * - * @throws Exception if any of the reflection lookups fail. - */ - @Test - public void testFinalNoConstructorClass() throws Exception { - boolean gotException = false; - try { - assertThatClassIsUtility(FinalNoConstructor.class); - } catch (AssertionError assertion) { - assertThat(assertion.getMessage(), - containsString("class with a default constructor that " + - "is not private")); - gotException = true; - } - assertThat(gotException, is(true)); - } - - /** - * Test class for class with more than one constructor check. - */ - static final class TwoConstructors { - private TwoConstructors() { } - private TwoConstructors(int x) { } - } - - /** - * Check that a non static class correctly produces an error. - * @throws Exception if any of the reflection lookups fail. - */ - @Test - public void testOnlyOneConstructor() throws Exception { - boolean gotException = false; - try { - assertThatClassIsUtility(TwoConstructors.class); - } catch (AssertionError assertion) { - assertThat(assertion.getMessage(), - containsString("more than one constructor")); - gotException = true; - } - assertThat(gotException, is(true)); - } - - /** - * Test class with a non private constructor. - */ - static final class NonPrivateConstructor { - protected NonPrivateConstructor() { } - } - - /** - * Check that a class with a non private constructor correctly - * produces an error. - * @throws Exception if any of the reflection lookups fail. - */ - @Test - public void testNonPrivateConstructor() throws Exception { - - boolean gotException = false; - try { - assertThatClassIsUtility(NonPrivateConstructor.class); - } catch (AssertionError assertion) { - assertThat(assertion.getMessage(), - containsString("constructor that is not private")); - gotException = true; - } - assertThat(gotException, is(true)); - } - - /** - * Test class with a non static method. - */ - static final class NonStaticMethod { - private NonStaticMethod() { } - public void aPublicMethod() { } - } - - /** - * Check that a class with a non static method correctly produces an error. - * @throws Exception if any of the reflection lookups fail. - */ - @Test - public void testNonStaticMethod() throws Exception { - - boolean gotException = false; - try { - assertThatClassIsUtility(NonStaticMethod.class); - } catch (AssertionError assertion) { - assertThat(assertion.getMessage(), - containsString("one or more non-static methods")); - gotException = true; - } - assertThat(gotException, is(true)); - } -} diff --git a/framework/src/onos/utils/misc/pom.xml b/framework/src/onos/utils/misc/pom.xml deleted file mode 100644 index 39171e95..00000000 --- a/framework/src/onos/utils/misc/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - 4.0.0 - - - org.onosproject - onlab-utils - 1.4.0-rc1 - ../pom.xml - - - onlab-misc - bundle - - Miscellaneous ON.Lab utilities - - - - com.google.guava - guava-testlib - - - org.onosproject - onlab-junit - test - - - org.easymock - easymock - test - - - io.netty - netty - - - commons-lang - commons-lang - - - org.apache.commons - commons-lang3 - - - - - com.eclipsesource.minimal-json - minimal-json - - - com.esotericsoftware - kryo - - - io.dropwizard.metrics - metrics-core - 3.1.0 - - - io.dropwizard.metrics - metrics-json - 3.1.0 - - - org.apache.felix - org.apache.felix.scr.annotations - - - - diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AbstractEdge.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AbstractEdge.java deleted file mode 100644 index 3e8960e6..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AbstractEdge.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.Objects; - -import static com.google.common.base.MoreObjects.toStringHelper; -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Abstract graph edge implementation. - */ -public abstract class AbstractEdge implements Edge { - - private final V src; - private final V dst; - - /** - * Creates a new edge between the specified source and destination vertexes. - * - * @param src source vertex - * @param dst destination vertex - */ - public AbstractEdge(V src, V dst) { - this.src = checkNotNull(src, "Source vertex cannot be null"); - this.dst = checkNotNull(dst, "Destination vertex cannot be null"); - } - - @Override - public V src() { - return src; - } - - @Override - public V dst() { - return dst; - } - - @Override - public int hashCode() { - return Objects.hash(src, dst); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof AbstractEdge) { - final AbstractEdge other = (AbstractEdge) obj; - return Objects.equals(this.src, other.src) && Objects.equals(this.dst, other.dst); - } - return false; - } - - @Override - public String toString() { - return toStringHelper(this) - .add("src", src) - .add("dst", dst) - .toString(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AbstractGraphPathSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AbstractGraphPathSearch.java deleted file mode 100644 index e7e2c40d..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AbstractGraphPathSearch.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Basis for various graph path search algorithm implementations. - * - * @param vertex type - * @param edge type - */ -public abstract class AbstractGraphPathSearch> - implements GraphPathSearch { - - private double samenessThreshold = Double.MIN_VALUE; - - /** - * Sets a new sameness threshold for comparing cost values; default is - * is {@link Double#MIN_VALUE}. - * - * @param threshold fractional double value - */ - public void setSamenessThreshold(double threshold) { - samenessThreshold = threshold; - } - - /** - * Returns the current sameness threshold for comparing cost values. - * - * @return current threshold - */ - public double samenessThreshold() { - return samenessThreshold; - } - - /** - * Default path search result that uses the DefaultPath to convey paths - * in a graph. - */ - protected class DefaultResult implements Result { - - private final V src; - private final V dst; - protected final Set> paths = new HashSet<>(); - protected final Map costs = new HashMap<>(); - protected final Map> parents = new HashMap<>(); - protected final int maxPaths; - - /** - * Creates the result of a single-path search. - * - * @param src path source - * @param dst optional path destination - */ - public DefaultResult(V src, V dst) { - this(src, dst, 1); - } - - /** - * Creates the result of path search. - * - * @param src path source - * @param dst optional path destination - * @param maxPaths optional limit of number of paths; - * {@link GraphPathSearch#ALL_PATHS} if no limit - */ - public DefaultResult(V src, V dst, int maxPaths) { - checkNotNull(src, "Source cannot be null"); - this.src = src; - this.dst = dst; - this.maxPaths = maxPaths; - } - - @Override - public V src() { - return src; - } - - @Override - public V dst() { - return dst; - } - - @Override - public Set> paths() { - return paths; - } - - @Override - public Map costs() { - return costs; - } - - @Override - public Map> parents() { - return parents; - } - - /** - * Indicates whether or not the given vertex has a cost yet. - * - * @param v vertex to test - * @return true if the vertex has cost already - */ - boolean hasCost(V v) { - return costs.get(v) != null; - } - - /** - * Returns the current cost to reach the specified vertex. - * - * @param v vertex to reach - * @return cost to reach the vertex - */ - double cost(V v) { - Double c = costs.get(v); - return c == null ? Double.MAX_VALUE : c; - } - - /** - * Updates the cost of the vertex using its existing cost plus the - * cost to traverse the specified edge. If the search is in single - * path mode, only one path will be accrued. - * - * @param vertex vertex to update - * @param edge edge through which vertex is reached - * @param cost current cost to reach the vertex from the source - * @param replace true to indicate that any accrued edges are to be - * cleared; false to indicate that the edge should be - * added to the previously accrued edges as they yield - * the same cost - */ - void updateVertex(V vertex, E edge, double cost, boolean replace) { - costs.put(vertex, cost); - if (edge != null) { - Set edges = parents.get(vertex); - if (edges == null) { - edges = new HashSet<>(); - parents.put(vertex, edges); - } - if (replace) { - edges.clear(); - } - if (maxPaths == ALL_PATHS || edges.size() < maxPaths) { - edges.add(edge); - } - } - } - - /** - * Removes the set of parent edges for the specified vertex. - * - * @param v vertex - */ - void removeVertex(V v) { - parents.remove(v); - } - - /** - * If possible, relax the specified edge using the supplied base cost - * and edge-weight function. - * - * @param edge edge to be relaxed - * @param cost base cost to reach the edge destination vertex - * @param ew optional edge weight function - * @param forbidNegatives if true negative values will forbid the link - * @return true if the edge was relaxed; false otherwise - */ - boolean relaxEdge(E edge, double cost, EdgeWeight ew, - boolean... forbidNegatives) { - V v = edge.dst(); - double oldCost = cost(v); - double hopCost = ew == null ? 1.0 : ew.weight(edge); - if (hopCost < 0 && forbidNegatives.length == 1 && forbidNegatives[0]) { - return false; - } - - double newCost = cost + hopCost; - boolean relaxed = newCost < oldCost; - boolean same = Math.abs(newCost - oldCost) <= samenessThreshold; - if (same || relaxed) { - updateVertex(v, edge, newCost, !same); - } - return relaxed; - } - - /** - * Builds a set of paths for the specified src/dst vertex pair. - */ - protected void buildPaths() { - Set destinations = new HashSet<>(); - if (dst == null) { - destinations.addAll(costs.keySet()); - } else { - destinations.add(dst); - } - - // Build all paths between the source and all requested destinations. - for (V v : destinations) { - // Ignore the source, if it is among the destinations. - if (!v.equals(src)) { - buildAllPaths(this, src, v, maxPaths); - } - } - } - - } - - /** - * Builds a set of all paths between the source and destination using the - * graph search result by applying breadth-first search through the parent - * edges and vertex costs. - * - * @param result graph search result - * @param src source vertex - * @param dst destination vertex - * @param maxPaths limit on the number of paths built; - * {@link GraphPathSearch#ALL_PATHS} if no limit - */ - private void buildAllPaths(DefaultResult result, V src, V dst, int maxPaths) { - DefaultMutablePath basePath = new DefaultMutablePath<>(); - basePath.setCost(result.cost(dst)); - - Set> pendingPaths = new HashSet<>(); - pendingPaths.add(basePath); - - while (!pendingPaths.isEmpty() && - (maxPaths == ALL_PATHS || result.paths.size() < maxPaths)) { - Set> frontier = new HashSet<>(); - - for (DefaultMutablePath path : pendingPaths) { - // For each pending path, locate its first vertex since we - // will be moving backwards from it. - V firstVertex = firstVertex(path, dst); - - // If the first vertex is our expected source, we have reached - // the beginning, so add the this path to the result paths. - if (firstVertex.equals(src)) { - path.setCost(result.cost(dst)); - result.paths.add(new DefaultPath<>(path.edges(), path.cost())); - - } else { - // If we have not reached the beginning, i.e. the source, - // fetch the set of edges leading to the first vertex of - // this pending path; if there are none, abandon processing - // this path for good. - Set firstVertexParents = result.parents.get(firstVertex); - if (firstVertexParents == null || firstVertexParents.isEmpty()) { - break; - } - - // Now iterate over all the edges and for each of them - // cloning the current path and then insert that edge to - // the path and then add that path to the pending ones. - // When processing the last edge, modify the current - // pending path rather than cloning a new one. - Iterator edges = firstVertexParents.iterator(); - while (edges.hasNext()) { - E edge = edges.next(); - boolean isLast = !edges.hasNext(); - DefaultMutablePath pendingPath = isLast ? path : new DefaultMutablePath<>(path); - pendingPath.insertEdge(edge); - frontier.add(pendingPath); - } - } - } - - // All pending paths have been scanned so promote the next frontier - pendingPaths = frontier; - } - } - - // Returns the first vertex of the specified path. This is either the source - // of the first edge or, if there are no edges yet, the given destination. - private V firstVertex(Path path, V dst) { - return path.edges().isEmpty() ? dst : path.edges().get(0).src(); - } - - /** - * Checks the specified path search arguments for validity. - * - * @param graph graph; must not be null - * @param src source vertex; must not be null and belong to graph - * @param dst optional target vertex; must belong to graph - */ - protected void checkArguments(Graph graph, V src, V dst) { - checkNotNull(graph, "Graph cannot be null"); - checkNotNull(src, "Source cannot be null"); - Set vertices = graph.getVertexes(); - checkArgument(vertices.contains(src), "Source not in the graph"); - checkArgument(dst == null || vertices.contains(dst), - "Destination not in graph"); - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AdjacencyListsGraph.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AdjacencyListsGraph.java deleted file mode 100644 index 3890dcf8..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/AdjacencyListsGraph.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSetMultimap; - -import java.util.Objects; -import java.util.Set; - -import static com.google.common.base.MoreObjects.toStringHelper; -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Immutable graph implemented using adjacency lists. - * - * @param vertex type - * @param edge type - */ -public class AdjacencyListsGraph> - implements Graph { - - private final Set vertexes; - private final Set edges; - - private final ImmutableSetMultimap sources; - private final ImmutableSetMultimap destinations; - - /** - * Creates a graph comprising of the specified vertexes and edges. - * - * @param vertexes set of graph vertexes - * @param edges set of graph edges - */ - public AdjacencyListsGraph(Set vertexes, Set edges) { - checkNotNull(vertexes, "Vertex set cannot be null"); - checkNotNull(edges, "Edge set cannot be null"); - - // Record ingress/egress edges for each vertex. - ImmutableSetMultimap.Builder srcMap = ImmutableSetMultimap.builder(); - ImmutableSetMultimap.Builder dstMap = ImmutableSetMultimap.builder(); - - // Also make sure that all edge end-points are added as vertexes - ImmutableSet.Builder actualVertexes = ImmutableSet.builder(); - actualVertexes.addAll(vertexes); - - for (E edge : edges) { - srcMap.put(edge.src(), edge); - actualVertexes.add(edge.src()); - dstMap.put(edge.dst(), edge); - actualVertexes.add(edge.dst()); - } - - // Make an immutable copy of the edge and vertex sets - this.edges = ImmutableSet.copyOf(edges); - this.vertexes = actualVertexes.build(); - - // Build immutable copies of sources and destinations edge maps - sources = srcMap.build(); - destinations = dstMap.build(); - } - - @Override - public Set getVertexes() { - return vertexes; - } - - @Override - public Set getEdges() { - return edges; - } - - @Override - public Set getEdgesFrom(V src) { - return sources.get(src); - } - - @Override - public Set getEdgesTo(V dst) { - return destinations.get(dst); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof AdjacencyListsGraph) { - AdjacencyListsGraph that = (AdjacencyListsGraph) obj; - return this.getClass() == that.getClass() && - Objects.equals(this.vertexes, that.vertexes) && - Objects.equals(this.edges, that.edges); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(vertexes, edges); - } - - @Override - public String toString() { - return toStringHelper(this) - .add("vertexes", vertexes) - .add("edges", edges) - .toString(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/BellmanFordGraphSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/BellmanFordGraphSearch.java deleted file mode 100644 index dc741f73..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/BellmanFordGraphSearch.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.graph; - -/** - * Bellman-Ford graph search algorithm for locating shortest-paths in - * directed graphs that may contain negative cycles. - */ -public class BellmanFordGraphSearch> - extends AbstractGraphPathSearch { - - @Override - public Result search(Graph graph, V src, V dst, - EdgeWeight weight, int maxPaths) { - checkArguments(graph, src, dst); - - // Prepare the graph search result. - DefaultResult result = new DefaultResult(src, dst, maxPaths); - - // The source vertex has cost 0, of course. - result.updateVertex(src, null, 0.0, true); - - int max = graph.getVertexes().size() - 1; - for (int i = 0; i < max; i++) { - // Relax, if possible, all egress edges of the current vertex. - for (E edge : graph.getEdges()) { - if (result.hasCost(edge.src())) { - result.relaxEdge(edge, result.cost(edge.src()), weight); - } - } - } - - // Remove any vertexes reached by traversing edges with negative weights. - for (E edge : graph.getEdges()) { - if (result.hasCost(edge.src())) { - if (result.relaxEdge(edge, result.cost(edge.src()), weight)) { - result.removeVertex(edge.dst()); - } - } - } - - // Finally, but the paths on the search result and return. - result.buildPaths(); - return result; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/BreadthFirstSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/BreadthFirstSearch.java deleted file mode 100644 index 40c8735b..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/BreadthFirstSearch.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.HashSet; -import java.util.Set; - -/** - * Implementation of the BFS algorithm. - */ -public class BreadthFirstSearch> - extends AbstractGraphPathSearch { - - @Override - public Result search(Graph graph, V src, V dst, - EdgeWeight weight, int maxPaths) { - checkArguments(graph, src, dst); - - // Prepare the graph result. - DefaultResult result = new DefaultResult(src, dst, maxPaths); - - // Setup the starting frontier with the source as the sole vertex. - Set frontier = new HashSet<>(); - result.updateVertex(src, null, 0.0, true); - frontier.add(src); - - boolean reachedEnd = false; - while (!reachedEnd && !frontier.isEmpty()) { - // Prepare the next frontier. - Set next = new HashSet<>(); - - // Visit all vertexes in the current frontier. - for (V vertex : frontier) { - double cost = result.cost(vertex); - - // Visit all egress edges of the current frontier vertex. - for (E edge : graph.getEdgesFrom(vertex)) { - V nextVertex = edge.dst(); - if (!result.hasCost(nextVertex)) { - // If this vertex has not been visited yet, update it. - double newCost = cost + (weight == null ? 1.0 : weight.weight(edge)); - result.updateVertex(nextVertex, edge, newCost, true); - // If we have reached our intended destination, bail. - if (nextVertex.equals(dst)) { - reachedEnd = true; - break; - } - next.add(nextVertex); - } - - if (reachedEnd) { - break; - } - } - } - - // Promote the next frontier. - frontier = next; - } - - // Finally, but the paths on the search result and return. - result.buildPaths(); - return result; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DefaultMutablePath.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DefaultMutablePath.java deleted file mode 100644 index ad7e8402..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DefaultMutablePath.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -import com.google.common.collect.ImmutableList; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import static com.google.common.base.MoreObjects.toStringHelper; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Simple concrete implementation of a directed graph path. - */ -public class DefaultMutablePath> implements MutablePath { - - private final List edges = new ArrayList<>(); - private double cost = 0.0; - - /** - * Creates a new empty path. - */ - public DefaultMutablePath() { - } - - /** - * Creates a new path as a copy of another path. - * - * @param path path to be copied - */ - public DefaultMutablePath(Path path) { - checkNotNull(path, "Path cannot be null"); - this.cost = path.cost(); - edges.addAll(path.edges()); - } - - @Override - public V src() { - return edges.isEmpty() ? null : edges.get(0).src(); - } - - @Override - public V dst() { - return edges.isEmpty() ? null : edges.get(edges.size() - 1).dst(); - } - - @Override - public double cost() { - return cost; - } - - @Override - public List edges() { - return ImmutableList.copyOf(edges); - } - - @Override - public void setCost(double cost) { - this.cost = cost; - } - - @Override - public Path toImmutable() { - return new DefaultPath<>(edges, cost); - } - - @Override - public void insertEdge(E edge) { - checkNotNull(edge, "Edge cannot be null"); - checkArgument(edges.isEmpty() || src().equals(edge.dst()), - "Edge destination must be the same as the current path source"); - edges.add(0, edge); - } - - @Override - public void appendEdge(E edge) { - checkNotNull(edge, "Edge cannot be null"); - checkArgument(edges.isEmpty() || dst().equals(edge.src()), - "Edge source must be the same as the current path destination"); - edges.add(edge); - } - - @Override - public void removeEdge(E edge) { - checkArgument(edge.src().equals(edge.dst()) || - edges.indexOf(edge) == 0 || - edges.lastIndexOf(edge) == edges.size() - 1, - "Edge must be at start or end of path, or it must be a cyclic edge"); - edges.remove(edge); - } - - @Override - public String toString() { - return toStringHelper(this) - .add("src", src()) - .add("dst", dst()) - .add("cost", cost) - .add("edges", edges) - .toString(); - } - - @Override - public int hashCode() { - return Objects.hash(edges, cost); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof DefaultMutablePath) { - final DefaultMutablePath other = (DefaultMutablePath) obj; - return Objects.equals(this.cost, other.cost) && - Objects.equals(this.edges, other.edges); - } - return false; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DefaultPath.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DefaultPath.java deleted file mode 100644 index 816fb161..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DefaultPath.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -import com.google.common.collect.ImmutableList; - -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -import static com.google.common.base.MoreObjects.toStringHelper; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Simple concrete implementation of a directed graph path. - */ -public class DefaultPath> implements Path { - - private final V src; - private final V dst; - private final List edges; - private double cost = 0.0; - - /** - * Creates a new path from the specified list of edges and cost. - * - * @param edges list of path edges - * @param cost path cost as a unit-less number - */ - public DefaultPath(List edges, double cost) { - checkNotNull(edges, "Edges list must not be null"); - checkArgument(!edges.isEmpty(), "There must be at least one edge"); - this.edges = ImmutableList.copyOf(edges); - this.src = edges.get(0).src(); - this.dst = edges.get(edges.size() - 1).dst(); - this.cost = cost; - } - - @Override - public V src() { - return src; - } - - @Override - public V dst() { - return dst; - } - - @Override - public double cost() { - return cost; - } - - @Override - public List edges() { - return Collections.unmodifiableList(edges); - } - - @Override - public String toString() { - return toStringHelper(this) - .add("src", src) - .add("dst", dst) - .add("cost", cost) - .add("edges", edges) - .toString(); - } - - @Override - public int hashCode() { - return Objects.hash(src, dst, edges, cost); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof DefaultPath) { - final DefaultPath other = (DefaultPath) obj; - return Objects.equals(this.src, other.src) && - Objects.equals(this.dst, other.dst) && - Objects.equals(this.cost, other.cost) && - Objects.equals(this.edges, other.edges); - } - return false; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DepthFirstSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DepthFirstSearch.java deleted file mode 100644 index 91b5108f..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DepthFirstSearch.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * DFS graph search algorithm implemented via iteration rather than recursion. - */ -public class DepthFirstSearch> - extends AbstractGraphPathSearch { - - /** - * Graph edge types as classified by the DFS algorithm. - */ - public static enum EdgeType { - TREE_EDGE, FORWARD_EDGE, BACK_EDGE, CROSS_EDGE - } - - @Override - public SpanningTreeResult search(Graph graph, V src, V dst, - EdgeWeight weight, int maxPaths) { - checkArguments(graph, src, dst); - - // Prepare the search result. - SpanningTreeResult result = new SpanningTreeResult(src, dst, maxPaths); - - // The source vertex has cost 0, of course. - result.updateVertex(src, null, 0.0, true); - - // Track finished vertexes and keep a stack of vertexes that have been - // started; start this stack with the source on it. - Set finished = new HashSet<>(); - Stack stack = new Stack<>(); - stack.push(src); - - while (!stack.isEmpty()) { - V vertex = stack.peek(); - if (vertex.equals(dst)) { - // If we have reached our destination, bail. - break; - } - - double cost = result.cost(vertex); - boolean tangent = false; - - // Visit all egress edges of the current vertex. - for (E edge : graph.getEdgesFrom(vertex)) { - // If we have seen the edge already, skip it. - if (result.isEdgeMarked(edge)) { - continue; - } - - // Examine the destination of the current edge. - V nextVertex = edge.dst(); - if (!result.hasCost(nextVertex)) { - // If this vertex have not finished this vertex yet, - // not started it, then start it as a tree-edge. - result.markEdge(edge, EdgeType.TREE_EDGE); - double newCost = cost + (weight == null ? 1.0 : weight.weight(edge)); - result.updateVertex(nextVertex, edge, newCost, true); - stack.push(nextVertex); - tangent = true; - break; - - } else if (!finished.contains(nextVertex)) { - // We started the vertex, but did not yet finish it, so - // it must be a back-edge. - result.markEdge(edge, EdgeType.BACK_EDGE); - } else { - // The target has been finished already, so what we have - // here is either a forward-edge or a cross-edge. - result.markEdge(edge, isForwardEdge(result, edge) ? - EdgeType.FORWARD_EDGE : EdgeType.CROSS_EDGE); - } - } - - // If we have not been sent on a tangent search and reached the - // end of the current scan normally, mark the node as finished - // and pop it off the vertex stack. - if (!tangent) { - finished.add(vertex); - stack.pop(); - } - } - - // Finally, but the paths on the search result and return. - result.buildPaths(); - return result; - } - - /** - * Determines whether the specified edge is a forward edge using the - * accumulated set of parent edges for each vertex. - * - * @param result search result - * @param edge edge to be classified - * @return true if the edge is a forward edge - */ - protected boolean isForwardEdge(DefaultResult result, E edge) { - // Follow the parent edges until we hit the edge source vertex - V target = edge.src(); - V vertex = edge.dst(); - Set parentEdges; - while ((parentEdges = result.parents.get(vertex)) != null) { - for (E parentEdge : parentEdges) { - vertex = parentEdge.src(); - if (vertex.equals(target)) { - return true; - } - } - } - return false; - } - - /** - * Graph search result which includes edge classification for building - * a spanning tree. - */ - public class SpanningTreeResult extends DefaultResult { - - protected final Map edges = new HashMap<>(); - - /** - * Creates a new spanning tree result. - * - * @param src search source - * @param dst optional search destination - * @param maxPaths limit on the number of paths - */ - public SpanningTreeResult(V src, V dst, int maxPaths) { - super(src, dst, maxPaths); - } - - /** - * Returns the map of edge type. - * - * @return edge to edge type bindings - */ - public Map edges() { - return edges; - } - - /** - * Indicates whether or not the edge has been marked with type. - * - * @param edge edge to test - * @return true if the edge has been marked already - */ - boolean isEdgeMarked(E edge) { - return edges.containsKey(edge); - } - - /** - * Marks the edge with the specified type. - * - * @param edge edge to mark - * @param type edge type - */ - void markEdge(E edge, EdgeType type) { - edges.put(edge, type); - } - - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DijkstraGraphSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DijkstraGraphSearch.java deleted file mode 100644 index b1892ee1..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DijkstraGraphSearch.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Set; - -/** - * Dijkstra shortest-path graph search algorithm capable of finding not just - * one, but all shortest paths between the source and destinations. - */ -public class DijkstraGraphSearch> - extends AbstractGraphPathSearch { - - @Override - public Result search(Graph graph, V src, V dst, - EdgeWeight weight, int maxPaths) { - checkArguments(graph, src, dst); - - // Use the default result to remember cumulative costs and parent - // edges to each each respective vertex. - DefaultResult result = new DefaultResult(src, dst, maxPaths); - - // Cost to reach the source vertex is 0 of course. - result.updateVertex(src, null, 0.0, false); - - if (graph.getEdges().isEmpty()) { - result.buildPaths(); - return result; - } - - // Use the min priority queue to progressively find each nearest - // vertex until we reach the desired destination, if one was given, - // or until we reach all possible destinations. - Heap minQueue = createMinQueue(graph.getVertexes(), - new PathCostComparator(result)); - while (!minQueue.isEmpty()) { - // Get the nearest vertex - V nearest = minQueue.extractExtreme(); - if (nearest.equals(dst)) { - break; - } - - // Find its cost and use it to determine if the vertex is reachable. - double cost = result.cost(nearest); - if (cost < Double.MAX_VALUE) { - // If the vertex is reachable, relax all its egress edges. - for (E e : graph.getEdgesFrom(nearest)) { - result.relaxEdge(e, cost, weight, true); - } - } - - // Re-prioritize the min queue. - minQueue.heapify(); - } - - // Now construct a set of paths from the results. - result.buildPaths(); - return result; - } - - // Compares path weights using their accrued costs; used for sorting the - // min priority queue. - private final class PathCostComparator implements Comparator { - private final DefaultResult result; - - private PathCostComparator(DefaultResult result) { - this.result = result; - } - - @Override - public int compare(V v1, V v2) { - double delta = result.cost(v2) - result.cost(v1); - return delta < 0 ? -1 : (delta > 0 ? 1 : 0); - } - } - - // Creates a min priority queue from the specified vertexes and comparator. - private Heap createMinQueue(Set vertexes, Comparator comparator) { - return new Heap<>(new ArrayList<>(vertexes), comparator); - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DisjointPathPair.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DisjointPathPair.java deleted file mode 100644 index dfa150e3..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/DisjointPathPair.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.List; -import java.util.Objects; - -import static com.google.common.base.MoreObjects.toStringHelper; - -/** - * Pair of disjoint paths. - * - * @param type of vertex - * @param type of edge - */ -public class DisjointPathPair> implements Path { - - private final Path primary, secondary; - private boolean primaryActive = true; - - /** - * Creates a disjoint path pair from two paths. - * - * @param primary primary path - * @param secondary secondary path - */ - public DisjointPathPair(Path primary, Path secondary) { - this.primary = primary; - this.secondary = secondary; - } - - @Override - public V src() { - return primary.src(); - } - - @Override - public V dst() { - return primary.dst(); - } - - /** - * Returns the primary path. - * - * @return primary path - */ - public Path primary() { - return primary; - } - - /** - * Returns the secondary path. - * - * @return primary path - */ - public Path secondary() { - return secondary; - } - - @Override - public double cost() { - return hasBackup() ? primary.cost() + secondary.cost() : primary.cost(); - } - - @Override - public List edges() { - return primaryActive || !hasBackup() ? primary.edges() : secondary.edges(); - } - - /** - * Checks if this path pair contains a backup/secondary path. - * - * @return boolean representing whether it has backup - */ - public boolean hasBackup() { - return secondary != null; - } - - @Override - public String toString() { - return toStringHelper(this) - .add("src", src()) - .add("dst", dst()) - .add("cost", cost()) - .add("edges", edges()) - .toString(); - } - - @Override - public int hashCode() { - // Note: DisjointPathPair with primary and secondary swapped - // must result in same hashCode - return hasBackup() ? primary.hashCode() + secondary.hashCode() : - Objects.hash(primary); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof DisjointPathPair) { - final DisjointPathPair other = (DisjointPathPair) obj; - return Objects.equals(this.src(), other.src()) && - Objects.equals(this.dst(), other.dst()) && - (Objects.equals(this.primary, other.primary) && - Objects.equals(this.secondary, other.secondary)) || - (Objects.equals(this.primary, other.secondary) && - Objects.equals(this.secondary, other.primary)); - } - return false; - } - - /** - * Returns number of paths inside this path pair object. - * - * @return number of paths - */ - public int size() { - return hasBackup() ? 2 : 1; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Edge.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Edge.java deleted file mode 100644 index 1bbfbf99..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Edge.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -/** - * Representation of a graph edge. - * - * @param vertex type - */ -public interface Edge { - - /** - * Returns the edge source vertex. - * - * @return source vertex - */ - V src(); - - /** - * Returns the edge destination vertex. - * - * @return destination vertex - */ - V dst(); - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/EdgeWeight.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/EdgeWeight.java deleted file mode 100644 index 975b59c7..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/EdgeWeight.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -/** - * Abstraction of a graph edge weight function. - */ -public interface EdgeWeight> { - - /** - * Returns the weight of the given edge as a unit-less number. - * - * @param edge edge to be weighed - * @return edge weight as a unit-less number - */ - double weight(E edge); - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GAOrganism.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GAOrganism.java deleted file mode 100644 index a0e0570d..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GAOrganism.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.graph; - -/** - * Interface representing an "organism": a specific solution - * to a problem where solutions can be evaluated in terms - * of fitness. These organisms can be used to represent any - * class of problem that genetic algorithms can be run on. - */ -interface GAOrganism { - /** - * A fitness function that determines how - * optimal a given organism is. - * - * @return fitness of organism - */ - double fitness(); - - /** - * A method that slightly mutates an organism. - */ - void mutate(); - - /** - * Creates a new random organism. - * - * @return random GAOrganism - */ - GAOrganism random(); - - /** - * Returns a child organism that is the result - * of "crossing" this organism with another. - * - * @param other Other organism to cross with - * @return child organism - */ - GAOrganism crossWith(GAOrganism other); -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GAPopulation.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GAPopulation.java deleted file mode 100644 index c5fa9b45..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GAPopulation.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -/** - * Represents a population of GAOrganisms. This class can be used - * to run a genetic algorithm on the population and return the fittest solutions. - */ -class GAPopulation extends ArrayList { - Random r = new Random(); - - /** - * Steps the population through one generation. The 75% least fit - * organisms are killed off and replaced with the children of the - * 25% (as well as some "random" newcomers). - */ - void step() { - Collections.sort(this, (org1, org2) -> { - double d = org1.fitness() - org2.fitness(); - if (d < 0) { - return -1; - } else if (d == 0) { - return 0; - } - return 1; - }); - int maxSize = size(); - for (int i = size() - 1; i > maxSize / 4; i--) { - remove(i); - } - for (Organism org: this) { - if (r.nextBoolean()) { - org.mutate(); - } - } - while (size() < maxSize * 4 / 5) { - Organism org1 = get(r.nextInt(size())); - Organism org2 = get(r.nextInt(size())); - add((Organism) org1.crossWith(org2)); - } - - while (size() < maxSize) { - Organism org1 = get(r.nextInt(size())); - add((Organism) org1.random()); - } - } - - /** - * Runs GA for the specified number of iterations, and returns - * a sample of the resulting population of solutions. - * - * @param generations Number of generations to run GA for - * @param populationSize Population size of GA - * @param sample Number of solutions to ask for - * @param template Template GAOrganism to seed the population with - * @return ArrayList containing sample number of organisms - */ - List runGA(int generations, int populationSize, int sample, Organism template) { - for (int i = 0; i < populationSize; i++) { - add((Organism) template.random()); - } - - for (int i = 0; i < generations; i++) { - step(); - } - for (int i = size() - 1; i >= sample; i--) { - remove(i); - } - return new ArrayList<>(this); - } -} - diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Graph.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Graph.java deleted file mode 100644 index bc7853ec..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Graph.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - - -import java.util.Set; - -/** - * Abstraction of a directed graph structure. - * - * @param vertex type - * @param edge type - */ -public interface Graph { - - /** - * Returns the set of vertexes comprising the graph. - * - * @return set of vertexes - */ - Set getVertexes(); - - /** - * Returns the set of edges comprising the graph. - * - * @return set of edges - */ - Set getEdges(); - - /** - * Returns all edges leading out from the specified source vertex. - * - * @param src source vertex - * @return set of egress edges; empty if no such edges - */ - Set getEdgesFrom(V src); - - /** - * Returns all edges leading towards the specified destination vertex. - * - * @param dst destination vertex - * @return set of ingress vertexes; empty if no such edges - */ - Set getEdgesTo(V dst); - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GraphPathSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GraphPathSearch.java deleted file mode 100644 index caebce47..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GraphPathSearch.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.Map; -import java.util.Set; - -/** - * Representation of a graph path search algorithm. - * - * @param vertex type - * @param edge type - */ -public interface GraphPathSearch> { - - static int ALL_PATHS = -1; - - /** - * Abstraction of a path search result. - */ - interface Result> { - - /** - * Returns the search source. - * - * @return search source - */ - V src(); - - /** - * Returns the search destination, if was was given. - * - * @return optional search destination - */ - V dst(); - - /** - * Returns the set of paths produced as a result of the graph search. - * - * @return set of paths - */ - Set> paths(); - - /** - * Returns bindings of each vertex to its parent edges in the path. - * - * @return map of vertex to its parent edge bindings - */ - Map> parents(); - - /** - * Return a bindings of each vertex to its cost in the path. - * - * @return map of vertex to path cost bindings - */ - Map costs(); - } - - /** - * Searches the specified graph for paths between vertices. - * - * @param graph graph to be searched - * @param src optional source vertex - * @param dst optional destination vertex; if null paths to all vertex - * destinations will be searched - * @param weight optional edge-weight; if null cost of each edge will be - * assumed to be 1.0 - * @param maxPaths limit on number of paths; {@link GraphPathSearch#ALL_PATHS} if no limit - * @return search results - */ - Result search(Graph graph, V src, V dst, - EdgeWeight weight, int maxPaths); - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GraphSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GraphSearch.java deleted file mode 100644 index ca369a7d..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/GraphSearch.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -/** - * Representation of a graph search algorithm and its outcome. - * - * @param vertex type - * @param edge type - */ -public interface GraphSearch> { - - /** - * Notion of a graph search result. - */ - interface Result> { - } - - /** - * Searches the specified graph. - * - * @param graph graph to be searched - * @param weight optional edge-weight; if null cost of each edge will be - * assumed to be 1.0 - * - * @return search results - */ - Result search(Graph graph, EdgeWeight weight); - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Heap.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Heap.java deleted file mode 100644 index ebb1a60b..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Heap.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -import com.google.common.collect.ImmutableList; - -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; - -import static com.google.common.base.MoreObjects.toStringHelper; -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Implementation of an array-backed heap structure whose sense of order is - * imposed by the provided comparator. - *

- * While this provides similar functionality to {@link java.util.PriorityQueue} - * data structure, one key difference is that external entities can control - * when to restore the heap property, which is done through invocation of the - * {@link #heapify} method. - *

- *

- * This class is not thread-safe and care must be taken to prevent concurrent - * modifications. - *

- * - * @param type of the items on the heap - */ -public class Heap { - - private final List data; - private final Comparator comparator; - - /** - * Creates a new heap backed by the specified list. In the interest of - * efficiency, the list should be array-backed. Also, for the same reason, - * the data is not copied and therefore, the caller must assure that the - * backing data is not altered in any way. - * - * @param data backing data list - * @param comparator comparator for ordering the heap items - */ - public Heap(List data, Comparator comparator) { - this.data = checkNotNull(data, "Data cannot be null"); - this.comparator = checkNotNull(comparator, "Comparator cannot be null"); - heapify(); - } - - /** - * Restores the heap property by re-arranging the elements in the backing - * array as necessary following any heap modifications. - */ - public void heapify() { - for (int i = data.size() / 2; i >= 0; i--) { - heapify(i); - } - } - - /** - * Returns the current size of the heap. - * - * @return number of items in the heap - */ - public int size() { - return data.size(); - } - - /** - * Returns true if there are no items in the heap. - * - * @return true if heap is empty - */ - public boolean isEmpty() { - return data.isEmpty(); - } - - /** - * Returns the most extreme item in the heap. - * - * @return heap extreme or null if the heap is empty - */ - public T extreme() { - return data.isEmpty() ? null : data.get(0); - } - - /** - * Extracts and returns the most extreme item from the heap. - * - * @return heap extreme or null if the heap is empty - */ - public T extractExtreme() { - if (!isEmpty()) { - T extreme = extreme(); - - data.set(0, data.get(data.size() - 1)); - data.remove(data.size() - 1); - heapify(); - return extreme; - } - return null; - } - - /** - * Inserts the specified item into the heap and returns the modified heap. - * - * @param item item to be inserted - * @return the heap self - * @throws IllegalArgumentException if the heap is already full - */ - public Heap insert(T item) { - data.add(item); - bubbleUp(); - return this; - } - - /** - * Returns iterator to traverse the heap level-by-level. This iterator - * does not permit removal of items. - * - * @return non-destructive heap iterator - */ - public Iterator iterator() { - return ImmutableList.copyOf(data).iterator(); - } - - // Bubbles up the last item in the heap to its proper position to restore - // the heap property. - private void bubbleUp() { - int child = data.size() - 1; - while (child > 0) { - int parent = child / 2; - if (comparator.compare(data.get(child), data.get(parent)) < 0) { - break; - } - swap(child, parent); - child = parent; - } - } - - // Restores the heap property of the specified heap layer. - private void heapify(int i) { - int left = 2 * i + 1; - int right = 2 * i; - int extreme = i; - - if (left < data.size() && - comparator.compare(data.get(extreme), data.get(left)) < 0) { - extreme = left; - } - - if (right < data.size() && - comparator.compare(data.get(extreme), data.get(right)) < 0) { - extreme = right; - } - - if (extreme != i) { - swap(i, extreme); - heapify(extreme); - } - } - - // Swaps two heap items identified by their respective indexes. - private void swap(int i, int k) { - T aux = data.get(i); - data.set(i, data.get(k)); - data.set(k, aux); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof Heap) { - Heap that = (Heap) obj; - return this.getClass() == that.getClass() && - Objects.equals(this.comparator, that.comparator) && - Objects.deepEquals(this.data, that.data); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(comparator, data); - } - - @Override - public String toString() { - return toStringHelper(this) - .add("data", data) - .add("comparator", comparator) - .toString(); - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/KshortestPathSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/KshortestPathSearch.java deleted file mode 100644 index 820e912c..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/KshortestPathSearch.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.ArrayList; -//import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -//import java.util.Map; -//import java.util.PriorityQueue; -import java.util.Set; - -import static org.onlab.graph.GraphPathSearch.ALL_PATHS; - -/** - * K-shortest-path graph search algorithm capable of finding not just one, - * but K shortest paths with ascending order between the source and destinations. - */ - -public class KshortestPathSearch> { - - // Define class variables. - private Graph immutableGraph; - private MutableGraph mutableGraph; - private List> pathResults = new ArrayList>(); - private List> pathCandidates = new ArrayList>(); - private V source; - private V sink; - private int numK = 0; - private EdgeWeight weight = null; - // private PriorityQueue> pathCandidates = new PriorityQueue>(); - - // Initialize the graph. - public KshortestPathSearch(Graph graph) { - immutableGraph = graph; - mutableGraph = new MutableAdjacencyListsGraph<>(graph.getVertexes(), - graph.getEdges()); - } - - public List> search(V src, - V dst, - EdgeWeight wei, - int k) { - - weight = wei; - source = src; - sink = dst; - numK = k; - // pathCandidates = new PriorityQueue>(); - - pathResults.clear(); - pathCandidates.clear(); - - // Double check the parameters - checkArguments(immutableGraph, src, dst, numK); - - // DefaultResult result = new DefaultResult(src, dst); - - searchKShortestPaths(); - - return pathResults; - } - - private void checkArguments(Graph graph, V src, V dst, int k) { - if (graph == null) { - throw new NullPointerException("graph is null"); - } - if (!graph.getVertexes().contains(src)) { - throw new NullPointerException("source node does not exist"); - } - if (!graph.getVertexes().contains(dst)) { - throw new NullPointerException("target node does not exist"); - } - if (k <= 0) { - throw new NullPointerException("K is negative or 0"); - } - if (weight == null) { - throw new NullPointerException("the cost matrix is null"); - } - } - - private void searchKShortestPaths() { - // Step 1: find the shortest path. - List shortestPath = searchShortestPath(immutableGraph, source, sink); - // no path exists, exit. - if (shortestPath == null) { - return; - } - - // Step 2: update the results. - pathResults.add(shortestPath); - // pathCandidates.add(shortestPath); - - // Step 3: find the other K-1 paths. - while (/*pathCandidates.size() > 0 &&*/pathResults.size() < numK) { - // 3.1 the spur node ranges from the first node to the last node in the previous k-shortest path. - List lastPath = pathResults.get(pathResults.size() - 1); - for (int i = 0; i < lastPath.size(); i++) { - // 3.1.1 convert the graph into mutable. - convertGraph(); - // 3.1.2 transform the graph. - List rootPath = createSpurNode(lastPath, i); - transformGraph(rootPath); - // 3.1.3 find the deviation node. - V devNode; - devNode = getDevNode(rootPath); - List spurPath; - // 3.1.4 find the shortest path in the transformed graph. - spurPath = searchShortestPath(mutableGraph, devNode, sink); - // 3.1.5 update the path candidates. - if (spurPath != null) { - // totalPath = rootPath + spurPath; - rootPath.addAll(spurPath); - pathCandidates.add(rootPath); - } - } - // 3.2 if there is no spur path, exit. - if (pathCandidates.size() == 0) { - break; - } - // 3.3 add the path into the results. - addPathResult(); - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private List searchShortestPath(Graph graph, V src, V dst) { - // Determine the shortest path from the source to the destination by using the Dijkstra algorithm. - DijkstraGraphSearch dijkstraAlg = new DijkstraGraphSearch(); - Set paths = dijkstraAlg.search(graph, src, dst, weight, ALL_PATHS).paths(); - Iterator itr = paths.iterator(); - if (!itr.hasNext()) { - return null; - } - // return the first shortest path only. - return (List) itr.next().edges(); - } - - private void convertGraph() { - // clear the mutableGraph first - if (mutableGraph != null) { - ((MutableAdjacencyListsGraph) mutableGraph).clear(); - } - - // create a immutableGraph - Set copyEa = immutableGraph.getEdges(); - Set copyVa = immutableGraph.getVertexes(); - for (V vertex : copyVa) { - mutableGraph.addVertex(vertex); - } - for (E edge : copyEa) { - mutableGraph.addEdge(edge); - } - } - - private V getDevNode(List path) { - V srcA; - V dstB; - - if (path.size() == 0) { - return source; - } - - E temp1 = path.get(path.size() - 1); - srcA = temp1.src(); - dstB = temp1.dst(); - - if (path.size() == 1) { - if (srcA.equals(source)) { - return dstB; - } else { - return srcA; - } - } else { - E temp2 = path.get(path.size() - 2); - if (srcA.equals(temp2.src()) || srcA.equals(temp2.dst())) { - return dstB; - } else { - return srcA; - } - } - } - - private List createSpurNode(List path, int n) { - List root = new ArrayList(); - - for (int i = 0; i < n; i++) { - root.add(path.get(i)); - } - return root; - } - - private void transformGraph(List rootPath) { - List prePath; - //remove edges - for (int i = 0; i < pathResults.size(); i++) { - prePath = pathResults.get(i); - if (prePath.size() == 1) { - mutableGraph.removeEdge(prePath.get(0)); - } else if (comparePath(rootPath, prePath)) { - for (int j = 0; j <= rootPath.size(); j++) { - mutableGraph.removeEdge(prePath.get(j)); - } - } - } - for (int i = 0; i < pathCandidates.size(); i++) { - prePath = pathCandidates.get(i); - if (prePath.size() == 1) { - mutableGraph.removeEdge(prePath.get(0)); - } else if (comparePath(rootPath, prePath)) { - for (int j = 0; j <= rootPath.size(); j++) { - mutableGraph.removeEdge(prePath.get(j)); - } - } - } - - if (rootPath.size() == 0) { - return; - } - - //remove nodes - List nodes = new ArrayList(); - nodes.add(source); - V pre = source; - V srcA; - V dstB; - for (int i = 0; i < rootPath.size() - 1; i++) { - E temp = rootPath.get(i); - srcA = temp.src(); - dstB = temp.dst(); - - if (srcA.equals(pre)) { - nodes.add(dstB); - pre = dstB; - } else { - nodes.add(srcA); - pre = srcA; - } - } - for (int i = 0; i < nodes.size(); i++) { - mutableGraph.removeVertex(nodes.get(i)); - } - } - - private boolean comparePath(List path1, List path2) { - if (path1.size() > path2.size()) { - return false; - } - if (path1.size() == 0) { - return true; - } - for (int i = 0; i < path1.size(); i++) { - if (path1.get(i) != path2.get(i)) { - return false; - } - } - return true; - } - - private void addPathResult() { - List sp; - sp = pathCandidates.get(0); - for (int i = 1; i < pathCandidates.size(); i++) { - if (sp.size() > pathCandidates.get(i).size()) { - sp = pathCandidates.get(i); - } - } - pathResults.add(sp); - // Log.info(sp.toString()); - pathCandidates.remove(sp); - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutableAdjacencyListsGraph.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutableAdjacencyListsGraph.java deleted file mode 100644 index 87571c4b..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutableAdjacencyListsGraph.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -import static com.google.common.base.MoreObjects.toStringHelper; - -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.SetMultimap; - -public class MutableAdjacencyListsGraph> -implements MutableGraph { - private Set vertexes = new HashSet(); - private Set edges = new HashSet(); - - private SetMultimap sources = HashMultimap.create(); - private SetMultimap destinations = HashMultimap.create(); - - /** - * Creates a graph comprising of the specified vertexes and edges. - * - * @param vertex set of graph vertexes - * @param edge set of graph edges - */ - public MutableAdjacencyListsGraph(Set vertex, Set edge) { - vertexes.addAll(vertex); - edges.addAll(edge); - for (E e : edge) { - sources.put(e.src(), e); - vertexes.add(e.src()); - destinations.put(e.dst(), e); - vertexes.add(e.dst()); - } - } - - @Override - public Set getVertexes() { - return vertexes; - } - - @Override - public Set getEdges() { - return edges; - } - - @Override - public Set getEdgesFrom(V src) { - return sources.get(src); - } - - @Override - public Set getEdgesTo(V dst) { - return destinations.get(dst); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof MutableAdjacencyListsGraph) { - MutableAdjacencyListsGraph that = (MutableAdjacencyListsGraph) obj; - return this.getClass() == that.getClass() && - Objects.equals(this.vertexes, that.vertexes) && - Objects.equals(this.edges, that.edges); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(vertexes, edges); - } - - @Override - public String toString() { - return toStringHelper(this) - .add("vertexes", vertexes) - .add("edges", edges) - .toString(); - } - - - @Override - public void addVertex(V vertex) { - if (vertexes != null) { - if (!vertexes.contains(vertex)) { - vertexes.add(vertex); - } - } - } - - @Override - public void removeVertex(V vertex) { - if (vertexes != null && edges != null) { - if (vertexes.contains(vertex)) { - vertexes.remove(vertex); - Set srcEdgesList = sources.get(vertex); - Set dstEdgesList = destinations.get(vertex); - edges.removeAll(srcEdgesList); - edges.removeAll(dstEdgesList); - sources.remove(vertex, srcEdgesList); - sources.remove(vertex, dstEdgesList); - } - } - } - - @Override - public void addEdge(E edge) { - if (edges != null) { - if (!edges.contains(edge)) { - edges.add(edge); - sources.put(edge.src(), edge); - destinations.put(edge.dst(), edge); - } - } - } - - @Override - public void removeEdge(E edge) { - if (edges != null) { - if (edges.contains(edge)) { - edges.remove(edge); - sources.remove(edge.src(), edge); - destinations.remove(edge.dst(), edge); - } - } - } - - @Override - public Graph toImmutable() { - return null; - } - - /** - * Clear the graph. - */ - public void clear() { - edges.clear(); - vertexes.clear(); - sources.clear(); - destinations.clear(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutableGraph.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutableGraph.java deleted file mode 100644 index bd2b600c..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutableGraph.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -/** - * Abstraction of a mutable graph that can be constructed gradually. - */ -public interface MutableGraph extends Graph { - - /** - * Adds the specified vertex to this graph. - * - * @param vertex new vertex - */ - void addVertex(V vertex); - - /** - * Removes the specified vertex from the graph. - * - * @param vertex vertex to be removed - */ - void removeVertex(V vertex); - - /** - * Adds the specified edge to this graph. If the edge vertexes are not - * already in the graph, they will be added as well. - * - * @param edge new edge - */ - void addEdge(E edge); - - /** - * Removes the specified edge from the graph. - * - * @param edge edge to be removed - */ - void removeEdge(E edge); - - /** - * Returns an immutable copy of this graph. - * - * @return immutable copy - */ - Graph toImmutable(); - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutablePath.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutablePath.java deleted file mode 100644 index 5cd8fd0e..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/MutablePath.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -/** - * Abstraction of a mutable path that allows gradual construction. - */ -public interface MutablePath> extends Path { - - /** - * Inserts a new edge at the beginning of this path. The edge must be - * adjacent to the prior start of the path. - * - * @param edge edge to be inserted - */ - void insertEdge(E edge); - - /** - * Appends a new edge at the end of the this path. The edge must be - * adjacent to the prior end of the path. - * - * @param edge edge to be inserted - */ - void appendEdge(E edge); - - /** - * Removes the specified edge. This edge must be either at the start or - * at the end of the path, or it must be a cyclic edge in order not to - * violate the contiguous path property. - * - * @param edge edge to be removed - */ - void removeEdge(E edge); - - /** - * Sets the total path cost as a unit-less double. - * - * @param cost new path cost - */ - void setCost(double cost); - - /** - * Returns an immutable copy of this path. - * - * @return immutable copy - */ - Path toImmutable(); - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Path.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Path.java deleted file mode 100644 index ed9aa2c9..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Path.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.List; - -/** - * Representation of a path in a graph as a sequence of edges. Paths are - * assumed to be continuous, where adjacent edges must share a vertex. - * - * @param vertex type - * @param edge type - */ -public interface Path> extends Edge { - - /** - * Returns the list of edges comprising the path. Adjacent edges will - * share the same vertex, meaning that a source of one edge, will be the - * same as the destination of the prior edge. - * - * @return list of path edges - */ - List edges(); - - /** - * Returns the total cost of the path as a unit-less number. - * - * @return path cost as a unit-less number - */ - double cost(); - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/SrlgGraphSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/SrlgGraphSearch.java deleted file mode 100644 index fa3d0ddf..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/SrlgGraphSearch.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - - -import java.util.Map; -import java.util.List; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; -import java.util.Random; - - -/** - * SRLG Graph Search finds a pair of paths with disjoint risk groups; i.e - * if one path goes through an edge in risk group 1, the other path will go - * through no edges in risk group 1. - */ -public class SrlgGraphSearch> - extends AbstractGraphPathSearch { - - static final int ITERATIONS = 100; - static final int POPSIZE = 50; - - boolean useSuurballe = false; - - static final double INF = 100000000.0; - - int numGroups; - Map riskGrouping; - - Graph orig; - V src, dst; - EdgeWeight weight; - - /** - * Creates an SRLG graph search object with the given number - * of groups and given risk mapping. - * - * @param groups the number of disjoint risk groups - * @param grouping map linking edges to integral group assignments - */ - public SrlgGraphSearch(int groups, Map grouping) { - numGroups = groups; - riskGrouping = grouping; - } - - /** - * Creates an SRLG graph search object from a map, inferring - * the number of groups and creating an integral mapping. - * - * @param grouping map linking edges to object group assignments, - * with same-group status linked to equality - */ - public SrlgGraphSearch(Map grouping) { - if (grouping == null) { - useSuurballe = true; - return; - } - numGroups = 0; - HashMap tmpMap = new HashMap<>(); - riskGrouping = new HashMap<>(); - for (E key: grouping.keySet()) { - Object value = grouping.get(key); - if (!tmpMap.containsKey(value)) { - tmpMap.put(value, numGroups); - numGroups++; - } - riskGrouping.put(key, tmpMap.get(value)); - } - } - - @Override - public Result search(Graph graph, V src, V dst, - EdgeWeight weight, int maxPaths) { - if (maxPaths == ALL_PATHS) { - maxPaths = POPSIZE; - } - if (useSuurballe) { - return new SuurballeGraphSearch().search(graph, src, dst, weight, ALL_PATHS); - } - if (weight == null) { - weight = edge -> 1; - } - checkArguments(graph, src, dst); - orig = graph; - this.src = src; - this.dst = dst; - this.weight = weight; - List best = new GAPopulation() - .runGA(ITERATIONS, POPSIZE, maxPaths, new Subset(new boolean[numGroups])); - Set dpps = new HashSet(); - for (Subset s: best) { - dpps.addAll(s.buildPaths()); - } - Result firstDijkstra = new DijkstraGraphSearch() - .search(orig, src, dst, weight, 1); - return new Result() { - final DefaultResult search = (DefaultResult) firstDijkstra; - - public V src() { - return src; - } - public V dst() { - return dst; - - } - public Set> paths() { - Set> pathsD = new HashSet<>(); - for (DisjointPathPair path: dpps) { - pathsD.add(path); - } - return pathsD; - } - public Map costs() { - return search.costs(); - - } - public Map> parents() { - return search.parents(); - - } - }; - } - - //finds the shortest path in the graph given a subset of edge types to use - private Result findShortestPathFromSubset(boolean[] subset) { - Graph graph = orig; - EdgeWeight modified = new EdgeWeight() { - final boolean[] subsetF = subset; - - @Override - public double weight(E edge) { - if (subsetF[riskGrouping.get(edge)]) { - return weight.weight(edge); - } - return INF; - } - }; - - Result res = new DijkstraGraphSearch().search(graph, src, dst, modified, 1); - return res; - } - /** - * A subset is a type of GA organism that represents a subset of allowed shortest - * paths (and its complement). Its fitness is determined by the sum of the weights - * of the first two shortest paths. - */ - class Subset implements GAOrganism { - - boolean[] subset; - boolean[] not; - Random r = new Random(); - - /** - * Creates a Subset from the given subset array. - * - * @param sub subset array - */ - public Subset(boolean[] sub) { - subset = sub.clone(); - not = new boolean[subset.length]; - for (int i = 0; i < subset.length; i++) { - not[i] = !subset[i]; - } - } - - @Override - public double fitness() { - Set> paths1 = findShortestPathFromSubset(subset).paths(); - Set> paths2 = findShortestPathFromSubset(not).paths(); - if (paths1.size() == 0 || paths2.size() == 0) { - return INF; - } - return paths1.iterator().next().cost() + paths2.iterator().next().cost(); - } - - @Override - public void mutate() { - int turns = r.nextInt((int) Math.sqrt(subset.length)); - while (turns > 0) { - int choose = r.nextInt(subset.length); - subset[choose] = !subset[choose]; - not[choose] = !not[choose]; - turns--; - } - } - - @Override - public GAOrganism crossWith(GAOrganism org) { - if (!(org.getClass().equals(getClass()))) { - return this; - } - Subset other = (Subset) (org); - boolean[] sub = new boolean[subset.length]; - for (int i = 0; i < subset.length; i++) { - sub[i] = subset[i]; - if (r.nextBoolean()) { - sub[i] = other.subset[i]; - } - } - return new Subset(sub); - } - - @Override - public GAOrganism random() { - boolean[] sub = new boolean[subset.length]; - for (int i = 0; i < sub.length; i++) { - sub[i] = r.nextBoolean(); - } - return new Subset(sub); - } - - /** - * Builds the set of disjoint path pairs for a given subset - * using Dijkstra's algorithm on both the subset and complement - * and returning all pairs with one from each set. - * - * @return all shortest disjoint paths given this subset - */ - public Set buildPaths() { - Set dpps = new HashSet<>(); - for (Path path1: findShortestPathFromSubset(subset).paths()) { - if (path1.cost() >= INF) { - continue; - } - for (Path path2: findShortestPathFromSubset(not).paths()) { - if (path2.cost() >= INF) { - continue; - } - DisjointPathPair dpp = new DisjointPathPair<>(path1, path2); - dpps.add(dpp); - } - } - return dpps; - } - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/SuurballeGraphSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/SuurballeGraphSearch.java deleted file mode 100644 index 76591c82..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/SuurballeGraphSearch.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.ArrayList; -import java.util.Set; -import java.util.List; -import java.util.Map; -import java.util.HashMap; -import java.util.HashSet; -import java.util.stream.Collectors; - -/** - * Suurballe shortest-path graph search algorithm capable of finding both - * a shortest path, as well as a backup shortest path, between a source and a destination - * such that the sum of the path lengths is minimized. - */ -public class SuurballeGraphSearch> extends DijkstraGraphSearch { - - @Override - public Result search(Graph graph, V src, V dst, - EdgeWeight weight, int maxPaths) { - - if (weight == null) { - weight = edge -> 1; - } - - List> dpps = new ArrayList<>(); - - final EdgeWeight weightf = weight; - DefaultResult firstDijkstraS = (DefaultResult) super.search(graph, src, dst, weight, ALL_PATHS); - DefaultResult firstDijkstra = (DefaultResult) super.search(graph, src, null, weight, ALL_PATHS); - - //choose an arbitrary shortest path to run Suurballe on - Path shortPath = null; - if (firstDijkstraS.paths().size() == 0) { - return firstDijkstraS; - } - for (Path p: firstDijkstraS.paths()) { - shortPath = p; - //transforms the graph so tree edges have 0 weight - EdgeWeight> modified = edge -> { - if (classE().isInstance(edge)) { - return weightf.weight((E) (edge)) + firstDijkstra.cost(edge.src()) - - firstDijkstra.cost(edge.dst()); - } - return 0; - }; - EdgeWeight modified2 = edge -> - weightf.weight(edge) + firstDijkstra.cost(edge.src()) - firstDijkstra.cost(edge.dst()); - - //create a residual graph g' by removing all src vertices and reversing 0 length path edges - MutableGraph> gt = mutableCopy(graph); - - Map, E> revToEdge = new HashMap<>(); - graph.getEdgesTo(src).forEach(gt::removeEdge); - for (E edge: shortPath.edges()) { - gt.removeEdge(edge); - Edge reverse = new Edge() { - final Edge orig = edge; - public V src() { - return orig.dst(); - } - public V dst() { - return orig.src(); - } - public String toString() { - return "ReversedEdge " + "src=" + src() + " dst=" + dst(); - } - }; - revToEdge.put(reverse, edge); - gt.addEdge(reverse); - } - - //rerun dijkstra on the temporary graph to get a second path - Result> secondDijkstra; - secondDijkstra = new DijkstraGraphSearch>().search(gt, src, dst, modified, ALL_PATHS); - - Path> residualShortPath = null; - if (secondDijkstra.paths().size() == 0) { - dpps.add(new DisjointPathPair(shortPath, null)); - continue; - } - - for (Path p2: secondDijkstra.paths()) { - residualShortPath = p2; - - MutableGraph roundTrip = mutableCopy(graph); - - List tmp = roundTrip.getEdges().stream().collect(Collectors.toList()); - - tmp.forEach(roundTrip::removeEdge); - - shortPath.edges().forEach(roundTrip::addEdge); - - if (residualShortPath != null) { - for (Edge edge: residualShortPath.edges()) { - if (classE().isInstance(edge)) { - roundTrip.addEdge((E) edge); - } else { - roundTrip.removeEdge(revToEdge.get(edge)); - } - } - } - //Actually build the final result - DefaultResult lastSearch = (DefaultResult) super.search(roundTrip, src, dst, weight, ALL_PATHS); - Path path1 = lastSearch.paths().iterator().next(); - path1.edges().forEach(roundTrip::removeEdge); - - Set> bckpaths = super.search(roundTrip, src, dst, weight, ALL_PATHS).paths(); - Path backup = null; - if (bckpaths.size() != 0) { - backup = bckpaths.iterator().next(); - } - - dpps.add(new DisjointPathPair<>(path1, backup)); - } - } - - for (int i = dpps.size() - 1; i > 0; i--) { - if (dpps.get(i).size() <= 1) { - dpps.remove(i); - } - } - - return new Result() { - final DefaultResult search = firstDijkstra; - - public V src() { - return src; - } - public V dst() { - return dst; - } - public Set> paths() { - Set> pathsD = new HashSet<>(); - int paths = 0; - for (DisjointPathPair path: dpps) { - pathsD.add((Path) path); - paths++; - if (paths == maxPaths) { - break; - } - } - return pathsD; - } - public Map costs() { - return search.costs(); - } - public Map> parents() { - return search.parents(); - } - }; - } - - private Class clazzV; - - public Class classV() { - return clazzV; - } - - private Class clazzE; - - public Class classE() { - return clazzE; - } - /** - * Creates a mutable copy of an immutable graph. - * - * @param graph immutable graph - * @return mutable copy - */ - public MutableGraph mutableCopy(Graph graph) { - clazzV = graph.getVertexes().iterator().next().getClass(); - clazzE = graph.getEdges().iterator().next().getClass(); - return new MutableAdjacencyListsGraph(graph.getVertexes(), graph.getEdges()); - } -} - diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/TarjanGraphSearch.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/TarjanGraphSearch.java deleted file mode 100644 index 1c436d94..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/TarjanGraphSearch.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Tarjan algorithm for searching a graph and producing results describing - * the graph SCC (strongly-connected components). - */ -public class TarjanGraphSearch> - implements GraphSearch { - - /** - * {@inheritDoc} - *

- * This implementation produces results augmented with information on - * SCCs within the graph. - *

- *

- * To prevent traversal of an edge, the {@link EdgeWeight#weight} should - * return a negative value as an edge weight. - *

- */ - @Override - public SccResult search(Graph graph, EdgeWeight weight) { - SccResult result = new SccResult<>(graph); - for (V vertex : graph.getVertexes()) { - VertexData data = result.data(vertex); - if (data == null) { - connect(graph, vertex, weight, result); - } - } - return result.build(); - } - - /** - * Scans the specified graph, using recursion, and produces SCC results. - * - * @param graph graph to search - * @param vertex current vertex to scan and connect - * @param weight optional edge weight - * @param result graph search result - * @return augmentation vertexData for the current vertex - */ - private VertexData connect(Graph graph, V vertex, - EdgeWeight weight, - SccResult result) { - VertexData data = result.addData(vertex); - - // Scan through all egress edges of the current vertex. - for (E edge : graph.getEdgesFrom(vertex)) { - V nextVertex = edge.dst(); - - // If edge weight is negative, skip it. - if (weight != null && weight.weight(edge) < 0) { - continue; - } - - // Attempt to get the augmentation vertexData for the next vertex. - VertexData nextData = result.data(nextVertex); - if (nextData == null) { - // Next vertex has not been visited yet, so do this now. - nextData = connect(graph, nextVertex, weight, result); - data.lowLink = Math.min(data.lowLink, nextData.lowLink); - - } else if (result.visited(nextData)) { - // Next vertex has been visited, which means it is in the - // same cluster as the current vertex. - data.lowLink = Math.min(data.lowLink, nextData.index); - } - } - - if (data.lowLink == data.index) { - result.addCluster(data); - } - return data; - } - - /** - * Graph search result augmented with SCC vertexData. - */ - public static final class SccResult> - implements Result { - - private final Graph graph; - private List> clusterVertexes = new ArrayList<>(); - private List> clusterEdges = new ArrayList<>(); - - private int index = 0; - private final Map> vertexData = new HashMap<>(); - private final List> visited = new ArrayList<>(); - - private SccResult(Graph graph) { - this.graph = graph; - } - - /** - * Returns the number of SCC clusters in the graph. - * - * @return number of clusters - */ - public int clusterCount() { - return clusterEdges.size(); - } - - /** - * Returns the list of strongly connected vertex clusters. - * - * @return list of strongly connected vertex sets - */ - public List> clusterVertexes() { - return clusterVertexes; - } - - /** - * Returns the list of edges linking strongly connected vertex clusters. - * - * @return list of strongly connected edge sets - */ - public List> clusterEdges() { - return clusterEdges; - } - - // Gets the augmentation vertexData for the specified vertex - private VertexData data(V vertex) { - return vertexData.get(vertex); - } - - // Adds augmentation vertexData for the specified vertex - private VertexData addData(V vertex) { - VertexData d = new VertexData<>(vertex, index); - vertexData.put(vertex, d); - visited.add(0, d); - index++; - return d; - } - - // Indicates whether the given vertex has been visited - private boolean visited(VertexData data) { - return visited.contains(data); - } - - // Adds a new cluster for the specified vertex - private void addCluster(VertexData data) { - Set vertexes = findClusterVertices(data); - clusterVertexes.add(vertexes); - clusterEdges.add(findClusterEdges(vertexes)); - } - - private Set findClusterVertices(VertexData data) { - VertexData nextVertexData; - Set vertexes = new HashSet<>(); - do { - nextVertexData = visited.remove(0); - vertexes.add(nextVertexData.vertex); - } while (data != nextVertexData); - return Collections.unmodifiableSet(vertexes); - } - - private Set findClusterEdges(Set vertexes) { - Set edges = new HashSet<>(); - for (V vertex : vertexes) { - for (E edge : graph.getEdgesFrom(vertex)) { - if (vertexes.contains((edge.dst()))) { - edges.add(edge); - } - } - } - return Collections.unmodifiableSet(edges); - } - - public SccResult build() { - clusterVertexes = Collections.unmodifiableList(clusterVertexes); - clusterEdges = Collections.unmodifiableList(clusterEdges); - return this; - } - } - - // Augments the vertex to assist in determining SCC clusters. - private static final class VertexData { - final V vertex; - int index; - int lowLink; - - private VertexData(V vertex, int index) { - this.vertex = vertex; - this.index = index; - this.lowLink = index; - } - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Vertex.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Vertex.java deleted file mode 100644 index 80e3e7df..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/Vertex.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.graph; - -/** - * Representation of a graph vertex. - */ -public interface Vertex { -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/package-info.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/package-info.java deleted file mode 100644 index 2ee949d2..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/graph/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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. - */ - -/** - * Graph abstractions and graph path finding algorithms. - */ -package org.onlab.graph; diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/EventMetric.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/EventMetric.java deleted file mode 100644 index d20ca53f..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/EventMetric.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.metrics; - -import com.codahale.metrics.Gauge; -import com.codahale.metrics.Meter; - -/** - * Metric measurements for events. - */ -public class EventMetric { - private static final String GAUGE_TIMESTAMP_NAME = "Timestamp.EpochMs"; - private static final String METER_RATE_NAME = "Rate"; - - private final MetricsService metricsService; - private final String componentName; - private final String featureName; - - private MetricsComponent metricsComponent; - private MetricsFeature metricsFeature; - - private volatile long lastEventTimestampEpochMs = 0; - private Gauge lastEventTimestampGauge; - private Meter eventRateMeter; - - /** - * Constructor. - * - * @param metricsService the Metrics Service to use for Metrics - * registration and deregistration - * @param componentName the Metrics Component Name to use for Metrics - * registration and deregistration - * @param featureName the Metrics Feature Name to use for Metrics - * registration and deregistration - */ - public EventMetric(MetricsService metricsService, String componentName, - String featureName) { - this.metricsService = metricsService; - this.componentName = componentName; - this.featureName = featureName; - } - - /** - * Registers the metrics. - */ - public void registerMetrics() { - metricsComponent = metricsService.registerComponent(componentName); - metricsFeature = metricsComponent.registerFeature(featureName); - - lastEventTimestampEpochMs = 0; - lastEventTimestampGauge = - metricsService.registerMetric(metricsComponent, - metricsFeature, - GAUGE_TIMESTAMP_NAME, - new Gauge() { - @Override - public Long getValue() { - return lastEventTimestampEpochMs; - } - }); - - eventRateMeter = metricsService.createMeter(metricsComponent, - metricsFeature, - METER_RATE_NAME); - } - - /** - * Removes the metrics. - */ - public void removeMetrics() { - lastEventTimestampEpochMs = 0; - metricsService.removeMetric(metricsComponent, - metricsFeature, - GAUGE_TIMESTAMP_NAME); - metricsService.removeMetric(metricsComponent, - metricsFeature, - METER_RATE_NAME); - } - - /** - * Updates the metric measurements for a single event. - */ - public void eventReceived() { - lastEventTimestampEpochMs = System.currentTimeMillis(); - eventRateMeter.mark(1); - } - - /** - * Gets the last event timestamp Gauge (ms from the Epoch). - * - * @return the last event timestamp Gauge (ms from the Epoch) - */ - public Gauge lastEventTimestampGauge() { - return lastEventTimestampGauge; - } - - /** - * Gets the event rate meter. - * - * @return the event rate meter - */ - public Meter eventRateMeter() { - return eventRateMeter; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsComponent.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsComponent.java deleted file mode 100644 index cc8fe83c..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsComponent.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.metrics; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * Components to register for metrics. - */ -public class MetricsComponent implements MetricsComponentRegistry { - private final String name; - - /** - * Registry to hold the Features defined in this Component. - */ - private final ConcurrentMap featuresRegistry = - new ConcurrentHashMap<>(); - - /** - * Constructs a component from a name. - * - * @param newName name of the component - */ - MetricsComponent(final String newName) { - name = newName; - } - - @Override - public String getName() { - return name; - } - - @Override - public MetricsFeature registerFeature(final String featureName) { - MetricsFeature feature = featuresRegistry.get(featureName); - if (feature == null) { - final MetricsFeature createdFeature = - new MetricsFeature(featureName); - feature = featuresRegistry.putIfAbsent(featureName, createdFeature); - if (feature == null) { - feature = createdFeature; - } - } - return feature; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsComponentRegistry.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsComponentRegistry.java deleted file mode 100644 index 89f6ec5e..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsComponentRegistry.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.metrics; - -/** - * Registry Entry for Metrics Components. - */ -public interface MetricsComponentRegistry { - /** - * Fetches the name of the Component. - * - * @return name of the Component - */ - String getName(); - - /** - * Registers a Feature for this component. - * - * @param featureName name of the Feature to register - * @return Feature object that can be used when creating Metrics - */ - MetricsFeature registerFeature(String featureName); -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsFeature.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsFeature.java deleted file mode 100644 index bc6753c9..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsFeature.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.metrics; - -/** - * Features to tag metrics. - */ -public class MetricsFeature { - private final String name; - - /** - * Constructs a Feature from a name. - * - * @param newName name of the Feature - */ - public MetricsFeature(final String newName) { - name = newName; - } - - /** - * Fetches the name of the Feature. - * - * @return name of the Feature - */ - public String getName() { - return name; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsManager.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsManager.java deleted file mode 100644 index 6c9314ad..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsManager.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.metrics; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import com.codahale.metrics.Counter; -import com.codahale.metrics.Gauge; -import com.codahale.metrics.Histogram; -import com.codahale.metrics.Meter; -import com.codahale.metrics.Metric; -import com.codahale.metrics.MetricFilter; -import com.codahale.metrics.MetricRegistry; -import com.codahale.metrics.Timer; - -/** - * This class holds the Metrics registry for ONOS. - * All metrics (Counter, Histogram, Timer, Meter, Gauge) use a hierarchical - * string-based naming scheme: COMPONENT.FEATURE.NAME. - * Example: "Topology.Counters.TopologyUpdates". - * The COMPONENT and FEATURE names have to be registered in advance before - * a metric can be created. Example: - *
- *   
- *     private final MetricsManager.MetricsComponent COMPONENT =
- *         MetricsManager.registerComponent("Topology");
- *     private final MetricsManager.MetricsFeature FEATURE =
- *         COMPONENT.registerFeature("Counters");
- *     private final Counter counterTopologyUpdates =
- *         MetricsManager.createCounter(COMPONENT, FEATURE, "TopologyUpdates");
- *   
- * 
- * Gauges are slightly different because they are not created directly in - * this class, but are allocated by the caller and passed in for registration: - *
- *   
- *     private final Gauge<Long> gauge =
- *         new {@literal Gauge<Long>}() {
- *             {@literal @}Override
- *             public Long getValue() {
- *                 return gaugeValue;
- *             }
- *         };
- *     MetricsManager.registerMetric(COMPONENT, FEATURE, GAUGE_NAME, gauge);
- *   
- * 
- */ -public class MetricsManager implements MetricsService { - - /** - * Registry to hold the Components defined in the system. - */ - private ConcurrentMap componentsRegistry = - new ConcurrentHashMap<>(); - - /** - * Registry for the Metrics objects created in the system. - */ - private MetricRegistry metricsRegistry = new MetricRegistry(); - - /** - * Clears the internal state. - */ - protected void clear() { - this.componentsRegistry = new ConcurrentHashMap<>(); - this.metricsRegistry = new MetricRegistry(); - } - - /** - * Registers a component. - * - * @param name name of the Component to register - * @return MetricsComponent object that can be used to create Metrics. - */ - @Override - public MetricsComponent registerComponent(final String name) { - MetricsComponent component = componentsRegistry.get(name); - if (component == null) { - final MetricsComponent createdComponent = - new MetricsComponent(name); - component = componentsRegistry.putIfAbsent(name, createdComponent); - if (component == null) { - component = createdComponent; - } - } - return component; - } - - /** - * Generates a name for a Metric from its component and feature. - * - * @param component component the metric is defined in - * @param feature feature the metric is defined in - * @param metricName local name of the metric - * - * @return full name of the metric - */ - private String generateName(final MetricsComponent component, - final MetricsFeature feature, - final String metricName) { - return MetricRegistry.name(component.getName(), - feature.getName(), - metricName); - } - - /** - * Creates a Counter metric. - * - * @param component component the Counter is defined in - * @param feature feature the Counter is defined in - * @param metricName local name of the metric - * @return the created Counter Meteric - */ - @Override - public Counter createCounter(final MetricsComponent component, - final MetricsFeature feature, - final String metricName) { - final String name = generateName(component, feature, metricName); - return metricsRegistry.counter(name); - } - - /** - * Creates a Histogram metric. - * - * @param component component the Histogram is defined in - * @param feature feature the Histogram is defined in - * @param metricName local name of the metric - * @return the created Histogram Metric - */ - @Override - public Histogram createHistogram(final MetricsComponent component, - final MetricsFeature feature, - final String metricName) { - final String name = generateName(component, feature, metricName); - return metricsRegistry.histogram(name); - } - - /** - * Creates a Timer metric. - * - * @param component component the Timer is defined in - * @param feature feature the Timer is defined in - * @param metricName local name of the metric - * @return the created Timer Metric - */ - @Override - public Timer createTimer(final MetricsComponent component, - final MetricsFeature feature, - final String metricName) { - final String name = generateName(component, feature, metricName); - return metricsRegistry.timer(name); - } - - /** - * Creates a Meter metric. - * - * @param component component the Meter is defined in - * @param feature feature the Meter is defined in - * @param metricName local name of the metric - * @return the created Meter Metric - */ - @Override - public Meter createMeter(final MetricsComponent component, - final MetricsFeature feature, - final String metricName) { - final String name = generateName(component, feature, metricName); - return metricsRegistry.meter(name); - } - - /** - * Registers an already created Metric. This is used for situation where a - * caller needs to allocate its own Metric, but still register it with the - * system. - * - * @param Metric type - * @param component component the Metric is defined in - * @param feature feature the Metric is defined in - * @param metricName local name of the metric - * @param metric Metric to register - * @return the registered Metric - */ - @Override - public T registerMetric( - final MetricsComponent component, - final MetricsFeature feature, - final String metricName, - final T metric) { - final String name = generateName(component, feature, metricName); - metricsRegistry.register(name, metric); - return metric; - } - - /** - * Removes the metric with the given name. - * - * @param component component the Metric is defined in - * @param feature feature the Metric is defined in - * @param metricName local name of the metric - * @return true if the metric existed and was removed, otherwise false - */ - @Override - public boolean removeMetric(final MetricsComponent component, - final MetricsFeature feature, - final String metricName) { - final String name = generateName(component, feature, metricName); - return metricsRegistry.remove(name); - } - - /** - * Fetches the existing Timers. - * - * @param filter filter to use to select Timers - * @return a map of the Timers that match the filter, with the key as the - * name String to the Timer. - */ - @Override - public Map getTimers(final MetricFilter filter) { - return metricsRegistry.getTimers(filter); - } - - /** - * Fetches the existing Gauges. - * - * @param filter filter to use to select Gauges - * @return a map of the Gauges that match the filter, with the key as the - * name String to the Gauge. - */ - @Override - public Map getGauges(final MetricFilter filter) { - return metricsRegistry.getGauges(filter); - } - - /** - * Fetches the existing Counters. - * - * @param filter filter to use to select Counters - * @return a map of the Counters that match the filter, with the key as the - * name String to the Counter. - */ - @Override - public Map getCounters(final MetricFilter filter) { - return metricsRegistry.getCounters(filter); - } - - /** - * Fetches the existing Meters. - * - * @param filter filter to use to select Meters - * @return a map of the Meters that match the filter, with the key as the - * name String to the Meter. - */ - @Override - public Map getMeters(final MetricFilter filter) { - return metricsRegistry.getMeters(filter); - } - - /** - * Fetches the existing Histograms. - * - * @param filter filter to use to select Histograms - * @return a map of the Histograms that match the filter, with the key as - * the name String to the Histogram. - */ - @Override - public Map getHistograms(final MetricFilter filter) { - return metricsRegistry.getHistograms(filter); - } - - /** - * Removes all Metrics that match a given filter. - * - * @param filter filter to use to select the Metrics to remove. - */ - @Override - public void removeMatching(final MetricFilter filter) { - metricsRegistry.removeMatching(filter); - } - - /** - * Fetches the existing Meters. - * - * - * @return a map of all metrics with the key as the - * name String to the Meter. - */ - public Map getMetrics() { - return metricsRegistry.getMetrics(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsService.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsService.java deleted file mode 100644 index 4f0d67a8..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsService.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.metrics; - -import java.util.Map; - -import com.codahale.metrics.Counter; -import com.codahale.metrics.Gauge; -import com.codahale.metrics.Histogram; -import com.codahale.metrics.Meter; -import com.codahale.metrics.Metric; -import com.codahale.metrics.MetricFilter; -import com.codahale.metrics.Timer; - -/** - * Metrics Service to collect metrics. - */ -public interface MetricsService { - - /** - * Registers a component. - * - * @param name name of the Component to register - * @return MetricsComponent object that can be used to create Metrics. - */ - MetricsComponent registerComponent(String name); - - /** - * Creates a Counter metric. - * - * @param component component the Counter is defined in - * @param feature feature the Counter is defined in - * @param metricName local name of the metric - * @return the created Counter Meteric - */ - Counter createCounter(MetricsComponent component, - MetricsFeature feature, - String metricName); - - /** - * Creates a Histogram metric. - * - * @param component component the Histogram is defined in - * @param feature feature the Histogram is defined in - * @param metricName local name of the metric - * @return the created Histogram Metric - */ - Histogram createHistogram(MetricsComponent component, - MetricsFeature feature, - String metricName); - - /** - * Creates a Timer metric. - * - * @param component component the Timer is defined in - * @param feature feature the Timer is defined in - * @param metricName local name of the metric - * @return the created Timer Metric - */ - Timer createTimer(MetricsComponent component, - MetricsFeature feature, - String metricName); - - /** - * Creates a Meter metric. - * - * @param component component the Meter is defined in - * @param feature feature the Meter is defined in - * @param metricName local name of the metric - * @return the created Meter Metric - */ - Meter createMeter(MetricsComponent component, - MetricsFeature feature, - String metricName); - - /** - * Registers an already created Metric. This is used for situation where a - * caller needs to allocate its own Metric, but still register it with the - * system. - * - * @param Metric type - * @param component component the Metric is defined in - * @param feature feature the Metric is defined in - * @param metricName local name of the metric - * @param metric Metric to register - * @return the registered Metric - */ - T registerMetric( - MetricsComponent component, - MetricsFeature feature, - String metricName, - T metric); - - /** - * Removes the metric with the given name. - * - * @param component component the Metric is defined in - * @param feature feature the Metric is defined in - * @param metricName local name of the metric - * @return true if the metric existed and was removed, otherwise false - */ - boolean removeMetric(MetricsComponent component, - MetricsFeature feature, - String metricName); - - /** - * Fetches the existing Timers. - * - * @param filter filter to use to select Timers - * @return a map of the Timers that match the filter, with the key as the - * name String to the Timer. - */ - Map getTimers(MetricFilter filter); - - /** - * Fetches the existing Gauges. - * - * @param filter filter to use to select Gauges - * @return a map of the Gauges that match the filter, with the key as the - * name String to the Gauge. - */ - Map getGauges(MetricFilter filter); - - /** - * Fetches the existing Counters. - * - * @param filter filter to use to select Counters - * @return a map of the Counters that match the filter, with the key as the - * name String to the Counter. - */ - Map getCounters(MetricFilter filter); - - /** - * Fetches the existing Meters. - * - * @param filter filter to use to select Meters - * @return a map of the Meters that match the filter, with the key as the - * name String to the Meter. - */ - Map getMeters(MetricFilter filter); - - /** - * Fetches the existing Histograms. - * - * @param filter filter to use to select Histograms - * @return a map of the Histograms that match the filter, with the key as - * the name String to the Histogram. - */ - Map getHistograms(MetricFilter filter); - - /** - * Fetches the existing metrics. - * - * @return a map of the Metrics, with the key as - * the name String to the Histogram. - */ - Map getMetrics(); - - /** - * Removes all Metrics that match a given filter. - * - * @param filter filter to use to select the Metrics to remove. - */ - void removeMatching(MetricFilter filter); -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsUtil.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsUtil.java deleted file mode 100644 index cab6c0ea..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/MetricsUtil.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.metrics; - -import com.codahale.metrics.Timer; -import com.codahale.metrics.Timer.Context; - -public final class MetricsUtil { - - /** - * Starts the Metric Timer. - *

- * If the given timer was null, it will silently return null. - *

- * - * @param timer timer to start - * @return timing context, if timer was not null - */ - public static Context startTimer(Timer timer) { - if (timer != null) { - return timer.time(); - } - return null; - } - - /** - * Stops the Metric Timer context. - *

- * If the given context was null, it will silently be ignored. - *

- * - * @param context timing context to stop, if not null. - */ - public static void stopTimer(Context context) { - if (context != null) { - context.stop(); - } - } - - // avoid instantiation - private MetricsUtil() {} -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/package-info.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/package-info.java deleted file mode 100644 index 0a61f353..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/metrics/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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. - */ - -/** - * Misc utils for various performance metrics. - */ -package org.onlab.metrics; diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ARP.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ARP.java deleted file mode 100644 index dc3c07f1..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ARP.java +++ /dev/null @@ -1,439 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -import static org.onlab.packet.PacketUtils.*; - -/** - * - * - */ -public class ARP extends BasePacket { - public static final short HW_TYPE_ETHERNET = 0x1; - - public static final short PROTO_TYPE_IP = 0x800; - - public static final short OP_REQUEST = 0x1; - public static final short OP_REPLY = 0x2; - public static final short OP_RARP_REQUEST = 0x3; - public static final short OP_RARP_REPLY = 0x4; - - public static final short INITIAL_HEADER_LENGTH = 8; - - protected short hardwareType; - protected short protocolType; - protected byte hardwareAddressLength; - protected byte protocolAddressLength; - protected short opCode; - protected byte[] senderHardwareAddress; - protected byte[] senderProtocolAddress; - protected byte[] targetHardwareAddress; - protected byte[] targetProtocolAddress; - - /** - * @return the hardwareType - */ - public short getHardwareType() { - return this.hardwareType; - } - - /** - * @param hwType - * the hardwareType to set - * @return this - */ - public ARP setHardwareType(final short hwType) { - this.hardwareType = hwType; - return this; - } - - /** - * @return the protocolType - */ - public short getProtocolType() { - return this.protocolType; - } - - /** - * @param protoType - * the protocolType to set - * @return this - */ - public ARP setProtocolType(final short protoType) { - this.protocolType = protoType; - return this; - } - - /** - * @return the hardwareAddressLength - */ - public byte getHardwareAddressLength() { - return this.hardwareAddressLength; - } - - /** - * @param hwAddressLength - * the hardwareAddressLength to set - * @return this - */ - public ARP setHardwareAddressLength(final byte hwAddressLength) { - this.hardwareAddressLength = hwAddressLength; - return this; - } - - /** - * @return the protocolAddressLength - */ - public byte getProtocolAddressLength() { - return this.protocolAddressLength; - } - - /** - * @param protoAddressLength - * the protocolAddressLength to set - * @return this - */ - public ARP setProtocolAddressLength(final byte protoAddressLength) { - this.protocolAddressLength = protoAddressLength; - return this; - } - - /** - * @return the opCode - */ - public short getOpCode() { - return this.opCode; - } - - /** - * @param op - * the opCode to set - * @return this - */ - public ARP setOpCode(final short op) { - this.opCode = op; - return this; - } - - /** - * @return the senderHardwareAddress - */ - public byte[] getSenderHardwareAddress() { - return this.senderHardwareAddress; - } - - /** - * @param senderHWAddress - * the senderHardwareAddress to set - * @return this - */ - public ARP setSenderHardwareAddress(final byte[] senderHWAddress) { - this.senderHardwareAddress = senderHWAddress; - return this; - } - - /** - * @return the senderProtocolAddress - */ - public byte[] getSenderProtocolAddress() { - return this.senderProtocolAddress; - } - - /** - * @param senderProtoAddress - * the senderProtocolAddress to set - * @return this - */ - public ARP setSenderProtocolAddress(final byte[] senderProtoAddress) { - this.senderProtocolAddress = senderProtoAddress; - return this; - } - - public ARP setSenderProtocolAddress(final int address) { - this.senderProtocolAddress = ByteBuffer.allocate(4).putInt(address) - .array(); - return this; - } - - /** - * @return the targetHardwareAddress - */ - public byte[] getTargetHardwareAddress() { - return this.targetHardwareAddress; - } - - /** - * @param targetHWAddress - * the targetHardwareAddress to set - * @return this - */ - public ARP setTargetHardwareAddress(final byte[] targetHWAddress) { - this.targetHardwareAddress = targetHWAddress; - return this; - } - - /** - * @return the targetProtocolAddress - */ - public byte[] getTargetProtocolAddress() { - return this.targetProtocolAddress; - } - - /** - * @return True if gratuitous ARP (SPA = TPA), false otherwise - */ - public boolean isGratuitous() { - assert this.senderProtocolAddress.length == this.targetProtocolAddress.length; - - int indx = 0; - while (indx < this.senderProtocolAddress.length) { - if (this.senderProtocolAddress[indx] != this.targetProtocolAddress[indx]) { - return false; - } - indx++; - } - - return true; - } - - /** - * @param targetProtoAddress - * the targetProtocolAddress to set - * @return this - */ - public ARP setTargetProtocolAddress(final byte[] targetProtoAddress) { - this.targetProtocolAddress = targetProtoAddress; - return this; - } - - public ARP setTargetProtocolAddress(final int address) { - this.targetProtocolAddress = ByteBuffer.allocate(4).putInt(address) - .array(); - return this; - } - - @Override - public byte[] serialize() { - final int length = 8 + 2 * (0xff & this.hardwareAddressLength) + 2 - * (0xff & this.protocolAddressLength); - final byte[] data = new byte[length]; - final ByteBuffer bb = ByteBuffer.wrap(data); - bb.putShort(this.hardwareType); - bb.putShort(this.protocolType); - bb.put(this.hardwareAddressLength); - bb.put(this.protocolAddressLength); - bb.putShort(this.opCode); - bb.put(this.senderHardwareAddress, 0, 0xff & this.hardwareAddressLength); - bb.put(this.senderProtocolAddress, 0, 0xff & this.protocolAddressLength); - bb.put(this.targetHardwareAddress, 0, 0xff & this.hardwareAddressLength); - bb.put(this.targetProtocolAddress, 0, 0xff & this.protocolAddressLength); - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.hardwareType = bb.getShort(); - this.protocolType = bb.getShort(); - this.hardwareAddressLength = bb.get(); - this.protocolAddressLength = bb.get(); - this.opCode = bb.getShort(); - this.senderHardwareAddress = new byte[0xff & this.hardwareAddressLength]; - bb.get(this.senderHardwareAddress, 0, this.senderHardwareAddress.length); - this.senderProtocolAddress = new byte[0xff & this.protocolAddressLength]; - bb.get(this.senderProtocolAddress, 0, this.senderProtocolAddress.length); - this.targetHardwareAddress = new byte[0xff & this.hardwareAddressLength]; - bb.get(this.targetHardwareAddress, 0, this.targetHardwareAddress.length); - this.targetProtocolAddress = new byte[0xff & this.protocolAddressLength]; - bb.get(this.targetProtocolAddress, 0, this.targetProtocolAddress.length); - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 13121; - int result = super.hashCode(); - result = prime * result + this.hardwareAddressLength; - result = prime * result + this.hardwareType; - result = prime * result + this.opCode; - result = prime * result + this.protocolAddressLength; - result = prime * result + this.protocolType; - result = prime * result + Arrays.hashCode(this.senderHardwareAddress); - result = prime * result + Arrays.hashCode(this.senderProtocolAddress); - result = prime * result + Arrays.hashCode(this.targetHardwareAddress); - result = prime * result + Arrays.hashCode(this.targetProtocolAddress); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof ARP)) { - return false; - } - final ARP other = (ARP) obj; - if (this.hardwareAddressLength != other.hardwareAddressLength) { - return false; - } - if (this.hardwareType != other.hardwareType) { - return false; - } - if (this.opCode != other.opCode) { - return false; - } - if (this.protocolAddressLength != other.protocolAddressLength) { - return false; - } - if (this.protocolType != other.protocolType) { - return false; - } - if (!Arrays.equals(this.senderHardwareAddress, - other.senderHardwareAddress)) { - return false; - } - if (!Arrays.equals(this.senderProtocolAddress, - other.senderProtocolAddress)) { - return false; - } - if (!Arrays.equals(this.targetHardwareAddress, - other.targetHardwareAddress)) { - return false; - } - if (!Arrays.equals(this.targetProtocolAddress, - other.targetProtocolAddress)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "ARP [hardwareType=" + this.hardwareType + ", protocolType=" - + this.protocolType + ", hardwareAddressLength=" - + this.hardwareAddressLength + ", protocolAddressLength=" - + this.protocolAddressLength + ", opCode=" + this.opCode - + ", senderHardwareAddress=" - + Arrays.toString(this.senderHardwareAddress) - + ", senderProtocolAddress=" - + Arrays.toString(this.senderProtocolAddress) - + ", targetHardwareAddress=" - + Arrays.toString(this.targetHardwareAddress) - + ", targetProtocolAddress=" - + Arrays.toString(this.targetProtocolAddress) + "]"; - } - - /** - * Builds an ARP reply based on a request. - * - * @param srcIp the IP address to use as the reply source - * @param srcMac the MAC address to use as the reply source - * @param request the ARP request we got - * @return an Ethernet frame containing the ARP reply - */ - public static Ethernet buildArpReply(Ip4Address srcIp, MacAddress srcMac, - Ethernet request) { - - Ethernet eth = new Ethernet(); - eth.setDestinationMACAddress(request.getSourceMAC()); - eth.setSourceMACAddress(srcMac); - eth.setEtherType(Ethernet.TYPE_ARP); - eth.setVlanID(request.getVlanID()); - - ARP arp = new ARP(); - arp.setOpCode(ARP.OP_REPLY); - arp.setProtocolType(ARP.PROTO_TYPE_IP); - arp.setHardwareType(ARP.HW_TYPE_ETHERNET); - - arp.setProtocolAddressLength((byte) Ip4Address.BYTE_LENGTH); - arp.setHardwareAddressLength((byte) Ethernet.DATALAYER_ADDRESS_LENGTH); - arp.setSenderHardwareAddress(srcMac.toBytes()); - arp.setTargetHardwareAddress(request.getSourceMACAddress()); - - arp.setTargetProtocolAddress(((ARP) request.getPayload()) - .getSenderProtocolAddress()); - arp.setSenderProtocolAddress(srcIp.toInt()); - - eth.setPayload(arp); - return eth; - } - - /** - * Deserializer function for ARP packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, INITIAL_HEADER_LENGTH); - - ARP arp = new ARP(); - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - arp.setHardwareType(bb.getShort()); - arp.setProtocolType(bb.getShort()); - - byte hwAddressLength = bb.get(); - arp.setHardwareAddressLength(hwAddressLength); - - byte protocolAddressLength = bb.get(); - arp.setProtocolAddressLength(protocolAddressLength); - arp.setOpCode(bb.getShort()); - - // Check we have enough space for the addresses - checkHeaderLength(length, INITIAL_HEADER_LENGTH + - 2 * hwAddressLength + - 2 * protocolAddressLength); - - arp.senderHardwareAddress = new byte[0xff & hwAddressLength]; - bb.get(arp.senderHardwareAddress, 0, arp.senderHardwareAddress.length); - arp.senderProtocolAddress = new byte[0xff & protocolAddressLength]; - bb.get(arp.senderProtocolAddress, 0, arp.senderProtocolAddress.length); - arp.targetHardwareAddress = new byte[0xff & hwAddressLength]; - bb.get(arp.targetHardwareAddress, 0, arp.targetHardwareAddress.length); - arp.targetProtocolAddress = new byte[0xff & protocolAddressLength]; - bb.get(arp.targetProtocolAddress, 0, arp.targetProtocolAddress.length); - - return arp; - }; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/BasePacket.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/BasePacket.java deleted file mode 100644 index 4aece66f..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/BasePacket.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -/** - * - * - */ -public abstract class BasePacket implements IPacket { - protected IPacket parent; - protected IPacket payload; - - /** - * @return the parent - */ - @Override - public IPacket getParent() { - return this.parent; - } - - /** - * @param parent - * the parent to set - */ - @Override - public IPacket setParent(final IPacket parent) { - this.parent = parent; - return this; - } - - /** - * @return the payload - */ - @Override - public IPacket getPayload() { - return this.payload; - } - - /** - * @param payload - * the payload to set - */ - @Override - public IPacket setPayload(final IPacket payload) { - this.payload = payload; - return this; - } - - @Override - public void resetChecksum() { - if (this.parent != null) { - this.parent.resetChecksum(); - } - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 6733; - int result = 1; - result = prime * result - + (this.payload == null ? 0 : this.payload.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof BasePacket)) { - return false; - } - final BasePacket other = (BasePacket) obj; - if (this.payload == null) { - if (other.payload != null) { - return false; - } - } else if (!this.payload.equals(other.payload)) { - return false; - } - return true; - } - - @Override - public Object clone() { - IPacket pkt; - try { - pkt = this.getClass().newInstance(); - } catch (final Exception e) { - throw new RuntimeException("Could not clone packet"); - } - - final byte[] data = this.serialize(); - pkt.deserialize(this.serialize(), 0, data.length); - pkt.setParent(this.parent); - return pkt; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ChassisId.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ChassisId.java deleted file mode 100644 index 23c9859f..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ChassisId.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -/** - * The class representing a network device chassisId. - * This class is immutable. - */ -public final class ChassisId { - - private static final long UNKNOWN = 0; - private final long value; - - /** - * Default constructor. - */ - public ChassisId() { - this.value = ChassisId.UNKNOWN; - } - - /** - * Constructor from a long value. - * - * @param value the value to use. - */ - public ChassisId(long value) { - this.value = value; - } - - /** - * Constructor from a string. - * - * @param value the value to use. - */ - public ChassisId(String value) { - this.value = Long.parseLong(value, 16); - } - - /** - * Get the value of the chassis id. - * - * @return the value of the chassis id. - */ - public long value() { - return value; - } - - /** - * Convert the Chassis Id value to a ':' separated hexadecimal string. - * - * @return the Chassis Id value as a ':' separated hexadecimal string. - */ - @Override - public String toString() { - return Long.toHexString(this.value); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof ChassisId)) { - return false; - } - - ChassisId otherChassisId = (ChassisId) other; - - return value == otherChassisId.value; - } - - @Override - public int hashCode() { - return Long.hashCode(value); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCP.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCP.java deleted file mode 100644 index de5b43fa..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCP.java +++ /dev/null @@ -1,632 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; -import java.util.ListIterator; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * - */ -public class DHCP extends BasePacket { - /** - * Dynamic Host Configuration Protocol packet. - * ------------------------------------------ |op (1) | htype(1) | hlen(1) | - * hops(1) | ------------------------------------------ | xid (4) | - * ------------------------------------------ | secs (2) | flags (2) | - * ------------------------------------------ | ciaddr (4) | - * ------------------------------------------ | yiaddr (4) | - * ------------------------------------------ | siaddr (4) | - * ------------------------------------------ | giaddr (4) | - * ------------------------------------------ | chaddr (16) | - * ------------------------------------------ | sname (64) | - * ------------------------------------------ | file (128) | - * ------------------------------------------ | options (312) | - * ------------------------------------------ - * - */ - // Header + magic without options - public static final int MIN_HEADER_LENGTH = 240; - public static final byte OPCODE_REQUEST = 0x1; - public static final byte OPCODE_REPLY = 0x2; - - public static final byte HWTYPE_ETHERNET = 0x1; - - public enum DHCPOptionCode { - OptionCode_SubnetMask((byte) 1), OptionCode_RouterAddress((byte) 3), OptionCode_DomainServer((byte) 6), - OptionCode_HostName((byte) 12), OptionCode_DomainName((byte) 15), OptionCode_BroadcastAddress((byte) 28), - OptionCode_RequestedIP((byte) 50), OptionCode_LeaseTime((byte) 51), OptionCode_MessageType((byte) 53), - OptionCode_DHCPServerIp((byte) 54), OptionCode_RequestedParameters((byte) 55), - OptionCode_RenewalTime((byte) 58), OPtionCode_RebindingTime((byte) 59), OptionCode_ClientID((byte) 61), - OptionCode_END((byte) 255); - - protected byte value; - - private DHCPOptionCode(final byte value) { - this.value = value; - } - - public byte getValue() { - return this.value; - } - } - - protected byte opCode; - protected byte hardwareType; - protected byte hardwareAddressLength; - protected byte hops; - protected int transactionId; - protected short seconds; - protected short flags; - protected int clientIPAddress; - protected int yourIPAddress; - protected int serverIPAddress; - protected int gatewayIPAddress; - protected byte[] clientHardwareAddress; - protected String serverName; - protected String bootFileName; - protected List options = new ArrayList(); - - /** - * @return the opCode - */ - public byte getOpCode() { - return this.opCode; - } - - /** - * @param opCode - * the opCode to set - * @return this - */ - public DHCP setOpCode(final byte opCode) { - this.opCode = opCode; - return this; - } - - /** - * @return the hardwareType - */ - public byte getHardwareType() { - return this.hardwareType; - } - - /** - * @param hardwareType - * the hardwareType to set - * @return this - */ - public DHCP setHardwareType(final byte hardwareType) { - this.hardwareType = hardwareType; - return this; - } - - /** - * @return the hardwareAddressLength - */ - public byte getHardwareAddressLength() { - return this.hardwareAddressLength; - } - - /** - * @param hardwareAddressLength - * the hardwareAddressLength to set - * @return this - */ - public DHCP setHardwareAddressLength(final byte hardwareAddressLength) { - this.hardwareAddressLength = hardwareAddressLength; - return this; - } - - /** - * @return the hops - */ - public byte getHops() { - return this.hops; - } - - /** - * @param hops - * the hops to set - * @return this - */ - public DHCP setHops(final byte hops) { - this.hops = hops; - return this; - } - - /** - * @return the transactionId - */ - public int getTransactionId() { - return this.transactionId; - } - - /** - * @param transactionId - * the transactionId to set - * @return this - */ - public DHCP setTransactionId(final int transactionId) { - this.transactionId = transactionId; - return this; - } - - /** - * @return the seconds - */ - public short getSeconds() { - return this.seconds; - } - - /** - * @param seconds - * the seconds to set - * @return this - */ - public DHCP setSeconds(final short seconds) { - this.seconds = seconds; - return this; - } - - /** - * @return the flags - */ - public short getFlags() { - return this.flags; - } - - /** - * @param flags - * the flags to set - * @return this - */ - public DHCP setFlags(final short flags) { - this.flags = flags; - return this; - } - - /** - * @return the clientIPAddress - */ - public int getClientIPAddress() { - return this.clientIPAddress; - } - - /** - * @param clientIPAddress - * the clientIPAddress to set - * @return this - */ - public DHCP setClientIPAddress(final int clientIPAddress) { - this.clientIPAddress = clientIPAddress; - return this; - } - - /** - * @return the yourIPAddress - */ - public int getYourIPAddress() { - return this.yourIPAddress; - } - - /** - * @param yourIPAddress - * the yourIPAddress to set - * @return this - */ - public DHCP setYourIPAddress(final int yourIPAddress) { - this.yourIPAddress = yourIPAddress; - return this; - } - - /** - * @return the serverIPAddress - */ - public int getServerIPAddress() { - return this.serverIPAddress; - } - - /** - * @param serverIPAddress - * the serverIPAddress to set - * @return this - */ - public DHCP setServerIPAddress(final int serverIPAddress) { - this.serverIPAddress = serverIPAddress; - return this; - } - - /** - * @return the gatewayIPAddress - */ - public int getGatewayIPAddress() { - return this.gatewayIPAddress; - } - - /** - * @param gatewayIPAddress - * the gatewayIPAddress to set - * @return this - */ - public DHCP setGatewayIPAddress(final int gatewayIPAddress) { - this.gatewayIPAddress = gatewayIPAddress; - return this; - } - - /** - * @return the clientHardwareAddress - */ - public byte[] getClientHardwareAddress() { - return this.clientHardwareAddress; - } - - /** - * @param clientHardwareAddress - * the clientHardwareAddress to set - * @return this - */ - public DHCP setClientHardwareAddress(final byte[] clientHardwareAddress) { - this.clientHardwareAddress = clientHardwareAddress; - return this; - } - - /** - * Gets a specific DHCP option parameter. - * - * @param optionCode - * The option code to get - * @return The value of the option if it exists, null otherwise - */ - public DHCPOption getOption(final DHCPOptionCode optionCode) { - for (final DHCPOption opt : this.options) { - if (opt.code == optionCode.value) { - return opt; - } - } - return null; - } - - /** - * @return the options - */ - public List getOptions() { - return this.options; - } - - /** - * @param options - * the options to set - * @return this - */ - public DHCP setOptions(final List options) { - this.options = options; - return this; - } - - /** - * @return the packetType base on option 53 - */ - public DHCPPacketType getPacketType() { - final ListIterator lit = this.options.listIterator(); - while (lit.hasNext()) { - final DHCPOption option = lit.next(); - // only care option 53 - if (option.getCode() == 53) { - return DHCPPacketType.getType(option.getData()[0]); - } - } - return null; - } - - /** - * @return the serverName - */ - public String getServerName() { - return this.serverName; - } - - /** - * @param server - * the serverName to set - * @return this - */ - public DHCP setServerName(final String server) { - this.serverName = server; - return this; - } - - /** - * @return the bootFileName - */ - public String getBootFileName() { - return this.bootFileName; - } - - /** - * @param bootFile - * the bootFileName to set - * @return this - */ - public DHCP setBootFileName(final String bootFile) { - this.bootFileName = bootFile; - return this; - } - - @Override - public byte[] serialize() { - // not guaranteed to retain length/exact format - this.resetChecksum(); - - // minimum size 240 including magic cookie, options generally padded to - // 300 - int optionsLength = 0; - for (final DHCPOption option : this.options) { - if (option.getCode() == 0 || option.getCode() == ((byte) 255)) { - optionsLength += 1; - } else { - optionsLength += 2 + (0xff & option.getLength()); - } - } - int optionsPadLength = 0; - if (optionsLength < 60) { - optionsPadLength = 60 - optionsLength; - } - - final byte[] data = new byte[240 + optionsLength + optionsPadLength]; - final ByteBuffer bb = ByteBuffer.wrap(data); - bb.put(this.opCode); - bb.put(this.hardwareType); - bb.put(this.hardwareAddressLength); - bb.put(this.hops); - bb.putInt(this.transactionId); - bb.putShort(this.seconds); - bb.putShort(this.flags); - bb.putInt(this.clientIPAddress); - bb.putInt(this.yourIPAddress); - bb.putInt(this.serverIPAddress); - bb.putInt(this.gatewayIPAddress); - checkArgument(this.clientHardwareAddress.length <= 16, - "Hardware address is too long (%s bytes)", this.clientHardwareAddress.length); - bb.put(this.clientHardwareAddress); - if (this.clientHardwareAddress.length < 16) { - for (int i = 0; i < 16 - this.clientHardwareAddress.length; ++i) { - bb.put((byte) 0x0); - } - } - this.writeString(this.serverName, bb, 64); - this.writeString(this.bootFileName, bb, 128); - // magic cookie - bb.put((byte) 0x63); - bb.put((byte) 0x82); - bb.put((byte) 0x53); - bb.put((byte) 0x63); - for (final DHCPOption option : this.options) { - final int code = option.getCode() & 0xff; - bb.put((byte) code); - if (code != 0 && code != 255) { - bb.put(option.getLength()); - bb.put(option.getData()); - } - } - // assume the rest is padded out with zeroes - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - if (bb.remaining() < DHCP.MIN_HEADER_LENGTH) { - return this; - } - - this.opCode = bb.get(); - this.hardwareType = bb.get(); - this.hardwareAddressLength = bb.get(); - this.hops = bb.get(); - this.transactionId = bb.getInt(); - this.seconds = bb.getShort(); - this.flags = bb.getShort(); - this.clientIPAddress = bb.getInt(); - this.yourIPAddress = bb.getInt(); - this.serverIPAddress = bb.getInt(); - this.gatewayIPAddress = bb.getInt(); - final int hardwareAddressLength = 0xff & this.hardwareAddressLength; - this.clientHardwareAddress = new byte[hardwareAddressLength]; - - bb.get(this.clientHardwareAddress); - for (int i = hardwareAddressLength; i < 16; ++i) { - bb.get(); - } - this.serverName = this.readString(bb, 64); - this.bootFileName = this.readString(bb, 128); - // read the magic cookie - // magic cookie - bb.get(); - bb.get(); - bb.get(); - bb.get(); - // read options - while (bb.hasRemaining()) { - final DHCPOption option = new DHCPOption(); - int code = 0xff & bb.get(); // convert signed byte to int in range - // [0,255] - option.setCode((byte) code); - if (code == 0) { - // skip these - continue; - } else if (code != 255) { - if (bb.hasRemaining()) { - final int l = 0xff & bb.get(); // convert signed byte to - // int in range [0,255] - option.setLength((byte) l); - if (bb.remaining() >= l) { - final byte[] optionData = new byte[l]; - bb.get(optionData); - option.setData(optionData); - } else { - // Skip the invalid option and set the END option - code = 0xff; - option.setCode((byte) code); - option.setLength((byte) 0); - } - } else { - // Skip the invalid option and set the END option - code = 0xff; - option.setCode((byte) code); - option.setLength((byte) 0); - } - } - this.options.add(option); - if (code == 255) { - // remaining bytes are supposed to be 0, but ignore them just in - // case - break; - } - } - - return this; - } - - protected void writeString(final String string, final ByteBuffer bb, - final int maxLength) { - if (string == null) { - for (int i = 0; i < maxLength; ++i) { - bb.put((byte) 0x0); - } - } else { - byte[] bytes = null; - try { - bytes = string.getBytes("ascii"); - } catch (final UnsupportedEncodingException e) { - throw new RuntimeException("Failure encoding server name", e); - } - int writeLength = bytes.length; - if (writeLength > maxLength) { - writeLength = maxLength; - } - bb.put(bytes, 0, writeLength); - for (int i = writeLength; i < maxLength; ++i) { - bb.put((byte) 0x0); - } - } - } - - private static String readString(final ByteBuffer bb, final int maxLength) { - final byte[] bytes = new byte[maxLength]; - bb.get(bytes); - String result = null; - try { - result = new String(bytes, "ascii").trim(); - } catch (final UnsupportedEncodingException e) { - throw new RuntimeException("Failure decoding string", e); - } - return result; - } - - /** - * Deserializer function for DHCP packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, MIN_HEADER_LENGTH); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - DHCP dhcp = new DHCP(); - - dhcp.opCode = bb.get(); - dhcp.hardwareType = bb.get(); - dhcp.hardwareAddressLength = bb.get(); - dhcp.hops = bb.get(); - dhcp.transactionId = bb.getInt(); - dhcp.seconds = bb.getShort(); - dhcp.flags = bb.getShort(); - dhcp.clientIPAddress = bb.getInt(); - dhcp.yourIPAddress = bb.getInt(); - dhcp.serverIPAddress = bb.getInt(); - dhcp.gatewayIPAddress = bb.getInt(); - final int hardwareAddressLength = 0xff & dhcp.hardwareAddressLength; - dhcp.clientHardwareAddress = new byte[hardwareAddressLength]; - - bb.get(dhcp.clientHardwareAddress); - for (int i = hardwareAddressLength; i < 16; ++i) { - bb.get(); - } - dhcp.serverName = readString(bb, 64); - dhcp.bootFileName = readString(bb, 128); - // read the magic cookie - // magic cookie - bb.get(); - bb.get(); - bb.get(); - bb.get(); - - // read options - boolean foundEndOptionsMarker = false; - while (bb.hasRemaining()) { - final DHCPOption option = new DHCPOption(); - int code = 0xff & bb.get(); // convert signed byte to int in range - // [0,255] - option.setCode((byte) code); - if (code == 0) { - // skip these - continue; - } else if (code != 255) { - if (bb.hasRemaining()) { - final int l = 0xff & bb.get(); // convert signed byte to - // int in range [0,255] - option.setLength((byte) l); - if (bb.remaining() >= l) { - final byte[] optionData = new byte[l]; - bb.get(optionData); - option.setData(optionData); - dhcp.options.add(option); - } else { - throw new DeserializationException( - "Buffer underflow while reading DHCP option"); - } - } - } else if (code == 255) { - DHCPOption end = new DHCPOption(); - end.setCode((byte) 255); - dhcp.options.add(end); - // remaining bytes are supposed to be 0, but ignore them just in - // case - foundEndOptionsMarker = true; - break; - } - } - - if (!foundEndOptionsMarker) { - throw new DeserializationException("DHCP End options marker was missing"); - } - - return dhcp; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCPOption.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCPOption.java deleted file mode 100644 index 1b6c670e..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCPOption.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.util.Arrays; - -/** - * - */ -public class DHCPOption { - protected byte code; - protected byte length; - protected byte[] data; - - /** - * @return the code - */ - public byte getCode() { - return this.code; - } - - /** - * @param code - * the code to set - * @return this - */ - public DHCPOption setCode(final byte code) { - this.code = code; - return this; - } - - /** - * @return the length - */ - public byte getLength() { - return this.length; - } - - /** - * @param length - * the length to set - * @return this - */ - public DHCPOption setLength(final byte length) { - this.length = length; - return this; - } - - /** - * @return the data - */ - public byte[] getData() { - return this.data; - } - - /** - * @param data - * the data to set - * @return this - */ - public DHCPOption setData(final byte[] data) { - this.data = data; - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + this.code; - result = prime * result + Arrays.hashCode(this.data); - result = prime * result + this.length; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof DHCPOption)) { - return false; - } - final DHCPOption other = (DHCPOption) obj; - if (this.code != other.code) { - return false; - } - if (!Arrays.equals(this.data, other.data)) { - return false; - } - if (this.length != other.length) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "DHCPOption [code=" + this.code + ", length=" + this.length - + ", data=" + Arrays.toString(this.data) + "]"; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCPPacketType.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCPPacketType.java deleted file mode 100644 index 8254c770..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DHCPPacketType.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -public enum DHCPPacketType { - // From RFC 1533 - DHCPDISCOVER(1), DHCPOFFER(2), DHCPREQUEST(3), DHCPDECLINE(4), DHCPACK(5), DHCPNAK( - 6), DHCPRELEASE(7), - - // From RFC2132 - DHCPINFORM(8), - - // From RFC3203 - DHCPFORCERENEW(9), - - // From RFC4388 - DHCPLEASEQUERY(10), DHCPLEASEUNASSIGNED(11), DHCPLEASEUNKNOWN(12), DHCPLEASEACTIVE( - 13); - - protected int value; - - private DHCPPacketType(final int value) { - this.value = value; - } - - public int getValue() { - return this.value; - } - - @Override - public String toString() { - switch (this.value) { - case 1: - return "DHCPDISCOVER"; - case 2: - return "DHCPOFFER"; - case 3: - return "DHCPREQUEST"; - case 4: - return "DHCPDECLINE"; - case 5: - return "DHCPACK"; - case 6: - return "DHCPNAK"; - case 7: - return "DHCPRELEASE"; - case 8: - return "DHCPINFORM"; - case 9: - return "DHCPFORCERENEW"; - case 10: - return "DHCPLEASEQUERY"; - case 11: - return "DHCPLEASEUNASSIGNED"; - case 12: - return "DHCPLEASEUNKNOWN"; - case 13: - return "DHCPLEASEACTIVE"; - default: - break; - } - - return null; - } - - public static DHCPPacketType getType(final int value) { - switch (value) { - case 1: - return DHCPDISCOVER; - case 2: - return DHCPOFFER; - case 3: - return DHCPREQUEST; - case 4: - return DHCPDECLINE; - case 5: - return DHCPACK; - case 6: - return DHCPNAK; - case 7: - return DHCPRELEASE; - case 8: - return DHCPINFORM; - case 9: - return DHCPFORCERENEW; - case 10: - return DHCPLEASEQUERY; - case 11: - return DHCPLEASEUNASSIGNED; - case 12: - return DHCPLEASEUNKNOWN; - case 13: - return DHCPLEASEACTIVE; - default: - break; - } - - return null; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Data.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Data.java deleted file mode 100644 index 79abcba1..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Data.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.util.Arrays; - -import static org.onlab.packet.PacketUtils.*; - -/** - * - */ -public class Data extends BasePacket { - protected byte[] data; - - /** - * - */ - public Data() { - data = new byte[0]; - } - - /** - * @param data the data - */ - public Data(final byte[] data) { - this.data = data; - } - - /** - * @return the data - */ - public byte[] getData() { - return this.data; - } - - /** - * @param data - * the data to set - * @return self - */ - public Data setData(final byte[] data) { - this.data = data; - return this; - } - - @Override - public byte[] serialize() { - return this.data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - this.data = Arrays.copyOfRange(data, offset, data.length); - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 1571; - int result = super.hashCode(); - result = prime * result + Arrays.hashCode(this.data); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof Data)) { - return false; - } - final Data other = (Data) obj; - if (!Arrays.equals(this.data, other.data)) { - return false; - } - return true; - } - - /** - * Deserializer function for generic payload data. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - // Allow zero-length data for now - if (length == 0) { - return new Data(); - } - - checkInput(data, offset, length, 1); - - Data dataObject = new Data(); - - dataObject.data = Arrays.copyOfRange(data, offset, data.length); - - return dataObject; - }; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DeserializationException.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DeserializationException.java deleted file mode 100644 index 03a8aa35..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/DeserializationException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet; - -/** - * Signals that an error occurred during deserialization of a packet. - */ -public class DeserializationException extends Exception { - - /** - * Creates a new deserialization exception with the given message. - * - * @param message exception message - */ - public DeserializationException(String message) { - super(message); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Deserializer.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Deserializer.java deleted file mode 100644 index e0ef381b..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Deserializer.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet; - -/** - * Function to deserialize a packet from a byte-based input stream. - */ -@FunctionalInterface -public interface Deserializer { - - /** - * Deserialize a packet object from a byte array. - * - * @param data input array to take packet bytes from - * @param offset index where this packet header begins in the byte array - * @param length length of the packet header - * @return a deserialized packet object - * @throws DeserializationException if the packet cannot be deserialized - * from the input - */ - U deserialize(byte[] data, int offset, int length) throws DeserializationException; -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EAP.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EAP.java deleted file mode 100644 index 516938a4..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EAP.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * - * * Copyright 2015 AT&T Foundry - * * - * * 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.onlab.packet; - -import java.nio.ByteBuffer; - -import static org.onlab.packet.PacketUtils.checkHeaderLength; -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * EAP (Extensible Authentication Protocol) packet. - */ -public class EAP extends BasePacket { - private static final int HEADER_LENGTH = 4; - - public static final short MIN_LEN = 0x4; - public static final short EAP_HDR_LEN_REQ_RESP = 5; - public static final short EAP_HDR_LEN_SUC_FAIL = 4; - - // EAP Code - public static final byte REQUEST = 0x1; - public static final byte RESPONSE = 0x2; - public static final byte SUCCESS = 0x3; - public static final byte FAILURE = 0x4; - - // EAP Attribute Type - public static final byte ATTR_IDENTITY = 0x1; - public static final byte ATTR_NOTIFICATION = 0x2; - public static final byte ATTR_NAK = 0x3; - public static final byte ATTR_MD5 = 0x4; - public static final byte ATTR_OTP = 0x5; - public static final byte ATTR_GTC = 0x6; - public static final byte ATTR_TLS = 0xd; - - protected byte code; - protected byte identifier; - protected short length; - protected byte type; - protected byte[] data; - - - /** - * Gets the EAP code. - * - * @return EAP code - */ - public byte getCode() { - return this.code; - } - - - /** - * Sets the EAP code. - * - * @param code EAP code - * @return this - */ - public EAP setCode(final byte code) { - this.code = code; - return this; - } - - /** - * Gets the EAP identifier. - * - * @return EAP identifier - */ - public byte getIdentifier() { - return this.identifier; - } - - /** - * Sets the EAP identifier. - * - * @param identifier EAP identifier - * @return this - */ - public EAP setIdentifier(final byte identifier) { - this.identifier = identifier; - return this; - } - - /** - * Gets the get packet length. - * - * @return packet length - */ - public short getLength() { - return this.length; - } - - /** - * Sets the packet length. - * - * @param length packet length - * @return this - */ - public EAP setLength(final short length) { - this.length = length; - return this; - } - - /** - * Gets the data type. - * - * @return data type - */ - public byte getDataType() { - return this.type; - } - - /** - * Sets the data type. - * - * @param type data type - * @return this - */ - public EAP setDataType(final byte type) { - this.type = type; - return this; - } - - /** - * Gets the EAP data. - * - * @return EAP data - */ - public byte[] getData() { - return this.data; - } - - /** - * Sets the EAP data. - * - * @param data EAP data to be set - * @return this - */ - public EAP setData(final byte[] data) { - this.data = data; - return this; - } - - /** - * Default EAP constructor that sets the EAP code to 0. - */ - public EAP() { - this.code = 0; - } - - /** - * EAP constructor that initially sets all fields. - * - * @param code EAP code - * @param identifier EAP identifier - * @param type packet type - * @param data EAP data - */ - public EAP(byte code, byte identifier, byte type, byte[] data) { - this.code = code; - this.identifier = identifier; - if (this.code == REQUEST || this.code == RESPONSE) { - this.length = (short) (5 + (data == null ? 0 : data.length)); - this.type = type; - } else { - this.length = (short) (4 + (data == null ? 0 : data.length)); - } - this.data = data; - } - - /** - * Deserializer for EAP packets. - * - * @return deserializer - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, HEADER_LENGTH); - - EAP eap = new EAP(); - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - eap.code = bb.get(); - eap.identifier = bb.get(); - eap.length = bb.getShort(); - - checkHeaderLength(length, eap.length); - - int dataLength; - if (eap.code == REQUEST || eap.code == RESPONSE) { - eap.type = bb.get(); - dataLength = eap.length - 5; - } else { - dataLength = eap.length - 4; - } - - eap.data = new byte[dataLength]; - bb.get(eap.data); - return eap; - }; - } - - @Override - public byte[] serialize() { - final byte[] data = new byte[this.length]; - - final ByteBuffer bb = ByteBuffer.wrap(data); - bb.put(this.code); - bb.put(this.identifier); - bb.putShort(this.length); - if (this.code == REQUEST || this.code == RESPONSE) { - bb.put(this.type); - } - if (this.data != null) { - bb.put(this.data); - } - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.code = bb.get(); - this.identifier = bb.get(); - this.length = bb.getShort(); - - int dataLength; - if (this.code == REQUEST || this.code == RESPONSE) { - this.type = bb.get(); - dataLength = this.length - 5; - } else { - dataLength = this.length - 4; - } - this.data = new byte[dataLength]; - bb.get(this.data); - return this; - } - - @Override - public int hashCode() { - final int prime = 3889; - int result = super.hashCode(); - result = prime * result + this.code; - result = prime * result + this.identifier; - result = prime * result + this.length; - result = prime * result + this.type; - return result; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EAPOL.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EAPOL.java deleted file mode 100644 index 1820cc31..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EAPOL.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * - * * Copyright 2015 AT&T Foundry - * * - * * 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.onlab.packet; - -import java.nio.ByteBuffer; - -import static org.onlab.packet.PacketUtils.checkHeaderLength; -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * EAPOL (Extensible Authentication Protocol over LAN) header. - */ -public class EAPOL extends BasePacket { - - private byte version = 0x01; - private byte eapolType; - private short packetLength; - - private static final int HEADER_LENGTH = 4; - - // EAPOL Packet Type - public static final byte EAPOL_PACKET = 0x0; - public static final byte EAPOL_START = 0x1; - public static final byte EAPOL_LOGOFF = 0x2; - public static final byte EAPOL_KEY = 0x3; - public static final byte EAPOL_ASF = 0x4; - - public static final MacAddress PAE_GROUP_ADDR = MacAddress.valueOf(new byte[] { - (byte) 0x01, (byte) 0x80, (byte) 0xc2, (byte) 0x00, (byte) 0x00, (byte) 0x03 - }); - - /** - * Gets the version. - * - * @return version - */ - public byte getVersion() { - return this.version; - } - - /** - * Sets the version. - * - * @param version EAPOL version - * @return this - */ - public EAPOL setVersion(final byte version) { - this.version = version; - return this; - } - - /** - * Gets the type. - * - * @return EAPOL type - */ - public byte getEapolType() { - return this.eapolType; - } - - /** - * Sets the EAPOL type. - * - * @param eapolType EAPOL type - * @return this - */ - public EAPOL setEapolType(final byte eapolType) { - this.eapolType = eapolType; - return this; - } - - /** - * Gets the packet length. - * - * @return packet length - */ - public short getPacketLength() { - return this.packetLength; - } - - /** - * Sets the packet length. - * - * @param packetLen packet length - * @return this - */ - public EAPOL setPacketLength(final short packetLen) { - this.packetLength = packetLen; - return this; - } - - /** - * Serializes the packet, based on the code/type using the payload - * to compute its length. - * - * @return this - */ - @Override - public byte[] serialize() { - byte[] payloadData = null; - - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - - // prepare the buffer to hold the version (1), packet type (1), - // packet length (2) and the eap payload. - // if there is no payload, packet length is 0 - byte[] data = new byte[4 + this.packetLength]; - final ByteBuffer bb = ByteBuffer.wrap(data); - bb.put(this.version); - bb.put(this.eapolType); - bb.putShort(this.packetLength); - - // put the EAP payload - if (payloadData != null) { - bb.put(payloadData); - } - - return data; - } - - @Override - public int hashCode() { - final int prime = 3889; - int result = super.hashCode(); - result = prime * result + this.version; - result = prime * result + this.eapolType; - result = prime * result + this.packetLength; - return result; - } - - /** - * Deserializer for EAPOL packets. - * - * @return deserializer - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, HEADER_LENGTH); - - EAPOL eapol = new EAPOL(); - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - eapol.setVersion(bb.get()); - eapol.setEapolType(bb.get()); - eapol.setPacketLength(bb.getShort()); - - if (eapol.packetLength > 0) { - checkHeaderLength(length, HEADER_LENGTH + eapol.packetLength); - // deserialize the EAP Payload - eapol.payload = EAP.deserializer().deserialize(data, - bb.position(), bb.limit() - bb.position()); - - eapol.payload.setParent(eapol); - } - - return eapol; - }; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - - // deserialize the EAPOL header - this.version = bb.get(); - this.eapolType = bb.get(); - this.packetLength = bb.getShort(); - - if (this.packetLength > 0) { - // deserialize the EAP Payload - this.payload = new EAP(); - - this.payload = this.payload.deserialize(data, bb.position(), length - 4); - this.payload.setParent(this); - } - - return this; - } -} - diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EthType.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EthType.java deleted file mode 100644 index b3b79e2c..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/EthType.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet; - -/** - * Representation of an Ethertype. - */ -public class EthType { - - /** - * A list of known ethertypes. Adding a fully defined enum here will - * associated the ethertype with a textual representation and a parsing - * class. - */ - public enum EtherType { - - ARP(0x806, "arp", org.onlab.packet.ARP.deserializer()), - RARP(0x8035, "rarp", org.onlab.packet.ARP.deserializer()), - IPV4(0x800, "ipv4", org.onlab.packet.IPv4.deserializer()), - IPV6(0x86dd, "ipv6", org.onlab.packet.IPv6.deserializer()), - LLDP(0x88cc, "lldp", org.onlab.packet.LLDP.deserializer()), - VLAN(0x8100, "vlan", null), - BDDP(0x8942, "bddp", org.onlab.packet.LLDP.deserializer()), - MPLS_UNICAST(0x8847, "mpls_unicast", org.onlab.packet.MPLS.deserializer()), - MPLS_MULTICAST(0x8848, "mpls_unicast", org.onlab.packet.MPLS.deserializer()), - EAPOL(0x888e, "eapol", org.onlab.packet.EAPOL.deserializer()), - UNKNOWN(0, "unknown", null); - - - private final EthType etherType; - private final String type; - private final Deserializer deserializer; - - /** - * Constructs a new ethertype. - * - * @param ethType The actual ethertype - * @param type it's textual representation - * @param deserializer a parser for this ethertype - */ - EtherType(int ethType, String type, Deserializer deserializer) { - this.etherType = new EthType(ethType); - this.type = type; - this.deserializer = deserializer; - } - - public EthType ethType() { - return etherType; - } - - @Override - public String toString() { - return type; - } - - public Deserializer deserializer() { - return deserializer; - } - - public static EtherType lookup(short etherType) { - for (EtherType ethType : EtherType.values()) { - if (ethType.ethType().toShort() == etherType) { - return ethType; - } - } - return UNKNOWN; - } - - } - - - private final short etherType; - - /** - * Builds the EthType. - * - * @param etherType an integer representing an ethtype - */ - public EthType(int etherType) { - this.etherType = (short) (etherType & 0xFFFF); - } - - /** - * Builds the EthType. - * - * @param etherType a short representing the ethtype - */ - public EthType(short etherType) { - this.etherType = etherType; - } - - /** - * Returns the short value for this ethtype. - * - * @return a short value - */ - public short toShort() { - return etherType; - } - - /** - * Looks up the ethertype by it's numerical representation - * and returns it's textual format. - * - * @param etherType the short value of the ethertype - * @return a textual representation - */ - public EtherType lookup(short etherType) { - for (EtherType ethType : EtherType.values()) { - if (ethType.ethType().toShort() == etherType) { - return ethType; - } - } - return null; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - EthType ethType = (EthType) o; - - if (etherType != ethType.etherType) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - return (int) etherType; - } - - public String toString() { - EtherType ethType = lookup(this.etherType); - return (ethType == null ? String.format("0x%04x", etherType) : - ethType.toString()); - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ethernet.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ethernet.java deleted file mode 100644 index 9ab5cab1..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ethernet.java +++ /dev/null @@ -1,718 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import org.onlab.packet.ndp.NeighborAdvertisement; -import org.onlab.packet.ndp.NeighborSolicitation; -import org.onlab.packet.ndp.Redirect; -import org.onlab.packet.ndp.RouterAdvertisement; -import org.onlab.packet.ndp.RouterSolicitation; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.onlab.packet.PacketUtils.checkHeaderLength; -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * - */ -public class Ethernet extends BasePacket { - private static final String HEXES = "0123456789ABCDEF"; - - public static final short TYPE_ARP = EthType.EtherType.ARP.ethType().toShort(); - public static final short TYPE_RARP = EthType.EtherType.RARP.ethType().toShort(); - public static final short TYPE_IPV4 = EthType.EtherType.IPV4.ethType().toShort(); - public static final short TYPE_IPV6 = EthType.EtherType.IPV6.ethType().toShort(); - public static final short TYPE_LLDP = EthType.EtherType.LLDP.ethType().toShort(); - public static final short TYPE_VLAN = EthType.EtherType.VLAN.ethType().toShort(); - public static final short TYPE_BSN = EthType.EtherType.BDDP.ethType().toShort(); - - public static final short MPLS_UNICAST = EthType.EtherType.MPLS_UNICAST.ethType().toShort();; - public static final short MPLS_MULTICAST = EthType.EtherType.MPLS_MULTICAST.ethType().toShort(); - - - public static final short VLAN_UNTAGGED = (short) 0xffff; - - public static final short ETHERNET_HEADER_LENGTH = 14; // bytes - public static final short VLAN_HEADER_LENGTH = 4; // bytes - - public static final short DATALAYER_ADDRESS_LENGTH = 6; // bytes - - private static final Map> ETHERTYPE_DESERIALIZER_MAP = - new HashMap<>(); - - static { - for (EthType.EtherType ethType : EthType.EtherType.values()) { - if (ethType.deserializer() != null) { - ETHERTYPE_DESERIALIZER_MAP.put(ethType.ethType().toShort(), ethType.deserializer()); - } - } - } - - protected MacAddress destinationMACAddress; - protected MacAddress sourceMACAddress; - protected byte priorityCode; - protected short vlanID; - protected short etherType; - protected boolean pad = false; - - /** - * By default, set Ethernet to untagged. - */ - public Ethernet() { - super(); - this.vlanID = Ethernet.VLAN_UNTAGGED; - } - - /** - * Gets the destination MAC address. - * - * @return the destination MAC as a byte array - */ - public byte[] getDestinationMACAddress() { - return this.destinationMACAddress.toBytes(); - } - - /** - * Gets the destination MAC address. - * - * @return the destination MAC - */ - public MacAddress getDestinationMAC() { - return this.destinationMACAddress; - } - - /** - * Sets the destination MAC address. - * - * @param destMac the destination MAC to set - * @return the Ethernet frame - */ - public Ethernet setDestinationMACAddress(final MacAddress destMac) { - this.destinationMACAddress = checkNotNull(destMac); - return this; - } - - /** - * Sets the destination MAC address. - * - * @param destMac the destination MAC to set - * @return the Ethernet frame - */ - public Ethernet setDestinationMACAddress(final byte[] destMac) { - this.destinationMACAddress = MacAddress.valueOf(destMac); - return this; - } - - /** - * Sets the destination MAC address. - * - * @param destMac the destination MAC to set - * @return the Ethernet frame - */ - public Ethernet setDestinationMACAddress(final String destMac) { - this.destinationMACAddress = MacAddress.valueOf(destMac); - return this; - } - - /** - * Gets the source MAC address. - * - * @return the source MACAddress as a byte array - */ - public byte[] getSourceMACAddress() { - return this.sourceMACAddress.toBytes(); - } - - /** - * Gets the source MAC address. - * - * @return the source MACAddress - */ - public MacAddress getSourceMAC() { - return this.sourceMACAddress; - } - - /** - * Sets the source MAC address. - * - * @param sourceMac the source MAC to set - * @return the Ethernet frame - */ - public Ethernet setSourceMACAddress(final MacAddress sourceMac) { - this.sourceMACAddress = checkNotNull(sourceMac); - return this; - } - - /** - * Sets the source MAC address. - * - * @param sourceMac the source MAC to set - * @return the Ethernet frame - */ - public Ethernet setSourceMACAddress(final byte[] sourceMac) { - this.sourceMACAddress = MacAddress.valueOf(sourceMac); - return this; - } - - /** - * Sets the source MAC address. - * - * @param sourceMac the source MAC to set - * @return the Ethernet frame - */ - public Ethernet setSourceMACAddress(final String sourceMac) { - this.sourceMACAddress = MacAddress.valueOf(sourceMac); - return this; - } - - /** - * Gets the priority code. - * - * @return the priorityCode - */ - public byte getPriorityCode() { - return this.priorityCode; - } - - /** - * Sets the priority code. - * - * @param priority the priorityCode to set - * @return the Ethernet frame - */ - public Ethernet setPriorityCode(final byte priority) { - this.priorityCode = priority; - return this; - } - - /** - * Gets the VLAN ID. - * - * @return the vlanID - */ - public short getVlanID() { - return this.vlanID; - } - - /** - * Sets the VLAN ID. - * - * @param vlan the vlanID to set - * @return the Ethernet frame - */ - public Ethernet setVlanID(final short vlan) { - this.vlanID = vlan; - return this; - } - - /** - * Gets the Ethernet type. - * - * @return the etherType - */ - public short getEtherType() { - return this.etherType; - } - - /** - * Sets the Ethernet type. - * - * @param ethType the etherType to set - * @return the Ethernet frame - */ - public Ethernet setEtherType(final short ethType) { - this.etherType = ethType; - return this; - } - - /** - * @return True if the Ethernet frame is broadcast, false otherwise - */ - public boolean isBroadcast() { - assert this.destinationMACAddress.length() == 6; - return this.destinationMACAddress.isBroadcast(); - } - - /** - * @return True is the Ethernet frame is multicast, False otherwise - */ - public boolean isMulticast() { - return this.destinationMACAddress.isMulticast(); - } - - /** - * Pad this packet to 60 bytes minimum, filling with zeros? - * - * @return the pad - */ - public boolean isPad() { - return this.pad; - } - - /** - * Pad this packet to 60 bytes minimum, filling with zeros? - * - * @param pd - * the pad to set - * @return this - */ - public Ethernet setPad(final boolean pd) { - this.pad = pd; - return this; - } - - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - int length = 14 + (this.vlanID == Ethernet.VLAN_UNTAGGED ? 0 : 4) - + (payloadData == null ? 0 : payloadData.length); - if (this.pad && length < 60) { - length = 60; - } - final byte[] data = new byte[length]; - final ByteBuffer bb = ByteBuffer.wrap(data); - bb.put(this.destinationMACAddress.toBytes()); - bb.put(this.sourceMACAddress.toBytes()); - if (this.vlanID != Ethernet.VLAN_UNTAGGED) { - bb.putShort(TYPE_VLAN); - bb.putShort((short) (this.priorityCode << 13 | this.vlanID & 0x0fff)); - } - bb.putShort(this.etherType); - if (payloadData != null) { - bb.put(payloadData); - } - if (this.pad) { - Arrays.fill(data, bb.position(), data.length, (byte) 0x0); - } - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - if (length <= 0) { - return null; - } - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - if (this.destinationMACAddress == null) { - this.destinationMACAddress = MacAddress.valueOf(new byte[6]); - } - final byte[] dstAddr = new byte[MacAddress.MAC_ADDRESS_LENGTH]; - bb.get(dstAddr); - this.destinationMACAddress = MacAddress.valueOf(dstAddr); - - if (this.sourceMACAddress == null) { - this.sourceMACAddress = MacAddress.valueOf(new byte[6]); - } - final byte[] srcAddr = new byte[MacAddress.MAC_ADDRESS_LENGTH]; - bb.get(srcAddr); - this.sourceMACAddress = MacAddress.valueOf(srcAddr); - - short ethType = bb.getShort(); - if (ethType == TYPE_VLAN) { - final short tci = bb.getShort(); - this.priorityCode = (byte) (tci >> 13 & 0x07); - this.vlanID = (short) (tci & 0x0fff); - ethType = bb.getShort(); - } else { - this.vlanID = Ethernet.VLAN_UNTAGGED; - } - this.etherType = ethType; - - IPacket payload; - Deserializer deserializer; - if (Ethernet.ETHERTYPE_DESERIALIZER_MAP.containsKey(ethType)) { - deserializer = Ethernet.ETHERTYPE_DESERIALIZER_MAP.get(ethType); - } else { - deserializer = Data.deserializer(); - } - try { - this.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - this.payload.setParent(this); - } catch (DeserializationException e) { - return this; - } - return this; - } - - /** - * Checks to see if a string is a valid MAC address. - * - * @param macAddress string to test if it is a valid MAC - * @return True if macAddress is a valid MAC, False otherwise - */ - public static boolean isMACAddress(final String macAddress) { - final String[] macBytes = macAddress.split(":"); - if (macBytes.length != 6) { - return false; - } - for (int i = 0; i < 6; ++i) { - if (Ethernet.HEXES.indexOf(macBytes[i].toUpperCase().charAt(0)) == -1 - || Ethernet.HEXES.indexOf(macBytes[i].toUpperCase().charAt( - 1)) == -1) { - return false; - } - } - return true; - } - - /** - * Accepts a MAC address of the form 00:aa:11:bb:22:cc, case does not - * matter, and returns a corresponding byte[]. - * - * @param macAddress - * The MAC address to convert into a byte array - * @return The macAddress as a byte array - */ - public static byte[] toMACAddress(final String macAddress) { - return MacAddress.valueOf(macAddress).toBytes(); - } - - /** - * Accepts a MAC address and returns the corresponding long, where the MAC - * bytes are set on the lower order bytes of the long. - * - * @param macAddress MAC address as a byte array - * @return a long containing the mac address bytes - */ - public static long toLong(final byte[] macAddress) { - return MacAddress.valueOf(macAddress).toLong(); - } - - /** - * Converts a long MAC address to a byte array. - * - * @param macAddress MAC address set on the lower order bytes of the long - * @return the bytes of the mac address - */ - public static byte[] toByteArray(final long macAddress) { - return MacAddress.valueOf(macAddress).toBytes(); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 7867; - int result = super.hashCode(); - result = prime * result + this.destinationMACAddress.hashCode(); - result = prime * result + this.etherType; - result = prime * result + this.vlanID; - result = prime * result + this.priorityCode; - result = prime * result + (this.pad ? 1231 : 1237); - result = prime * result + this.sourceMACAddress.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof Ethernet)) { - return false; - } - final Ethernet other = (Ethernet) obj; - if (!this.destinationMACAddress.equals(other.destinationMACAddress)) { - return false; - } - if (this.priorityCode != other.priorityCode) { - return false; - } - if (this.vlanID != other.vlanID) { - return false; - } - if (this.etherType != other.etherType) { - return false; - } - if (this.pad != other.pad) { - return false; - } - if (!this.sourceMACAddress.equals(other.sourceMACAddress)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString(java.lang.Object) - */ - @Override - public String toString() { - - final StringBuffer sb = new StringBuffer("\n"); - - final IPacket pkt = this.getPayload(); - - if (pkt instanceof ARP) { - sb.append("arp"); - } else if (pkt instanceof LLDP) { - sb.append("lldp"); - } else if (pkt instanceof ICMP) { - sb.append("icmp"); - } else if (pkt instanceof IPv4) { - sb.append("ip"); - } else if (pkt instanceof DHCP) { - sb.append("dhcp"); - } else { - sb.append(this.getEtherType()); - } - - sb.append("\ndl_vlan: "); - if (this.getVlanID() == Ethernet.VLAN_UNTAGGED) { - sb.append("untagged"); - } else { - sb.append(this.getVlanID()); - } - sb.append("\ndl_vlan_pcp: "); - sb.append(this.getPriorityCode()); - sb.append("\ndl_src: "); - sb.append(bytesToHex(this.getSourceMACAddress())); - sb.append("\ndl_dst: "); - sb.append(bytesToHex(this.getDestinationMACAddress())); - - if (pkt instanceof ARP) { - final ARP p = (ARP) pkt; - sb.append("\nnw_src: "); - sb.append(IPv4.fromIPv4Address(IPv4.toIPv4Address(p - .getSenderProtocolAddress()))); - sb.append("\nnw_dst: "); - sb.append(IPv4.fromIPv4Address(IPv4.toIPv4Address(p - .getTargetProtocolAddress()))); - } else if (pkt instanceof LLDP) { - sb.append("lldp packet"); - } else if (pkt instanceof ICMP) { - final ICMP icmp = (ICMP) pkt; - sb.append("\nicmp_type: "); - sb.append(icmp.getIcmpType()); - sb.append("\nicmp_code: "); - sb.append(icmp.getIcmpCode()); - } else if (pkt instanceof IPv4) { - final IPv4 p = (IPv4) pkt; - sb.append("\nnw_src: "); - sb.append(IPv4.fromIPv4Address(p.getSourceAddress())); - sb.append("\nnw_dst: "); - sb.append(IPv4.fromIPv4Address(p.getDestinationAddress())); - sb.append("\nnw_tos: "); - sb.append(p.getDiffServ()); - sb.append("\nnw_proto: "); - sb.append(p.getProtocol()); - - IPacket payload = pkt.getPayload(); - if (payload != null) { - if (payload instanceof TCP) { - sb.append("\ntp_src: "); - sb.append(((TCP) payload).getSourcePort()); - sb.append("\ntp_dst: "); - sb.append(((TCP) payload).getDestinationPort()); - - } else if (payload instanceof UDP) { - sb.append("\ntp_src: "); - sb.append(((UDP) payload).getSourcePort()); - sb.append("\ntp_dst: "); - sb.append(((UDP) payload).getDestinationPort()); - } else if (payload instanceof ICMP) { - final ICMP icmp = (ICMP) payload; - sb.append("\nicmp_type: "); - sb.append(icmp.getIcmpType()); - sb.append("\nicmp_code: "); - sb.append(icmp.getIcmpCode()); - } - } - } else if (pkt instanceof IPv6) { - final IPv6 ipv6 = (IPv6) pkt; - sb.append("\nipv6_src: "); - sb.append(Ip6Address.valueOf(ipv6.getSourceAddress()).toString()); - sb.append("\nipv6_dst: "); - sb.append(Ip6Address.valueOf(ipv6.getDestinationAddress()).toString()); - sb.append("\nipv6_proto: "); - sb.append(ipv6.getNextHeader()); - - IPacket payload = pkt.getPayload(); - if (payload != null && payload instanceof ICMP6) { - final ICMP6 icmp6 = (ICMP6) payload; - sb.append("\nicmp6_type: "); - sb.append(icmp6.getIcmpType()); - sb.append("\nicmp6_code: "); - sb.append(icmp6.getIcmpCode()); - - payload = payload.getPayload(); - if (payload != null) { - if (payload instanceof NeighborSolicitation) { - final NeighborSolicitation ns = (NeighborSolicitation) payload; - sb.append("\nns_target_addr: "); - sb.append(Ip6Address.valueOf(ns.getTargetAddress()).toString()); - ns.getOptions().forEach(option -> { - sb.append("\noption_type: "); - sb.append(option.type()); - sb.append("\noption_data: "); - sb.append(bytesToHex(option.data())); - }); - } else if (payload instanceof NeighborAdvertisement) { - final NeighborAdvertisement na = (NeighborAdvertisement) payload; - sb.append("\nna_target_addr: "); - sb.append(Ip6Address.valueOf(na.getTargetAddress()).toString()); - sb.append("\nna_solicited_flag: "); - sb.append(na.getSolicitedFlag()); - sb.append("\nna_router_flag: "); - sb.append(na.getRouterFlag()); - sb.append("\nna_override_flag: "); - sb.append(na.getOverrideFlag()); - na.getOptions().forEach(option -> { - sb.append("\noption_type: "); - sb.append(option.type()); - sb.append("\noption_data: "); - sb.append(bytesToHex(option.data())); - }); - } else if (payload instanceof RouterSolicitation) { - final RouterSolicitation rs = (RouterSolicitation) payload; - sb.append("\nrs"); - rs.getOptions().forEach(option -> { - sb.append("\noption_type: "); - sb.append(option.type()); - sb.append("\noption_data: "); - sb.append(bytesToHex(option.data())); - }); - } else if (payload instanceof RouterAdvertisement) { - final RouterAdvertisement ra = (RouterAdvertisement) payload; - sb.append("\nra_hop_limit: "); - sb.append(ra.getCurrentHopLimit()); - sb.append("\nra_mflag: "); - sb.append(ra.getMFlag()); - sb.append("\nra_oflag: "); - sb.append(ra.getOFlag()); - sb.append("\nra_reachable_time: "); - sb.append(ra.getReachableTime()); - sb.append("\nra_retransmit_time: "); - sb.append(ra.getRetransmitTimer()); - sb.append("\nra_router_lifetime: "); - sb.append(ra.getRouterLifetime()); - ra.getOptions().forEach(option -> { - sb.append("\noption_type: "); - sb.append(option.type()); - sb.append("\noption_data: "); - sb.append(bytesToHex(option.data())); - }); - } else if (payload instanceof Redirect) { - final Redirect rd = (Redirect) payload; - sb.append("\nrd_target_addr: "); - sb.append(Ip6Address.valueOf(rd.getTargetAddress()).toString()); - rd.getOptions().forEach(option -> { - sb.append("\noption_type: "); - sb.append(option.type()); - sb.append("\noption_data: "); - sb.append(bytesToHex(option.data())); - }); - } - } - } - } else if (pkt instanceof DHCP) { - sb.append("\ndhcp packet"); - } else if (pkt instanceof Data) { - sb.append("\ndata packet"); - } else if (pkt instanceof LLC) { - sb.append("\nllc packet"); - } else { - sb.append("\nunknown packet"); - } - - return sb.toString(); - } - - public static String bytesToHex(byte[] in) { - final StringBuilder builder = new StringBuilder(); - for (byte b : in) { - builder.append(String.format("%02x", b)); - } - return builder.toString(); - } - - /** - * Deserializer function for Ethernet packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, ETHERNET_HEADER_LENGTH); - - byte[] addressBuffer = new byte[DATALAYER_ADDRESS_LENGTH]; - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - Ethernet eth = new Ethernet(); - // Read destination MAC address into buffer - bb.get(addressBuffer); - eth.setDestinationMACAddress(addressBuffer); - - // Read source MAC address into buffer - bb.get(addressBuffer); - eth.setSourceMACAddress(addressBuffer); - - short ethType = bb.getShort(); - if (ethType == TYPE_VLAN) { - checkHeaderLength(length, ETHERNET_HEADER_LENGTH + VLAN_HEADER_LENGTH); - final short tci = bb.getShort(); - eth.setPriorityCode((byte) (tci >> 13 & 0x07)); - eth.setVlanID((short) (tci & 0x0fff)); - ethType = bb.getShort(); - } else { - eth.setVlanID(Ethernet.VLAN_UNTAGGED); - } - eth.setEtherType(ethType); - - IPacket payload; - Deserializer deserializer; - if (Ethernet.ETHERTYPE_DESERIALIZER_MAP.containsKey(ethType)) { - deserializer = Ethernet.ETHERTYPE_DESERIALIZER_MAP.get(ethType); - } else { - deserializer = Data.deserializer(); - } - payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - payload.setParent(eth); - eth.setPayload(payload); - - return eth; - }; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ICMP.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ICMP.java deleted file mode 100644 index d07a9ba4..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ICMP.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; - -import static org.onlab.packet.PacketUtils.*; - -/** - * Implements ICMP packet format. - * - */ -public class ICMP extends BasePacket { - protected byte icmpType; - protected byte icmpCode; - protected short checksum; - - public static final byte TYPE_ECHO_REQUEST = 0x08; - public static final byte TYPE_ECHO_REPLY = 0x00; - public static final byte SUBTYPE_ECHO_REPLY = 0x00; - - public static final short ICMP_HEADER_LENGTH = 4; - - /** - * @return the icmpType - */ - public byte getIcmpType() { - return this.icmpType; - } - - /** - * @param icmpType - * to set - * @return this - */ - public ICMP setIcmpType(final byte icmpType) { - this.icmpType = icmpType; - return this; - } - - /** - * @return the icmp code - */ - public byte getIcmpCode() { - return this.icmpCode; - } - - /** - * @param icmpCode - * code to set - * @return this - */ - public ICMP setIcmpCode(final byte icmpCode) { - this.icmpCode = icmpCode; - return this; - } - - /** - * @return the checksum - */ - public short getChecksum() { - return this.checksum; - } - - /** - * @param checksum - * the checksum to set - * @return this - */ - public ICMP setChecksum(final short checksum) { - this.checksum = checksum; - return this; - } - - /** - * Serializes the packet. Will compute and set the following fields if they - * are set to specific values at the time serialize is called: -checksum : 0 - * -length : 0 - */ - @Override - public byte[] serialize() { - int length = 4; - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - length += payloadData.length; - } - - final byte[] data = new byte[length]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.put(this.icmpType); - bb.put(this.icmpCode); - bb.putShort(this.checksum); - if (payloadData != null) { - bb.put(payloadData); - } - - if (this.parent != null && this.parent instanceof IPv4) { - ((IPv4) this.parent).setProtocol(IPv4.PROTOCOL_ICMP); - } - - // compute checksum if needed - if (this.checksum == 0) { - bb.rewind(); - int accumulation = 0; - - for (int i = 0; i < length / 2; ++i) { - accumulation += 0xffff & bb.getShort(); - } - // pad to an even number of shorts - if (length % 2 > 0) { - accumulation += (bb.get() & 0xff) << 8; - } - - accumulation = (accumulation >> 16 & 0xffff) - + (accumulation & 0xffff); - this.checksum = (short) (~accumulation & 0xffff); - bb.putShort(2, this.checksum); - } - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.icmpType = bb.get(); - this.icmpCode = bb.get(); - this.checksum = bb.getShort(); - - this.payload = new Data(); - this.payload = this.payload.deserialize(data, bb.position(), bb.limit() - - bb.position()); - this.payload.setParent(this); - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - result = prime * result + this.icmpType; - result = prime * result + this.icmpCode; - result = prime * result + this.checksum; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof ICMP)) { - return false; - } - final ICMP other = (ICMP) obj; - if (this.icmpType != other.icmpType) { - return false; - } - if (this.icmpCode != other.icmpCode) { - return false; - } - if (this.checksum != other.checksum) { - return false; - } - return true; - } - - /** - * Deserializer function for ICMP packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, ICMP_HEADER_LENGTH); - - ICMP icmp = new ICMP(); - - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - icmp.icmpType = bb.get(); - icmp.icmpCode = bb.get(); - icmp.checksum = bb.getShort(); - - icmp.payload = Data.deserializer() - .deserialize(data, bb.position(), bb.limit() - - bb.position()); - icmp.payload.setParent(icmp); - return icmp; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ICMP6.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ICMP6.java deleted file mode 100644 index c8981302..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ICMP6.java +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import org.onlab.packet.ipv6.IExtensionHeader; -import org.onlab.packet.ndp.NeighborAdvertisement; -import org.onlab.packet.ndp.NeighborSolicitation; -import org.onlab.packet.ndp.Redirect; -import org.onlab.packet.ndp.RouterAdvertisement; -import org.onlab.packet.ndp.RouterSolicitation; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * Implements ICMPv6 packet format. (RFC 4443) - */ -public class ICMP6 extends BasePacket { - public static final byte HEADER_LENGTH = 4; // bytes - - // Type - /** Destination Unreachable. */ - public static final byte DEST_UNREACH = (byte) 0x01; - /** Packet Too Big. */ - public static final byte PKT_TOO_BIG = (byte) 0x02; - /** Time Exceeded. */ - public static final byte TIME_EXCEED = (byte) 0x03; - /** Parameter Problem. */ - public static final byte PARAM_ERR = (byte) 0x04; - /** Echo Request. */ - public static final byte ECHO_REQUEST = (byte) 0x80; - /** Echo Reply. */ - public static final byte ECHO_REPLY = (byte) 0x81; - /** Multicast Listener Query. */ - public static final byte MCAST_QUERY = (byte) 0x82; - /** Multicast Listener Report. */ - public static final byte MCAST_REPORT = (byte) 0x83; - /** Multicast Listener Done. */ - public static final byte MCAST_DONE = (byte) 0x84; - /** Router Solicitation. */ - public static final byte ROUTER_SOLICITATION = (byte) 0x85; - /** Router Advertisement. */ - public static final byte ROUTER_ADVERTISEMENT = (byte) 0x86; - /** Neighbor Solicitation. */ - public static final byte NEIGHBOR_SOLICITATION = (byte) 0x87; - /** Neighbor Advertisement. */ - public static final byte NEIGHBOR_ADVERTISEMENT = (byte) 0x88; - /** Redirect Message. */ - public static final byte REDIRECT = (byte) 0x89; - - // Code for DEST_UNREACH - /** No route to destination. */ - public static final byte NO_ROUTE = (byte) 0x00; - /** Communication with destination administratively prohibited. */ - public static final byte COMM_PROHIBIT = (byte) 0x01; - /** Beyond scope of source address. */ - public static final byte BEYOND_SCOPE = (byte) 0x02; - /** Address unreachable. */ - public static final byte ADDR_UNREACH = (byte) 0x03; - /** Port unreachable. */ - public static final byte PORT_UNREACH = (byte) 0x04; - /** Source address failed ingress/egress policy. */ - public static final byte FAIL_POLICY = (byte) 0x05; - /** Reject route to destination. */ - public static final byte REJECT_ROUTE = (byte) 0x06; - /** Error in Source Routing Header. */ - public static final byte SRC_ROUTING_HEADER_ERR = (byte) 0x07; - - // Code for TIME_EXCEED - /** Hop limit exceeded in transit. */ - public static final byte HOP_LIMIT_EXCEED = (byte) 0x00; - /** Fragment reassembly time exceeded. */ - public static final byte DEFRAG_TIME_EXCEED = (byte) 0x01; - - // Code for PARAM_ERR - /** Erroneous header field encountered. */ - public static final byte HDR_FIELD_ERR = (byte) 0x00; - /** Unrecognized Next Header type encountered. */ - public static final byte NEXT_HEADER_ERR = (byte) 0x01; - /** Unrecognized IPv6 option encountered. */ - public static final byte IPV6_OPT_ERR = (byte) 0x01; - - public static final Map> TYPE_DESERIALIZER_MAP = - new HashMap<>(); - - static { - ICMP6.TYPE_DESERIALIZER_MAP.put(ICMP6.ROUTER_SOLICITATION, RouterSolicitation.deserializer()); - ICMP6.TYPE_DESERIALIZER_MAP.put(ICMP6.ROUTER_ADVERTISEMENT, RouterAdvertisement.deserializer()); - ICMP6.TYPE_DESERIALIZER_MAP.put(ICMP6.NEIGHBOR_SOLICITATION, NeighborSolicitation.deserializer()); - ICMP6.TYPE_DESERIALIZER_MAP.put(ICMP6.NEIGHBOR_ADVERTISEMENT, NeighborAdvertisement.deserializer()); - ICMP6.TYPE_DESERIALIZER_MAP.put(ICMP6.REDIRECT, Redirect.deserializer()); - } - - protected byte icmpType; - protected byte icmpCode; - protected short checksum; - - private static final byte[] ZERO_ADDRESS = new byte[Ip6Address.BYTE_LENGTH]; - - /** - * Gets ICMP6 type. - * - * @return the ICMP6 type - */ - public byte getIcmpType() { - return this.icmpType; - } - - /** - * Sets ICMP6 type. - * - * @param icmpType the ICMP type to set - * @return this - */ - public ICMP6 setIcmpType(final byte icmpType) { - this.icmpType = icmpType; - return this; - } - - /** - * Gets ICMP6 code. - * - * @return the ICMP6 code - */ - public byte getIcmpCode() { - return this.icmpCode; - } - - /** - * Sets ICMP6 code. - * - * @param icmpCode the ICMP6 code to set - * @return this - */ - public ICMP6 setIcmpCode(final byte icmpCode) { - this.icmpCode = icmpCode; - return this; - } - - /** - * Gets checksum. - * - * @return the checksum - */ - public short getChecksum() { - return this.checksum; - } - - /** - * Sets checksum. - * - * @param checksum the checksum to set - * @return this - */ - public ICMP6 setChecksum(final short checksum) { - this.checksum = checksum; - return this; - } - - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - - int payloadLength = 0; - if (payloadData != null) { - payloadLength = payloadData.length; - } - - final byte[] data = new byte[HEADER_LENGTH + payloadLength]; - final ByteBuffer bbData = ByteBuffer.wrap(data); - - // Creating ByteBuffer for checksum calculation - final byte[] checksumData = - new byte[IPv6.FIXED_HEADER_LENGTH + HEADER_LENGTH + payloadLength]; - final ByteBuffer bbChecksum = ByteBuffer.wrap(checksumData); - - // - // Creating IPv6 Pseudo Header for checksum calculation according - // to RFC 4443 and RFC 2460 - // - IPv6 ipv6Parent = null; - for (IPacket p = this.parent; p != null; p = p.getParent()) { - if (p instanceof IPv6) { - ipv6Parent = (IPv6) p; - break; - } - } - if (ipv6Parent != null) { - bbChecksum.put(ipv6Parent.getSourceAddress()); - bbChecksum.put(ipv6Parent.getDestinationAddress()); - } else { - // NOTE: IPv6 source and destination addresses unknown. Use zeroes. - bbChecksum.put(ZERO_ADDRESS); - bbChecksum.put(ZERO_ADDRESS); - } - bbChecksum.putInt(HEADER_LENGTH + payloadLength); - bbChecksum.put((byte) 0); - bbChecksum.put((byte) 0); - bbChecksum.put((byte) 0); - bbChecksum.put(IPv6.PROTOCOL_ICMP6); - bbChecksum.put(this.icmpType); - bbChecksum.put(this.icmpCode); - bbChecksum.put((byte) 0); - bbChecksum.put((byte) 0); - - bbData.put(this.icmpType); - bbData.put(this.icmpCode); - bbData.putShort(this.checksum); - if (payloadData != null) { - bbData.put(payloadData); - bbChecksum.put(payloadData); - } - - if (this.parent != null) { - if (this.parent instanceof IPv6) { - ((IPv6) this.parent).setNextHeader(IPv6.PROTOCOL_ICMP6); - } else if (this.parent instanceof IExtensionHeader) { - ((IExtensionHeader) this.parent).setNextHeader(IPv6.PROTOCOL_ICMP6); - } - } - - // compute checksum if needed - if (this.checksum == 0) { - bbData.rewind(); - bbChecksum.rewind(); - int accumulation = 0; - - for (int i = 0; i < checksumData.length / 2; ++i) { - accumulation += 0xffff & bbChecksum.getShort(); - } - // pad to an even number of shorts - if (checksumData.length % 2 > 0) { - accumulation += (bbChecksum.get() & 0xff) << 8; - } - - accumulation = (accumulation >> 16 & 0xffff) - + (accumulation & 0xffff); - this.checksum = (short) (~accumulation & 0xffff); - bbData.putShort(2, this.checksum); - } - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.icmpType = bb.get(); - this.icmpCode = bb.get(); - this.checksum = bb.getShort(); - - Deserializer deserializer; - if (ICMP6.TYPE_DESERIALIZER_MAP.containsKey(icmpType)) { - deserializer = TYPE_DESERIALIZER_MAP.get(icmpType); - } else { - deserializer = Data.deserializer(); - } - try { - this.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - this.payload.setParent(this); - } catch (DeserializationException e) { - return this; - } - - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - result = prime * result + this.icmpType; - result = prime * result + this.icmpCode; - result = prime * result + this.checksum; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof ICMP6)) { - return false; - } - final ICMP6 other = (ICMP6) obj; - if (this.icmpType != other.icmpType) { - return false; - } - if (this.icmpCode != other.icmpCode) { - return false; - } - if (this.checksum != other.checksum) { - return false; - } - return true; - } - - /** - * Deserializer function for ICMPv6 packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, HEADER_LENGTH); - - ICMP6 icmp6 = new ICMP6(); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - - icmp6.icmpType = bb.get(); - icmp6.icmpCode = bb.get(); - icmp6.checksum = bb.getShort(); - - Deserializer deserializer; - if (ICMP6.TYPE_DESERIALIZER_MAP.containsKey(icmp6.icmpType)) { - deserializer = TYPE_DESERIALIZER_MAP.get(icmp6.icmpType); - } else { - deserializer = Data.deserializer(); - } - icmp6.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - icmp6.payload.setParent(icmp6); - - return icmp6; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMP.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMP.java deleted file mode 100644 index 254f1325..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMP.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.slf4j.Logger; - -import static org.slf4j.LoggerFactory.getLogger; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.onlab.packet.PacketUtils.checkInput; - - -/** - * Implements IGMP control packet format. - */ -public class IGMP extends BasePacket { - private final Logger log = getLogger(getClass()); - - public static final byte TYPE_IGMPV3_MEMBERSHIP_QUERY = 0x11; - public static final byte TYPE_IGMPV1_MEMBERSHIP_REPORT = 0x12; - public static final byte TYPE_IGMPV2_MEMBERSHIP_REPORT = 0x16; - public static final byte TYPE_IGMPV2_LEAVE_GROUP = 0x17; - public static final byte TYPE_IGMPV3_MEMBERSHIP_REPORT = 0x22; - public static final Map> PROTOCOL_DESERIALIZER_MAP = new HashMap<>(); - - public static final int MINIMUM_HEADER_LEN = 12; - - List groups = new ArrayList<>(); - - // Fields contained in the IGMP header - private byte igmpType; - private byte resField = 0; - private short checksum = 0; - - private byte[] unsupportTypeData; - - public IGMP() { - } - - /** - * Get the IGMP message type. - * - * @return the IGMP message type - */ - public byte getIgmpType() { - return igmpType; - } - - /** - * Set the IGMP message type. - * - * @param msgType IGMP message type - */ - public void setIgmpType(byte msgType) { - igmpType = msgType; - } - - /** - * Get the checksum of this message. - * - * @return the checksum - */ - public short getChecksum() { - return checksum; - } - - /** - * get the Max Resp Code. - * - * @return The Maximum Time allowed before before sending a responding report. - */ - public byte getMaxRespField() { - return resField; - } - - /** - * Set the Max Resp Code. - * - * @param respCode the Maximum Response Code. - */ - public void setMaxRespCode(byte respCode) { - if (igmpType != IGMP.TYPE_IGMPV3_MEMBERSHIP_QUERY) { - log.debug("Requesting the max response code for an incorrect field: "); - } - this.resField = respCode; - } - - /** - * Get the list of IGMPGroups. The group objects will be either IGMPQuery or IGMPMembership - * depending on the IGMP message type. For IGMP Query, the groups list should only be - * one group. - * - * @return The list of IGMP groups. - */ - public List getGroups() { - return groups; - } - - /** - * Add a multicast group to this IGMP message. - * - * @param group the IGMPGroup will be IGMPQuery or IGMPMembership depending on the message type. - * @return true if group was valid and added, false otherwise. - */ - public boolean addGroup(IGMPGroup group) { - checkNotNull(group); - switch (this.igmpType) { - case TYPE_IGMPV3_MEMBERSHIP_QUERY: - if (group instanceof IGMPMembership) { - return false; - } - - if (group.sources.size() > 1) { - return false; - } - break; - - case TYPE_IGMPV3_MEMBERSHIP_REPORT: - if (group instanceof IGMPMembership) { - return false; - } - break; - - default: - log.debug("Warning no IGMP message type has been set"); - } - - this.groups.add(group); - return true; - } - - /** - * Serialize this IGMP packet. This will take care - * of serializing IGMPv3 Queries and IGMPv3 Membership - * Reports. - * - * @return the serialized IGMP message - */ - @Override - public byte[] serialize() { - byte [] data = new byte[8915]; - - ByteBuffer bb = ByteBuffer.wrap(data); - bb.put(this.getIgmpType()); - - // reserved or max resp code depending on type. - bb.put(this.resField); - - // Must calculate checksum - bb.putShort((short) 0); - - switch (this.igmpType) { - - case IGMP.TYPE_IGMPV3_MEMBERSHIP_REPORT: - // reserved - bb.putShort((short) 0); - // Number of groups - bb.putShort((short) groups.size()); - // Fall through - - case IGMP.TYPE_IGMPV3_MEMBERSHIP_QUERY: - - for (IGMPGroup grp : groups) { - grp.serialize(bb); - } - break; - - default: - bb.put(this.unsupportTypeData); - break; - } - - int size = bb.position(); - bb.position(0); - byte [] rdata = new byte[size]; - bb.get(rdata, 0, size); - return rdata; - } - - /** - * Deserialize an IGMP message. - * - * @param data bytes to deserialize - * @param offset offset to start deserializing from - * @param length length of the data to deserialize - * @return populated IGMP object - */ - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - - IGMP igmp = new IGMP(); - try { - igmp = IGMP.deserializer().deserialize(data, offset, length); - } catch (DeserializationException e) { - log.error(e.getStackTrace().toString()); - return this; - } - this.igmpType = igmp.igmpType; - this.resField = igmp.resField; - this.checksum = igmp.checksum; - this.groups = igmp.groups; - return this; - } - - /** - * Deserializer function for IPv4 packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, MINIMUM_HEADER_LEN); - - IGMP igmp = new IGMP(); - - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - igmp.igmpType = bb.get(); - igmp.resField = bb.get(); - igmp.checksum = bb.getShort(); - int len = MINIMUM_HEADER_LEN; - String msg; - - switch (igmp.igmpType) { - - case TYPE_IGMPV3_MEMBERSHIP_QUERY: - IGMPQuery qgroup = new IGMPQuery(); - qgroup.deserialize(bb); - igmp.groups.add(qgroup); - break; - - case TYPE_IGMPV3_MEMBERSHIP_REPORT: - bb.getShort(); // Ignore resvd - int ngrps = bb.getShort(); - - for (; ngrps > 0; ngrps--) { - IGMPMembership mgroup = new IGMPMembership(); - mgroup.deserialize(bb); - igmp.groups.add(mgroup); - } - break; - - /* - * NOTE: according to the IGMPv3 spec. These previous IGMP type fields - * must be supported. At this time we are going to assume we run - * in a modern network where all devices are IGMPv3 capable. - */ - case TYPE_IGMPV1_MEMBERSHIP_REPORT: - case TYPE_IGMPV2_MEMBERSHIP_REPORT: - case TYPE_IGMPV2_LEAVE_GROUP: - igmp.unsupportTypeData = bb.array(); // Is this the entire array? - msg = "IGMP message type: " + igmp.igmpType + " is not supported"; - igmp.log.debug(msg); - break; - - default: - msg = "IGMP message type: " + igmp.igmpType + " is not recognized"; - igmp.unsupportTypeData = bb.array(); - igmp.log.debug(msg); - break; - } - return igmp; - }; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof IGMP)) { - return false; - } - final IGMP other = (IGMP) obj; - if (this.igmpType != other.igmpType) { - return false; - } - if (this.resField != other.resField) { - return false; - } - if (this.checksum != other.checksum) { - return false; - } - if (this.groups.size() != other.groups.size()) { - return false; - } - // TODO: equals should be true regardless of order. - if (!groups.equals(other.groups)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 2521; - int result = super.hashCode(); - result = prime * result + this.igmpType; - result = prime * result + this.groups.size(); - result = prime * result + this.resField; - result = prime * result + this.checksum; - result = prime * result + this.groups.hashCode(); - return result; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPGroup.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPGroup.java deleted file mode 100644 index 70ff5563..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPGroup.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -/** - * A class to represent Groups for membership query and reports. - */ -public abstract class IGMPGroup { - - protected int auxInfo; - protected IpAddress gaddr; - protected List sources = new ArrayList<>(); - - public IGMPGroup() { - } - - /** - * Initialize this object with a multicast group address and additional info. - * - * @param gaddr: the multicast group address for this message type. - * @param auxInfo: additional info potentially used by IGMPQuery - */ - public IGMPGroup(IpAddress gaddr, int auxInfo) { - this.gaddr = gaddr; - this.auxInfo = auxInfo; - } - - /** - * Get the multicast group address. - * - * @return the group address - */ - public IpAddress getGaddr() { - return this.gaddr; - } - - /** - * Get the auxillary info. - * - * @return the auxillary info - */ - public int getAuxInfo() { - return this.auxInfo; - } - - /** - * Add a unicast source address to this message. - * - * @param saddr IPv4 unicast source address - */ - public void addSource(IpAddress saddr) { - sources.add(saddr); - } - - /** - * Return the list of source addresses. - * - * @return list of source addresses - */ - public List getSources() { - return sources; - } - - /** - * Deserialize an IGMPQuery or IGMPMembership message. - * - * @param bb the ByteBuffer wrapping the serialized message. The position of the - * ByteBuffer should be pointing at the head of either message type. - * @return An object populated with the respective IGMPGroup subclass - * @throws DeserializationException in case deserialization goes wrong - */ - public abstract IGMPGroup deserialize(ByteBuffer bb) throws DeserializationException; - - /** - * Serialize the IGMPGroup subclass. - * - * @param bb the ByteBuffer to write into, positioned at the next spot to be written to. - * @return The serialized message - */ - public abstract byte[] serialize(ByteBuffer bb); -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPMembership.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPMembership.java deleted file mode 100644 index 495e283c..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPMembership.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import static org.onlab.packet.PacketUtils.checkBufferLength; - -public class IGMPMembership extends IGMPGroup { - - public static final byte MODE_IS_INCLUDE = 0x1; - public static final byte MODE_IS_EXCLUDE = 0x2; - public static final byte CHANGE_TO_INCLUDE_MODE = 0x3; - public static final byte CHANGE_TO_EXCLUDE_MODE = 0x4; - public static final byte ALLOW_NEW_SOURCES = 0x5; - public static final byte BLOCK_OLD_SOURCES = 0x6; - - private final int minGroupRecordLen = Ip4Address.BYTE_LENGTH + 4; - - protected byte recordType; - protected byte auxDataLength = 0; - protected byte[] auxData; - - /** - * Constructor initialized with a multicast group address. - * - * @param gaddr A multicast group address. - */ - public IGMPMembership(Ip4Address gaddr) { - super(gaddr, 0); - } - - /** - * Default constructor. - */ - public IGMPMembership() { - super(); - } - - /** - * Serialize this Membership Report. - * - * @param bb the ByteBuffer to write into, positioned at the next spot to be written to. - * @return serialized IGMP message. - */ - @Override - public byte[] serialize(ByteBuffer bb) { - - bb.put(recordType); - bb.put(auxDataLength); // reserved - bb.putShort((short) sources.size()); - bb.put(gaddr.toOctets()); - for (IpAddress ipaddr : sources) { - bb.put(ipaddr.toOctets()); - } - - if (auxDataLength > 0) { - bb.put(auxData); - } - - return bb.array(); - } - - /** - * Deserialize the IGMP Membership report packet. - * - * @param bb the ByteBuffer wrapping the serialized message. The position of the - * ByteBuffer should be pointing at the head of either message type. - * @return IGMP Group - * @throws DeserializationException if deserialization fails - */ - public IGMPGroup deserialize(ByteBuffer bb) throws DeserializationException { - - // Make sure there is enough buffer to read the header, - // including the number of sources - checkBufferLength(bb.remaining(), 0, minGroupRecordLen); - recordType = bb.get(); - auxDataLength = bb.get(); - int nsrcs = bb.getShort(); - - gaddr = Ip4Address.valueOf(bb.getInt()); - - // Make sure we have enough buffer to hold all of these sources - checkBufferLength(bb.remaining(), 0, Ip4Address.BYTE_LENGTH * nsrcs); - for (; nsrcs > 0; nsrcs--) { - Ip4Address src = Ip4Address.valueOf(bb.getInt()); - this.sources.add(src); - } - - if (auxDataLength > 0) { - auxData = new byte[auxDataLength]; - bb.get(auxData, 0, auxDataLength); - } - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals() - */ - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof IGMPMembership)) { - return false; - } - IGMPMembership other = (IGMPMembership) obj; - - if (!this.gaddr.equals(other.gaddr)) { - return false; - } - if (this.recordType != other.recordType) { - return false; - } - if (this.auxDataLength != other.auxDataLength) { - return false; - } - if (this.sources.size() != other.sources.size()) { - return false; - } - // TODO: make these tolerant of order - if (!this.sources.equals(other.sources)) { - return false; - } - - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 2521; - int result = super.hashCode(); - result = prime * result + this.gaddr.hashCode(); - result = prime * result + this.recordType; - result = prime * result + this.auxDataLength; - result = prime * result + this.sources.hashCode(); - return result; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPQuery.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPQuery.java deleted file mode 100644 index bb53eba5..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IGMPQuery.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; - -public class IGMPQuery extends IGMPGroup { - - // Bits and bytes after the group address - private byte resv = 0; - private boolean sbit = false; - private byte qrv = 2; - private byte qqic = 0x7d; - - /** - * Create IGMP Query message. - * - * @param gaddr initiaze with a group address. - * @param auxInfo auxillary info. - */ - public IGMPQuery(IpAddress gaddr, int auxInfo) { - super(gaddr, auxInfo); - } - - /** - * Create IGMP Query message. - */ - public IGMPQuery() { - super(); - } - - /** - * Is the S flag set? Telling adjacent routers to suppress normal timer updates. - * - * @return true if the flag is set, false otherwise - */ - public boolean isSbit() { - return sbit; - } - - /** - * Set the S flag. Default is false. - * - * @param sbit true or false - */ - public void setSbit(boolean sbit) { - this.sbit = sbit; - } - - /** - * Get the Querier Robustness Variable. - * - * @return querier robustness value - */ - public byte getQrv() { - return qrv; - } - - /** - * Set the Querier Robustness Variable. Default is 2. - * - * @param qrv new querier robustness value - */ - public void setQrv(byte qrv) { - this.qrv = qrv; - } - - /** - * Get the reserved field. Should be zero, but ignored regardless of it's value. - * - * @return the reserved field. - */ - public byte getResv() { - return resv; - } - - /** - * Set the reserved field. Should be 0 and ignored by receivers. - * - * @param resv the reserved field. - */ - public void setResv(byte resv) { - this.resv = resv; - } - - /** - * Serialize this IGMPQuery. - * - * @param bb the ByteBuffer to write into, positioned at the next spot to be written to. - * @return the serialized message - */ - @Override - public byte[] serialize(ByteBuffer bb) { - - bb.put(gaddr.toOctets()); - byte fld = (byte) (0x7 & qrv); - bb.put(fld); - bb.put(qqic); - bb.putShort((short) sources.size()); - for (IpAddress ipaddr : sources) { - bb.put(ipaddr.toOctets()); - } - return bb.array(); - } - - /** - * Deserialize the IGMP Query group structure. - * - * @param bb ByteBuffer pointing at the IGMP Query group address - * @return the IGMP Group object - */ - public IGMPGroup deserialize(ByteBuffer bb) throws DeserializationException { - - gaddr = Ip4Address.valueOf(bb.getInt()); - byte fld = bb.get(); - - // Just ignore the reserved bits - resv = 0; - this.sbit = ((fld & 0x8) == 0x8); - qrv = (byte) (fld & 0x7); - - // QQIC field - qqic = bb.get(); - - // Get the number of sources. - short nsrcs = bb.getShort(); - - // Do a sanity check on the amount of space we have in our buffer. - int lengthNeeded = (Ip4Address.BYTE_LENGTH * nsrcs); - PacketUtils.checkHeaderLength(bb.remaining(), lengthNeeded); - - for (; nsrcs > 0; nsrcs--) { - Ip4Address ipaddr = Ip4Address.valueOf(bb.getInt()); - this.sources.add(ipaddr); - } - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals() - */ - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof IGMPQuery)) { - return false; - } - IGMPQuery other = (IGMPQuery) obj; - - if (this.sbit != other.sbit) { - return false; - } - if (this.qrv != other.qrv) { - return false; - } - if (this.qqic != other.qqic) { - return false; - } - if (this.sources.size() != other.sources.size()) { - return false; - } - - // TODO: make these tolerant of order - if (!this.sources.equals(other.sources)) { - return false; - } - - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 2521; - int result = super.hashCode(); - result = prime * result + this.gaddr.hashCode(); - result = prime * result + this.qqic; - result = prime * result + this.qrv; - result = prime * result + this.sources.hashCode(); - return result; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPacket.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPacket.java deleted file mode 100644 index 64e6ac36..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPacket.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -/** - * - */ -public interface IPacket { - /** - * - * @return the payload - */ - IPacket getPayload(); - - /** - * - * @param packet new payload - * @return self - */ - IPacket setPayload(IPacket packet); - - /** - * - * @return parent packet - */ - IPacket getParent(); - - /** - * - * @param packet new parent - * @return self - */ - IPacket setParent(IPacket packet); - - /** - * Reset any checksums as needed, and call resetChecksum on all parents. - */ - void resetChecksum(); - - /** - * Sets all payloads parent packet if applicable, then serializes this - * packet and all payloads. - * - * @return a byte[] containing this packet and payloads - */ - byte[] serialize(); - - /** - * Deserializes this packet layer and all possible payloads. - * - * NOTE: This method has been deprecated and will be removed in a future - * release. It is now recommended to use the Deserializer function provided - * by the deserialize() method on each packet to deserialize them. The - * Deserializer functions are robust to malformed input. - * - * @param data bytes to deserialize - * @param offset - * offset to start deserializing from - * @param length - * length of the data to deserialize - * @return the deserialized data - * @deprecated in Cardinal Release - */ - @Deprecated - IPacket deserialize(byte[] data, int offset, int length); - - /** - * Clone this packet and its payload packet but not its parent. - * - * @return the clone - */ - Object clone(); -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPv4.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPv4.java deleted file mode 100644 index a5c5f4f1..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPv4.java +++ /dev/null @@ -1,733 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import static org.onlab.packet.PacketUtils.*; - -/** - * - */ -public class IPv4 extends BasePacket { - public static final byte PROTOCOL_ICMP = 0x1; - public static final byte PROTOCOL_IGMP = 0x2; - public static final byte PROTOCOL_TCP = 0x6; - public static final byte PROTOCOL_UDP = 0x11; - public static final byte PROTOCOL_PIM = 0x67; - public static final Map> PROTOCOL_DESERIALIZER_MAP = - new HashMap<>(); - - static { - IPv4.PROTOCOL_DESERIALIZER_MAP.put(IPv4.PROTOCOL_ICMP, ICMP.deserializer()); - IPv4.PROTOCOL_DESERIALIZER_MAP.put(IPv4.PROTOCOL_IGMP, IGMP.deserializer()); - IPv4.PROTOCOL_DESERIALIZER_MAP.put(IPv4.PROTOCOL_TCP, TCP.deserializer()); - IPv4.PROTOCOL_DESERIALIZER_MAP.put(IPv4.PROTOCOL_UDP, UDP.deserializer()); - IPv4.PROTOCOL_DESERIALIZER_MAP.put(IPv4.PROTOCOL_PIM, PIM.deserializer()); - } - - private static final byte DSCP_MASK = 0x3f; - private static final byte DSCP_OFFSET = 2; - private static final byte ECN_MASK = 0x3; - - private static final short HEADER_LENGTH = 20; - - protected byte version; - protected byte headerLength; - protected byte diffServ; - protected short totalLength; - protected short identification; - protected byte flags; - protected short fragmentOffset; - protected byte ttl; - protected byte protocol; - protected short checksum; - protected int sourceAddress; - protected int destinationAddress; - protected byte[] options; - - protected boolean isTruncated; - - /** - * Default constructor that sets the version to 4. - */ - public IPv4() { - super(); - this.version = 4; - this.isTruncated = false; - } - - /** - * @return the version - */ - public byte getVersion() { - return this.version; - } - - /** - * @param version - * the version to set - * @return this - */ - public IPv4 setVersion(final byte version) { - this.version = version; - return this; - } - - /** - * @return the headerLength - */ - public byte getHeaderLength() { - return this.headerLength; - } - - /** - * Gets the DSCP value (6 bits). - * - * @return the DSCP value (6 bits) - */ - public byte getDscp() { - return (byte) ((this.diffServ >>> DSCP_OFFSET) & DSCP_MASK); - } - - /** - * Sets the DSCP value (6 bits). - * - * @param dscp the DSCP value (6 bits) - * @return this - */ - public IPv4 setDscp(byte dscp) { - this.diffServ &= ~(DSCP_MASK << DSCP_OFFSET); - this.diffServ |= (dscp & DSCP_MASK) << DSCP_OFFSET; - return this; - } - - /** - * Gets the ECN value (2 bits). - * - * @return the ECN value (2 bits) - */ - public byte getEcn() { - return (byte) (this.diffServ & ECN_MASK); - } - - /** - * Sets the ECN value (2 bits). - * - * @param ecn the ECN value (2 bits) - * @return this - */ - public IPv4 setEcn(byte ecn) { - this.diffServ &= ~ECN_MASK; - this.diffServ |= (ecn & ECN_MASK); - return this; - } - - /** - * Gets the DiffServ octet (including the DSCP and ECN bits). - * - * @return the diffServ octet (including the DSCP and ECN bits) - */ - public byte getDiffServ() { - return this.diffServ; - } - - /** - * Sets the DiffServ octet (including the DSCP and ECN bits). - * - * @param diffServ the diffServ octet to set (including the DSCP and ECN - * bits) - * @return this - */ - public IPv4 setDiffServ(final byte diffServ) { - this.diffServ = diffServ; - return this; - } - - /** - * @return the totalLength - */ - public short getTotalLength() { - return this.totalLength; - } - - /** - * @return the identification - */ - public short getIdentification() { - return this.identification; - } - - public boolean isTruncated() { - return this.isTruncated; - } - - public void setTruncated(final boolean isTruncated) { - this.isTruncated = isTruncated; - } - - /** - * @param identification - * the identification to set - * @return this - */ - public IPv4 setIdentification(final short identification) { - this.identification = identification; - return this; - } - - /** - * @return the flags - */ - public byte getFlags() { - return this.flags; - } - - /** - * @param flags - * the flags to set - * @return this -s */ - public IPv4 setFlags(final byte flags) { - this.flags = flags; - return this; - } - - /** - * @return the fragmentOffset - */ - public short getFragmentOffset() { - return this.fragmentOffset; - } - - /** - * @param fragmentOffset - * the fragmentOffset to set - * @return this - */ - public IPv4 setFragmentOffset(final short fragmentOffset) { - this.fragmentOffset = fragmentOffset; - return this; - } - - /** - * @return the ttl - */ - public byte getTtl() { - return this.ttl; - } - - /** - * @param ttl - * the ttl to set - * @return this - */ - public IPv4 setTtl(final byte ttl) { - this.ttl = ttl; - return this; - } - - /** - * @return the protocol - */ - public byte getProtocol() { - return this.protocol; - } - - /** - * @param protocol - * the protocol to set - * @return this - */ - public IPv4 setProtocol(final byte protocol) { - this.protocol = protocol; - return this; - } - - /** - * @return the checksum - */ - public short getChecksum() { - return this.checksum; - } - - /** - * @param checksum - * the checksum to set - * @return this - */ - public IPv4 setChecksum(final short checksum) { - this.checksum = checksum; - return this; - } - - @Override - public void resetChecksum() { - this.checksum = 0; - super.resetChecksum(); - } - - /** - * @return the sourceAddress - */ - public int getSourceAddress() { - return this.sourceAddress; - } - - /** - * @param sourceAddress - * the sourceAddress to set - * @return this - */ - public IPv4 setSourceAddress(final int sourceAddress) { - this.sourceAddress = sourceAddress; - return this; - } - - /** - * @param sourceAddress - * the sourceAddress to set - * @return this - */ - public IPv4 setSourceAddress(final String sourceAddress) { - this.sourceAddress = IPv4.toIPv4Address(sourceAddress); - return this; - } - - /** - * @return the destinationAddress - */ - public int getDestinationAddress() { - return this.destinationAddress; - } - - /** - * @param destinationAddress - * the destinationAddress to set - * @return this - */ - public IPv4 setDestinationAddress(final int destinationAddress) { - this.destinationAddress = destinationAddress; - return this; - } - - /** - * @param destinationAddress - * the destinationAddress to set - * @return this - */ - public IPv4 setDestinationAddress(final String destinationAddress) { - this.destinationAddress = IPv4.toIPv4Address(destinationAddress); - return this; - } - - /** - * @return the options - */ - public byte[] getOptions() { - return this.options; - } - - /** - * @param options - * the options to set - * @return this - */ - public IPv4 setOptions(final byte[] options) { - if (options != null && options.length % 4 > 0) { - throw new IllegalArgumentException( - "Options length must be a multiple of 4"); - } - this.options = options; - return this; - } - - /** - * Serializes the packet. Will compute and set the following fields if they - * are set to specific values at the time serialize is called: -checksum : 0 - * -headerLength : 0 -totalLength : 0 - */ - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - - int optionsLength = 0; - if (this.options != null) { - optionsLength = this.options.length / 4; - } - this.headerLength = (byte) (5 + optionsLength); - - this.totalLength = (short) (this.headerLength * 4 + (payloadData == null ? 0 - : payloadData.length)); - - final byte[] data = new byte[this.totalLength]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.put((byte) ((this.version & 0xf) << 4 | this.headerLength & 0xf)); - bb.put(this.diffServ); - bb.putShort(this.totalLength); - bb.putShort(this.identification); - bb.putShort((short) ((this.flags & 0x7) << 13 | this.fragmentOffset & 0x1fff)); - bb.put(this.ttl); - bb.put(this.protocol); - bb.putShort(this.checksum); - bb.putInt(this.sourceAddress); - bb.putInt(this.destinationAddress); - if (this.options != null) { - bb.put(this.options); - } - if (payloadData != null) { - bb.put(payloadData); - } - - // compute checksum if needed - if (this.checksum == 0) { - bb.rewind(); - int accumulation = 0; - for (int i = 0; i < this.headerLength * 2; ++i) { - accumulation += 0xffff & bb.getShort(); - } - accumulation = (accumulation >> 16 & 0xffff) - + (accumulation & 0xffff); - this.checksum = (short) (~accumulation & 0xffff); - bb.putShort(10, this.checksum); - } - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - short sscratch; - - this.version = bb.get(); - this.headerLength = (byte) (this.version & 0xf); - this.version = (byte) (this.version >> 4 & 0xf); - this.diffServ = bb.get(); - this.totalLength = bb.getShort(); - this.identification = bb.getShort(); - sscratch = bb.getShort(); - this.flags = (byte) (sscratch >> 13 & 0x7); - this.fragmentOffset = (short) (sscratch & 0x1fff); - this.ttl = bb.get(); - this.protocol = bb.get(); - this.checksum = bb.getShort(); - this.sourceAddress = bb.getInt(); - this.destinationAddress = bb.getInt(); - - if (this.headerLength > 5) { - final int optionsLength = (this.headerLength - 5) * 4; - this.options = new byte[optionsLength]; - bb.get(this.options); - } - - if (this.totalLength != length) { - this.isTruncated = true; - } else { - this.isTruncated = false; - } - - Deserializer deserializer; - if (IPv4.PROTOCOL_DESERIALIZER_MAP.containsKey(this.protocol)) { - deserializer = IPv4.PROTOCOL_DESERIALIZER_MAP.get(this.protocol); - } else { - deserializer = Data.deserializer(); - } - try { - this.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - this.payload.setParent(this); - } catch (DeserializationException e) { - return this; - } - - return this; - } - - /** - * Accepts an IPv4 address of the form xxx.xxx.xxx.xxx, ie 192.168.0.1 and - * returns the corresponding 32 bit integer. - * - * @param ipAddress ip address in string form - * @return int ip address value - */ - public static int toIPv4Address(final String ipAddress) { - if (ipAddress == null) { - throw new IllegalArgumentException("Specified IPv4 address must" - + "contain 4 sets of numerical digits separated by periods"); - } - final String[] octets = ipAddress.split("\\."); - if (octets.length != 4) { - throw new IllegalArgumentException("Specified IPv4 address must" - + "contain 4 sets of numerical digits separated by periods"); - } - - int result = 0; - for (int i = 0; i < 4; ++i) { - result |= Integer.parseInt(octets[i]) << (3 - i) * 8; - } - return result; - } - - /** - * Accepts an IPv4 address in a byte array and returns the corresponding - * 32-bit integer value. - * - * @param ipAddress ip address in byte form - * @return int ip address value - */ - public static int toIPv4Address(final byte[] ipAddress) { - int ip = 0; - for (int i = 0; i < 4; i++) { - final int t = (ipAddress[i] & 0xff) << (3 - i) * 8; - ip |= t; - } - return ip; - } - - /** - * Accepts an IPv4 address and returns of string of the form xxx.xxx.xxx.xxx, - * e.g., 192.168.0.1. - * - * @param ipAddress ip address in form - * @return string form of ip address - */ - public static String fromIPv4Address(final int ipAddress) { - final StringBuffer sb = new StringBuffer(); - int result = 0; - for (int i = 0; i < 4; ++i) { - result = ipAddress >> (3 - i) * 8 & 0xff; - sb.append(result); - if (i != 3) { - sb.append("."); - } - } - return sb.toString(); - } - - /** - * Accepts a collection of IPv4 addresses as integers and returns a single - * String useful in toString method's containing collections of IP - * addresses. - * - * @param ipAddresses - * collection - * @return ip addresses in comma-separated string form - */ - public static String fromIPv4AddressCollection( - final Collection ipAddresses) { - if (ipAddresses == null) { - return "null"; - } - final StringBuffer sb = new StringBuffer(); - sb.append("["); - for (final Integer ip : ipAddresses) { - sb.append(IPv4.fromIPv4Address(ip)); - sb.append(","); - } - sb.replace(sb.length() - 1, sb.length(), "]"); - return sb.toString(); - } - - /** - * Accepts an IPv4 address of the form xxx.xxx.xxx.xxx, ie 192.168.0.1 and - * returns the corresponding byte array. - * - * @param ipAddress - * The IP address in the form xx.xxx.xxx.xxx. - * @return The IP address separated into bytes - */ - public static byte[] toIPv4AddressBytes(final String ipAddress) { - final String[] octets = ipAddress.split("\\."); - if (octets.length != 4) { - throw new IllegalArgumentException("Specified IPv4 address must" - + "contain 4 sets of numerical digits separated by periods"); - } - - final byte[] result = new byte[4]; - for (int i = 0; i < 4; ++i) { - result[i] = Integer.valueOf(octets[i]).byteValue(); - } - return result; - } - - /** - * Accepts an IPv4 address in the form of an integer and returns the - * corresponding byte array. - * - * @param ipAddress - * The IP address as an integer. - * @return The IP address separated into bytes. - */ - public static byte[] toIPv4AddressBytes(final int ipAddress) { - return new byte[] {(byte) (ipAddress >>> 24), - (byte) (ipAddress >>> 16), (byte) (ipAddress >>> 8), - (byte) ipAddress}; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 2521; - int result = super.hashCode(); - result = prime * result + this.checksum; - result = prime * result + this.destinationAddress; - result = prime * result + this.diffServ; - result = prime * result + this.flags; - result = prime * result + this.fragmentOffset; - result = prime * result + this.headerLength; - result = prime * result + this.identification; - result = prime * result + Arrays.hashCode(this.options); - result = prime * result + this.protocol; - result = prime * result + this.sourceAddress; - result = prime * result + this.totalLength; - result = prime * result + this.ttl; - result = prime * result + this.version; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof IPv4)) { - return false; - } - final IPv4 other = (IPv4) obj; - if (this.checksum != other.checksum) { - return false; - } - if (this.destinationAddress != other.destinationAddress) { - return false; - } - if (this.diffServ != other.diffServ) { - return false; - } - if (this.flags != other.flags) { - return false; - } - if (this.fragmentOffset != other.fragmentOffset) { - return false; - } - if (this.headerLength != other.headerLength) { - return false; - } - if (this.identification != other.identification) { - return false; - } - if (!Arrays.equals(this.options, other.options)) { - return false; - } - if (this.protocol != other.protocol) { - return false; - } - if (this.sourceAddress != other.sourceAddress) { - return false; - } - if (this.totalLength != other.totalLength) { - return false; - } - if (this.ttl != other.ttl) { - return false; - } - if (this.version != other.version) { - return false; - } - return true; - } - - /** - * Deserializer function for IPv4 packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, HEADER_LENGTH); - - IPv4 ipv4 = new IPv4(); - - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - - byte versionByte = bb.get(); - ipv4.headerLength = (byte) (versionByte & 0xf); - ipv4.setVersion((byte) (versionByte >> 4 & 0xf)); - ipv4.setDiffServ(bb.get()); - ipv4.totalLength = bb.getShort(); - ipv4.identification = bb.getShort(); - short flagsFragment = bb.getShort(); - ipv4.flags = (byte) (flagsFragment >> 13 & 0x7); - ipv4.fragmentOffset = (short) (flagsFragment & 0x1fff); - ipv4.ttl = bb.get(); - ipv4.protocol = bb.get(); - ipv4.checksum = bb.getShort(); - ipv4.sourceAddress = bb.getInt(); - ipv4.destinationAddress = bb.getInt(); - - if (ipv4.headerLength > 5) { - checkHeaderLength(length, ipv4.headerLength * 4); - - int optionsLength = (ipv4.headerLength - 5) * 4; - ipv4.options = new byte[optionsLength]; - bb.get(ipv4.options); - } - - Deserializer deserializer; - if (IPv4.PROTOCOL_DESERIALIZER_MAP.containsKey(ipv4.protocol)) { - deserializer = IPv4.PROTOCOL_DESERIALIZER_MAP.get(ipv4.protocol); - } else { - deserializer = Data.deserializer(); - } - ipv4.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - ipv4.payload.setParent(ipv4); - - if (ipv4.totalLength != length) { - ipv4.isTruncated = true; - } else { - ipv4.isTruncated = false; - } - - return ipv4; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPv6.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPv6.java deleted file mode 100644 index 2e59632a..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IPv6.java +++ /dev/null @@ -1,384 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import org.onlab.packet.ipv6.Authentication; -import org.onlab.packet.ipv6.DestinationOptions; -import org.onlab.packet.ipv6.EncapSecurityPayload; -import org.onlab.packet.ipv6.Fragment; -import org.onlab.packet.ipv6.HopByHopOptions; -import org.onlab.packet.ipv6.IExtensionHeader; -import org.onlab.packet.ipv6.Routing; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * Implements IPv6 packet format. (RFC 2460) - */ -public class IPv6 extends BasePacket implements IExtensionHeader { - public static final byte FIXED_HEADER_LENGTH = 40; // bytes - - public static final byte PROTOCOL_TCP = 0x6; - public static final byte PROTOCOL_UDP = 0x11; - public static final byte PROTOCOL_ICMP6 = 0x3A; - public static final byte PROTOCOL_HOPOPT = 0x00; - public static final byte PROTOCOL_ROUTING = 0x2B; - public static final byte PROTOCOL_FRAG = 0x2C; - public static final byte PROTOCOL_ESP = 0x32; - public static final byte PROTOCOL_AH = 0x33; - public static final byte PROTOCOL_DSTOPT = 0x3C; - - - public static final Map> PROTOCOL_DESERIALIZER_MAP = - new HashMap<>(); - - static { - IPv6.PROTOCOL_DESERIALIZER_MAP.put(IPv6.PROTOCOL_ICMP6, ICMP6.deserializer()); - IPv6.PROTOCOL_DESERIALIZER_MAP.put(IPv6.PROTOCOL_TCP, TCP.deserializer()); - IPv6.PROTOCOL_DESERIALIZER_MAP.put(IPv6.PROTOCOL_UDP, UDP.deserializer()); - IPv6.PROTOCOL_DESERIALIZER_MAP.put(IPv6.PROTOCOL_HOPOPT, HopByHopOptions.deserializer()); - IPv6.PROTOCOL_DESERIALIZER_MAP.put(IPv6.PROTOCOL_ROUTING, Routing.deserializer()); - IPv6.PROTOCOL_DESERIALIZER_MAP.put(IPv6.PROTOCOL_FRAG, Fragment.deserializer()); - IPv6.PROTOCOL_DESERIALIZER_MAP.put(IPv6.PROTOCOL_ESP, EncapSecurityPayload.deserializer()); - IPv6.PROTOCOL_DESERIALIZER_MAP.put(IPv6.PROTOCOL_AH, Authentication.deserializer()); - IPv6.PROTOCOL_DESERIALIZER_MAP.put(IPv6.PROTOCOL_DSTOPT, DestinationOptions.deserializer()); - } - - protected byte version; - protected byte trafficClass; - protected int flowLabel; - protected short payloadLength; - protected byte nextHeader; - protected byte hopLimit; - protected byte[] sourceAddress = new byte[Ip6Address.BYTE_LENGTH]; - protected byte[] destinationAddress = new byte[Ip6Address.BYTE_LENGTH]; - - /** - * Default constructor that sets the version to 6. - */ - public IPv6() { - super(); - this.version = 6; - } - - /** - * Gets IP version. - * - * @return the IP version - */ - public byte getVersion() { - return this.version; - } - - /** - * Sets IP version. - * - * @param version the IP version to set - * @return this - */ - public IPv6 setVersion(final byte version) { - this.version = version; - return this; - } - - /** - * Gets traffic class. - * - * @return the traffic class - */ - public byte getTrafficClass() { - return this.trafficClass; - } - - /** - * Sets traffic class. - * - * @param trafficClass the traffic class to set - * @return this - */ - public IPv6 setTrafficClass(final byte trafficClass) { - this.trafficClass = trafficClass; - return this; - } - - /** - * Gets flow label. - * - * @return the flow label - */ - public int getFlowLabel() { - return this.flowLabel; - } - - /** - * Sets flow label. - * - * @param flowLabel the flow label to set - * @return this - */ - public IPv6 setFlowLabel(final int flowLabel) { - this.flowLabel = flowLabel; - return this; - } - - @Override - public byte getNextHeader() { - return this.nextHeader; - } - - @Override - public IPv6 setNextHeader(final byte nextHeader) { - this.nextHeader = nextHeader; - return this; - } - - /** - * Gets hop limit. - * - * @return the hop limit - */ - public byte getHopLimit() { - return this.hopLimit; - } - - /** - * Sets hop limit. - * - * @param hopLimit the hop limit to set - * @return this - */ - public IPv6 setHopLimit(final byte hopLimit) { - this.hopLimit = hopLimit; - return this; - } - - /** - * Gets source address. - * - * @return the IPv6 source address - */ - public byte[] getSourceAddress() { - return this.sourceAddress; - } - - /** - * Sets source address. - * - * @param sourceAddress the IPv6 source address to set - * @return this - */ - public IPv6 setSourceAddress(final byte[] sourceAddress) { - this.sourceAddress = Arrays.copyOfRange(sourceAddress, 0, Ip6Address.BYTE_LENGTH); - return this; - } - - /** - * Gets destination address. - * - * @return the IPv6 destination address - */ - public byte[] getDestinationAddress() { - return this.destinationAddress; - } - - /** - * Sets destination address. - * - * @param destinationAddress the IPv6 destination address to set - * @return this - */ - public IPv6 setDestinationAddress(final byte[] destinationAddress) { - this.destinationAddress = Arrays.copyOfRange(destinationAddress, 0, Ip6Address.BYTE_LENGTH); - return this; - } - - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - - this.payloadLength = 0; - if (payloadData != null) { - this.payloadLength = (short) payloadData.length; - } - - final byte[] data = new byte[FIXED_HEADER_LENGTH + payloadLength]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.putInt((this.version & 0xf) << 28 | (this.trafficClass & 0xff) << 20 | this.flowLabel & 0xfffff); - bb.putShort(this.payloadLength); - bb.put(this.nextHeader); - bb.put(this.hopLimit); - bb.put(this.sourceAddress, 0, Ip6Address.BYTE_LENGTH); - bb.put(this.destinationAddress, 0, Ip6Address.BYTE_LENGTH); - - if (payloadData != null) { - bb.put(payloadData); - } - - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - int iscratch; - - iscratch = bb.getInt(); - this.version = (byte) (iscratch >> 28 & 0xf); - this.trafficClass = (byte) (iscratch >> 20 & 0xff); - this.flowLabel = iscratch & 0xfffff; - this.payloadLength = bb.getShort(); - this.nextHeader = bb.get(); - this.hopLimit = bb.get(); - bb.get(this.sourceAddress, 0, Ip6Address.BYTE_LENGTH); - bb.get(this.destinationAddress, 0, Ip6Address.BYTE_LENGTH); - - Deserializer deserializer; - if (IPv6.PROTOCOL_DESERIALIZER_MAP.containsKey(this.nextHeader)) { - deserializer = IPv6.PROTOCOL_DESERIALIZER_MAP.get(this.nextHeader); - } else { - deserializer = Data.deserializer(); - } - try { - this.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - this.payload.setParent(this); - } catch (DeserializationException e) { - return this; - } - - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 2521; - int result = super.hashCode(); - ByteBuffer bb; - bb = ByteBuffer.wrap(this.destinationAddress); - for (int i = 0; i < 4; i++) { - result = prime * result + bb.getInt(); - } - result = prime * result + this.trafficClass; - result = prime * result + this.flowLabel; - result = prime * result + this.hopLimit; - result = prime * result + this.nextHeader; - result = prime * result + this.payloadLength; - bb = ByteBuffer.wrap(this.sourceAddress); - for (int i = 0; i < 4; i++) { - result = prime * result + bb.getInt(); - } - result = prime * result + this.version; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof IPv6)) { - return false; - } - final IPv6 other = (IPv6) obj; - if (!Arrays.equals(this.destinationAddress, other.destinationAddress)) { - return false; - } - if (this.trafficClass != other.trafficClass) { - return false; - } - if (this.flowLabel != other.flowLabel) { - return false; - } - if (this.hopLimit != other.hopLimit) { - return false; - } - if (this.nextHeader != other.nextHeader) { - return false; - } - if (this.payloadLength != other.payloadLength) { - return false; - } - if (!Arrays.equals(this.sourceAddress, other.sourceAddress)) { - return false; - } - return true; - } - - /** - * Deserializer function for IPv6 packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, FIXED_HEADER_LENGTH); - - IPv6 ipv6 = new IPv6(); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - - int iscratch = bb.getInt(); - - ipv6.version = (byte) (iscratch >> 28 & 0xf); - ipv6.trafficClass = (byte) (iscratch >> 20 & 0xff); - ipv6.flowLabel = iscratch & 0xfffff; - ipv6.payloadLength = bb.getShort(); - ipv6.nextHeader = bb.get(); - ipv6.hopLimit = bb.get(); - bb.get(ipv6.sourceAddress, 0, Ip6Address.BYTE_LENGTH); - bb.get(ipv6.destinationAddress, 0, Ip6Address.BYTE_LENGTH); - - Deserializer deserializer; - if (IPv6.PROTOCOL_DESERIALIZER_MAP.containsKey(ipv6.nextHeader)) { - deserializer = IPv6.PROTOCOL_DESERIALIZER_MAP.get(ipv6.nextHeader); - } else { - deserializer = Data.deserializer(); - } - ipv6.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - ipv6.payload.setParent(ipv6); - - return ipv6; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip4Address.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip4Address.java deleted file mode 100644 index 114f126c..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip4Address.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.net.InetAddress; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.nio.ByteBuffer; -import java.util.Arrays; - -import com.google.common.net.InetAddresses; - -/** - * A class representing an IPv4 address. - * This class is immutable. - */ -public final class Ip4Address extends IpAddress { - public static final IpAddress.Version VERSION = IpAddress.Version.INET; - public static final int BYTE_LENGTH = IpAddress.INET_BYTE_LENGTH; - public static final int BIT_LENGTH = IpAddress.INET_BIT_LENGTH; - - /** - * Constructor for given IP address version and address octets. - * - * @param value the IP address value stored in network byte order - * (i.e., the most significant byte first) - * @throws IllegalArgumentException if the arguments are invalid - */ - private Ip4Address(byte[] value) { - super(VERSION, value); - } - - /** - * Returns the integer value of this IPv4 address. - * - * @return the IPv4 address's value as an integer - */ - public int toInt() { - ByteBuffer bb = ByteBuffer.wrap(super.toOctets()); - return bb.getInt(); - } - - /** - * Converts an integer into an IPv4 address. - * - * @param value an integer representing an IPv4 address value - * @return an IPv4 address - */ - public static Ip4Address valueOf(int value) { - byte[] bytes = - ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array(); - return new Ip4Address(bytes); - } - - /** - * Converts a byte array into an IPv4 address. - * - * @param value the IPv4 address value stored in network byte order - * (i.e., the most significant byte first) - * @return an IPv4 address - * @throws IllegalArgumentException if the argument is invalid - */ - public static Ip4Address valueOf(byte[] value) { - return new Ip4Address(value); - } - - /** - * Converts a byte array and a given offset from the beginning of the - * array into an IPv4 address. - *

- * The IP address is stored in network byte order (i.e., the most - * significant byte first). - *

- * @param value the value to use - * @param offset the offset in bytes from the beginning of the byte array - * @return an IPv4 address - * @throws IllegalArgumentException if the arguments are invalid - */ - public static Ip4Address valueOf(byte[] value, int offset) { - IpAddress.checkArguments(VERSION, value, offset); - byte[] bc = Arrays.copyOfRange(value, offset, value.length); - return Ip4Address.valueOf(bc); - } - - /** - * Converts an InetAddress into an IPv4 address. - * - * @param inetAddress the InetAddress value to use. It must contain an IPv4 - * address - * @return an IPv4 address - * @throws IllegalArgumentException if the argument is invalid - */ - public static Ip4Address valueOf(InetAddress inetAddress) { - byte[] bytes = inetAddress.getAddress(); - if (inetAddress instanceof Inet4Address) { - return new Ip4Address(bytes); - } - if ((inetAddress instanceof Inet6Address) || - (bytes.length == INET6_BYTE_LENGTH)) { - final String msg = "Invalid IPv4 version address string: " + - inetAddress.toString(); - throw new IllegalArgumentException(msg); - } - // Use the number of bytes as a hint - if (bytes.length == INET_BYTE_LENGTH) { - return new Ip4Address(bytes); - } - final String msg = "Unrecognized IP version address string: " + - inetAddress.toString(); - throw new IllegalArgumentException(msg); - } - - /** - * Converts an IPv4 string literal (e.g., "10.2.3.4") into an IP address. - * - * @param value an IPv4 address value in string form - * @return an IPv4 address - * @throws IllegalArgumentException if the argument is invalid - */ - public static Ip4Address valueOf(String value) { - InetAddress inetAddress = null; - try { - inetAddress = InetAddresses.forString(value); - } catch (IllegalArgumentException e) { - final String msg = "Invalid IP address string: " + value; - throw new IllegalArgumentException(msg); - } - return valueOf(inetAddress); - } - - /** - * Creates an IPv4 network mask prefix. - * - * @param prefixLength the length of the mask prefix. Must be in the - * interval [0, 32] - * @return a new IPv4 address that contains a mask prefix of the - * specified length - * @throws IllegalArgumentException if the argument is invalid - */ - public static Ip4Address makeMaskPrefix(int prefixLength) { - byte[] mask = IpAddress.makeMaskPrefixArray(VERSION, prefixLength); - return new Ip4Address(mask); - } - - /** - * Creates an IPv4 address by masking it with a network mask of given - * mask length. - * - * @param address the address to mask - * @param prefixLength the length of the mask prefix. Must be in the - * interval [0, 32] - * @return a new IPv4 address that is masked with a mask prefix of the - * specified length - * @throws IllegalArgumentException if the prefix length is invalid - */ - public static Ip4Address makeMaskedAddress(final Ip4Address address, - int prefixLength) { - byte[] net = makeMaskedAddressArray(address, prefixLength); - return Ip4Address.valueOf(net); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip4Prefix.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip4Prefix.java deleted file mode 100644 index fc442c3e..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip4Prefix.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -/** - * The class representing an IPv4 network address. - * This class is immutable. - */ -public final class Ip4Prefix extends IpPrefix { - public static final IpAddress.Version VERSION = IpAddress.Version.INET; - // Maximum network mask length - public static final int MAX_MASK_LENGTH = IpPrefix.MAX_INET_MASK_LENGTH; - - /** - * Constructor for given IPv4 address, and a prefix length. - * - * @param address the IPv4 address - * @param prefixLength the prefix length - * @throws IllegalArgumentException if the prefix length value is invalid - */ - private Ip4Prefix(Ip4Address address, int prefixLength) { - super(address, prefixLength); - } - - /** - * Returns the IPv4 address value of the prefix. - * - * @return the IPv4 address value of the prefix - */ - public Ip4Address address() { - IpAddress a = super.address(); - return (Ip4Address) a; - } - - /** - * Converts an integer and a prefix length into an IPv4 prefix. - * - * @param address an integer representing the IPv4 address - * @param prefixLength the prefix length - * @return an IPv4 prefix - * @throws IllegalArgumentException if the prefix length value is invalid - */ - public static Ip4Prefix valueOf(int address, int prefixLength) { - return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength); - } - - /** - * Converts a byte array and a prefix length into an IPv4 prefix. - * - * @param address the IPv4 address value stored in network byte order - * @param prefixLength the prefix length - * @return an IPv4 prefix - * @throws IllegalArgumentException if the prefix length value is invalid - */ - public static Ip4Prefix valueOf(byte[] address, int prefixLength) { - return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength); - } - - /** - * Converts an IPv4 address and a prefix length into an IPv4 prefix. - * - * @param address the IPv4 address - * @param prefixLength the prefix length - * @return an IPv4 prefix - * @throws IllegalArgumentException if the prefix length value is invalid - */ - public static Ip4Prefix valueOf(Ip4Address address, int prefixLength) { - return new Ip4Prefix(address, prefixLength); - } - - /** - * Converts a CIDR (slash) notation string (e.g., "10.1.0.0/16") - * into an IPv4 prefix. - * - * @param address an IP prefix in string form (e.g., "10.1.0.0/16") - * @return an IPv4 prefix - * @throws IllegalArgumentException if the arguments are invalid - */ - public static Ip4Prefix valueOf(String address) { - final String[] parts = address.split("/"); - if (parts.length != 2) { - String msg = "Malformed IPv4 prefix string: " + address + ". " + - "Address must take form \"x.x.x.x/y\""; - throw new IllegalArgumentException(msg); - } - Ip4Address ipAddress = Ip4Address.valueOf(parts[0]); - int prefixLength = Integer.parseInt(parts[1]); - - return new Ip4Prefix(ipAddress, prefixLength); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip6Address.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip6Address.java deleted file mode 100644 index d353422b..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip6Address.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.net.InetAddress; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.util.Arrays; - -import com.google.common.net.InetAddresses; - -/** - * A class representing an IPv6 address. - * This class is immutable. - */ -public final class Ip6Address extends IpAddress { - public static final IpAddress.Version VERSION = IpAddress.Version.INET6; - public static final int BYTE_LENGTH = IpAddress.INET6_BYTE_LENGTH; - public static final int BIT_LENGTH = IpAddress.INET6_BIT_LENGTH; - - /** - * Constructor for given IP address version and address octets. - * - * @param value the IP address value stored in network byte order - * (i.e., the most significant byte first) - * @throws IllegalArgumentException if the arguments are invalid - */ - private Ip6Address(byte[] value) { - super(VERSION, value); - } - - /** - * Converts a byte array into an IPv6 address. - * - * @param value the IPv6 address value stored in network byte order - * (i.e., the most significant byte first) - * @return an IPv6 address - * @throws IllegalArgumentException if the argument is invalid - */ - public static Ip6Address valueOf(byte[] value) { - return new Ip6Address(value); - } - - /** - * Converts a byte array and a given offset from the beginning of the - * array into an IPv6 address. - *

- * The IP address is stored in network byte order (i.e., the most - * significant byte first). - *

- * @param value the value to use - * @param offset the offset in bytes from the beginning of the byte array - * @return an IPv6 address - * @throws IllegalArgumentException if the arguments are invalid - */ - public static Ip6Address valueOf(byte[] value, int offset) { - IpAddress.checkArguments(VERSION, value, offset); - byte[] bc = Arrays.copyOfRange(value, offset, value.length); - return Ip6Address.valueOf(bc); - } - - /** - * Converts an InetAddress into an IPv6 address. - * - * @param inetAddress the InetAddress value to use. It must contain an IPv6 - * address - * @return an IPv6 address - * @throws IllegalArgumentException if the argument is invalid - */ - public static Ip6Address valueOf(InetAddress inetAddress) { - byte[] bytes = inetAddress.getAddress(); - if (inetAddress instanceof Inet6Address) { - return new Ip6Address(bytes); - } - if ((inetAddress instanceof Inet4Address) || - (bytes.length == INET_BYTE_LENGTH)) { - final String msg = "Invalid IPv6 version address string: " + - inetAddress.toString(); - throw new IllegalArgumentException(msg); - } - // Use the number of bytes as a hint - if (bytes.length == INET6_BYTE_LENGTH) { - return new Ip6Address(bytes); - } - final String msg = "Unrecognized IP version address string: " + - inetAddress.toString(); - throw new IllegalArgumentException(msg); - } - - /** - * Converts an IPv6 string literal (e.g., "1111:2222::8888") into an IP - * address. - * - * @param value an IPv6 address value in string form - * @return an IPv6 address - * @throws IllegalArgumentException if the argument is invalid - */ - public static Ip6Address valueOf(String value) { - InetAddress inetAddress = null; - try { - inetAddress = InetAddresses.forString(value); - } catch (IllegalArgumentException e) { - final String msg = "Invalid IP address string: " + value; - throw new IllegalArgumentException(msg); - } - return valueOf(inetAddress); - } - - /** - * Creates an IPv6 network mask prefix. - * - * @param prefixLength the length of the mask prefix. Must be in the - * interval [0, 128] - * @return a new IPv6 address that contains a mask prefix of the - * specified length - * @throws IllegalArgumentException if the arguments are invalid - */ - public static Ip6Address makeMaskPrefix(int prefixLength) { - byte[] mask = IpAddress.makeMaskPrefixArray(VERSION, prefixLength); - return new Ip6Address(mask); - } - - /** - * Creates an IPv6 address by masking it with a network mask of given - * mask length. - * - * @param address the address to mask - * @param prefixLength the length of the mask prefix. Must be in the - * interval [0, 128] - * @return a new IPv6 address that is masked with a mask prefix of the - * specified length - * @throws IllegalArgumentException if the prefix length is invalid - */ - public static Ip6Address makeMaskedAddress(final Ip6Address address, - int prefixLength) { - byte[] net = makeMaskedAddressArray(address, prefixLength); - return Ip6Address.valueOf(net); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip6Prefix.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip6Prefix.java deleted file mode 100644 index 4ea9099b..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/Ip6Prefix.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -/** - * The class representing an IPv6 network address. - * This class is immutable. - */ -public final class Ip6Prefix extends IpPrefix { - public static final IpAddress.Version VERSION = IpAddress.Version.INET6; - // Maximum network mask length - public static final int MAX_MASK_LENGTH = IpPrefix.MAX_INET6_MASK_LENGTH; - - /** - * Constructor for given IPv6 address, and a prefix length. - * - * @param address the IPv6 address - * @param prefixLength the prefix length - * @throws IllegalArgumentException if the prefix length value is invalid - */ - private Ip6Prefix(Ip6Address address, int prefixLength) { - super(address, prefixLength); - } - - /** - * Returns the IPv6 address value of the prefix. - * - * @return the IPv6 address value of the prefix - */ - public Ip6Address address() { - IpAddress a = super.address(); - return (Ip6Address) a; - } - - /** - * Converts a byte array and a prefix length into an IPv6 prefix. - * - * @param address the IPv6 address value stored in network byte order - * @param prefixLength the prefix length - * @return an IPv6 prefix - * @throws IllegalArgumentException if the prefix length value is invalid - */ - public static Ip6Prefix valueOf(byte[] address, int prefixLength) { - return new Ip6Prefix(Ip6Address.valueOf(address), prefixLength); - } - - /** - * Converts an IPv6 address and a prefix length into an IPv6 prefix. - * - * @param address the IPv6 address - * @param prefixLength the prefix length - * @return an IPv6 prefix - * @throws IllegalArgumentException if the prefix length value is invalid - */ - public static Ip6Prefix valueOf(Ip6Address address, int prefixLength) { - return new Ip6Prefix(address, prefixLength); - } - - /** - * Converts a CIDR (slash) notation string (e.g., "1111:2222::/64") - * into an IPv6 prefix. - * - * @param address an IP prefix in string form (e.g.,"1111:2222::/64") - * @return an IPv6 prefix - * @throws IllegalArgumentException if the arguments are invalid - */ - public static Ip6Prefix valueOf(String address) { - final String[] parts = address.split("/"); - if (parts.length != 2) { - String msg = "Malformed IPv6 prefix string: " + address + ". " + - "Address must take form " + - "\"xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/y\""; - throw new IllegalArgumentException(msg); - } - Ip6Address ipAddress = Ip6Address.valueOf(parts[0]); - int prefixLength = Integer.parseInt(parts[1]); - - return new Ip6Prefix(ipAddress, prefixLength); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IpAddress.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IpAddress.java deleted file mode 100644 index 5fdd3276..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IpAddress.java +++ /dev/null @@ -1,559 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.net.InetAddress; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.Objects; -import com.google.common.net.InetAddresses; -import com.google.common.primitives.UnsignedBytes; - - -/** - * A class representing an IP address. - * This class is immutable. - */ -public class IpAddress implements Comparable { - private static final int BIT_MASK = 0x000000ff; - - // IP Versions - public enum Version { INET, INET6 }; - - // lengths of address, in bytes - public static final int INET_BYTE_LENGTH = 4; - public static final int INET_BIT_LENGTH = INET_BYTE_LENGTH * Byte.SIZE; - public static final int INET6_BYTE_LENGTH = 16; - public static final int INET6_BIT_LENGTH = INET6_BYTE_LENGTH * Byte.SIZE; - - private final Version version; - private final byte[] octets; - - /** - * Constructor for given IP address version and address octets. - * - * @param version the IP address version - * @param value the IP address value stored in network byte order - * (i.e., the most significant byte first) - * @throws IllegalArgumentException if the arguments are invalid - */ - protected IpAddress(Version version, byte[] value) { - checkArguments(version, value, 0); - this.version = version; - switch (version) { - case INET: - this.octets = Arrays.copyOf(value, INET_BYTE_LENGTH); - break; - case INET6: - this.octets = Arrays.copyOf(value, INET6_BYTE_LENGTH); - break; - default: - // Should not be reached - this.octets = null; - break; - } - } - - /** - * Returns the IP version of this address. - * - * @return the version - */ - public Version version() { - return this.version; - } - - /** - * Tests whether the IP version of this address is IPv4. - * - * @return true if the IP version of this address is IPv4, otherwise false. - */ - public boolean isIp4() { - return (version() == Ip4Address.VERSION); - } - - /** - * Tests whether the IP version of this address is IPv6. - * - * @return true if the IP version of this address is IPv6, otherwise false. - */ - public boolean isIp6() { - return (version() == Ip6Address.VERSION); - } - - /** - * Gets the {@link Ip4Address} view of the IP address. - * - * @return the {@link Ip4Address} view of the IP address if it is IPv4, - * otherwise null - */ - public Ip4Address getIp4Address() { - if (!isIp4()) { - return null; - } - - // Return this object itself if it is already instance of Ip4Address - if (this instanceof Ip4Address) { - return (Ip4Address) this; - } - return Ip4Address.valueOf(octets); - } - - /** - * Gets the {@link Ip6Address} view of the IP address. - * - * @return the {@link Ip6Address} view of the IP address if it is IPv6, - * otherwise null - */ - public Ip6Address getIp6Address() { - if (!isIp6()) { - return null; - } - - // Return this object itself if it is already instance of Ip6Address - if (this instanceof Ip6Address) { - return (Ip6Address) this; - } - return Ip6Address.valueOf(octets); - } - - /** - * Returns the IP address as a byte array. - * - * @return a byte array - */ - public byte[] toOctets() { - return Arrays.copyOf(octets, octets.length); - } - - /** - * Computes the IP address byte length for a given IP version. - * - * @param version the IP version - * @return the IP address byte length for the IP version - * @throws IllegalArgumentException if the IP version is invalid - */ - public static int byteLength(Version version) { - switch (version) { - case INET: - return INET_BYTE_LENGTH; - case INET6: - return INET6_BYTE_LENGTH; - default: - String msg = "Invalid IP version " + version; - throw new IllegalArgumentException(msg); - } - } - - /** - * Converts an integer into an IPv4 address. - * - * @param value an integer representing an IPv4 address value - * @return an IP address - */ - public static IpAddress valueOf(int value) { - byte[] bytes = - ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array(); - return new IpAddress(Version.INET, bytes); - } - - /** - * Converts a byte array into an IP address. - * - * @param version the IP address version - * @param value the IP address value stored in network byte order - * (i.e., the most significant byte first) - * @return an IP address - * @throws IllegalArgumentException if the arguments are invalid - */ - public static IpAddress valueOf(Version version, byte[] value) { - return new IpAddress(version, value); - } - - /** - * Converts a byte array and a given offset from the beginning of the - * array into an IP address. - *

- * The IP address is stored in network byte order (i.e., the most - * significant byte first). - *

- * @param version the IP address version - * @param value the value to use - * @param offset the offset in bytes from the beginning of the byte array - * @return an IP address - * @throws IllegalArgumentException if the arguments are invalid - */ - public static IpAddress valueOf(Version version, byte[] value, - int offset) { - checkArguments(version, value, offset); - byte[] bc = Arrays.copyOfRange(value, offset, value.length); - return IpAddress.valueOf(version, bc); - } - - /** - * Converts an InetAddress into an IP address. - * - * @param inetAddress the InetAddress value to use - * @return an IP address - * @throws IllegalArgumentException if the argument is invalid - */ - public static IpAddress valueOf(InetAddress inetAddress) { - byte[] bytes = inetAddress.getAddress(); - if (inetAddress instanceof Inet4Address) { - return new IpAddress(Version.INET, bytes); - } - if (inetAddress instanceof Inet6Address) { - return new IpAddress(Version.INET6, bytes); - } - // Use the number of bytes as a hint - if (bytes.length == INET_BYTE_LENGTH) { - return new IpAddress(Version.INET, bytes); - } - if (bytes.length == INET6_BYTE_LENGTH) { - return new IpAddress(Version.INET6, bytes); - } - final String msg = "Unrecognized IP version address string: " + - inetAddress.toString(); - throw new IllegalArgumentException(msg); - } - - /** - * Converts an IPv4 or IPv6 string literal (e.g., "10.2.3.4" or - * "1111:2222::8888") into an IP address. - * - * @param value an IP address value in string form - * @return an IP address - * @throws IllegalArgumentException if the argument is invalid - */ - public static IpAddress valueOf(String value) { - InetAddress inetAddress = null; - try { - inetAddress = InetAddresses.forString(value); - } catch (IllegalArgumentException e) { - final String msg = "Invalid IP address string: " + value; - throw new IllegalArgumentException(msg); - } - return valueOf(inetAddress); - } - - /** - * Creates an IP network mask prefix. - * - * @param version the IP address version - * @param prefixLength the length of the mask prefix. Must be in the - * interval [0, 32] for IPv4, or [0, 128] for IPv6 - * @return a new IP address that contains a mask prefix of the - * specified length - * @throws IllegalArgumentException if the arguments are invalid - */ - public static IpAddress makeMaskPrefix(Version version, int prefixLength) { - byte[] mask = makeMaskPrefixArray(version, prefixLength); - return new IpAddress(version, mask); - } - - /** - * Creates an IP address by masking it with a network mask of given - * mask length. - * - * @param address the address to mask - * @param prefixLength the length of the mask prefix. Must be in the - * interval [0, 32] for IPv4, or [0, 128] for IPv6 - * @return a new IP address that is masked with a mask prefix of the - * specified length - * @throws IllegalArgumentException if the prefix length is invalid - */ - public static IpAddress makeMaskedAddress(final IpAddress address, - int prefixLength) { - if (address instanceof Ip4Address) { - Ip4Address ip4a = (Ip4Address) address; - return Ip4Address.makeMaskedAddress(ip4a, prefixLength); - } else if (address instanceof Ip6Address) { - Ip6Address ip6a = (Ip6Address) address; - return Ip6Address.makeMaskedAddress(ip6a, prefixLength); - } else { - byte[] net = makeMaskedAddressArray(address, prefixLength); - return IpAddress.valueOf(address.version(), net); - } - } - - /** - * Check if this IP address is zero. - * - * @return true if this address is zero - */ - public boolean isZero() { - for (byte b : octets) { - if (b != 0) { - return false; - } - } - return true; - } - - /** - * Check if this IP address is self-assigned. - * - * @return true if this address is self-assigned - */ - public boolean isSelfAssigned() { - return isIp4() && octets[0] == (byte) 169; - } - - @Override - public int compareTo(IpAddress o) { - // Compare first the version - if (this.version != o.version) { - return this.version.compareTo(o.version); - } - - // Compare the bytes, one-by-one - for (int i = 0; i < this.octets.length; i++) { - if (this.octets[i] != o.octets[i]) { - return UnsignedBytes.compare(this.octets[i], o.octets[i]); - } - } - return 0; // Equal - } - - @Override - public int hashCode() { - return Objects.hash(version, Arrays.hashCode(octets)); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if ((obj == null) || (!(obj instanceof IpAddress))) { - return false; - } - IpAddress other = (IpAddress) obj; - return (version == other.version) && - Arrays.equals(octets, other.octets); - } - - @Override - /* - * (non-Javadoc) - * The string representation of the IP address: "x.x.x.x" for IPv4 - * addresses, or ':' separated string for IPv6 addresses. - * - * @see java.lang.Object#toString() - */ - public String toString() { - // FIXME InetAddress is super slow - switch (version) { - case INET: - return String.format("%d.%d.%d.%d", octets[0] & 0xff, - octets[1] & 0xff, - octets[2] & 0xff, - octets[3] & 0xff); - case INET6: - default: - return ipv6ToStringHelper(); - } - } - - /** - * Generates an IP prefix. - * - * @return the IP prefix of the IP address - */ - public IpPrefix toIpPrefix() { - - if (isIp4()) { - return IpPrefix.valueOf(new IpAddress(Version.INET, octets), - Ip4Address.BIT_LENGTH); - } else { - return IpPrefix.valueOf(new IpAddress(Version.INET6, octets), - Ip6Address.BIT_LENGTH); - } - } - - /** - * Gets the IP address name for the IP address version. - * - * @param version the IP address version - * @return the IP address name for the IP address version - */ - private static String addressName(Version version) { - switch (version) { - case INET: - return "IPv4"; - case INET6: - return "IPv6"; - default: - break; - } - return "UnknownIP(" + version + ")"; - } - - /** - * Checks whether the arguments are valid. - * - * @param version the IP address version - * @param value the IP address value stored in a byte array - * @param offset the offset in bytes from the beginning of the byte - * array with the address - * @throws IllegalArgumentException if any of the arguments is invalid - */ - static void checkArguments(Version version, byte[] value, int offset) { - // Check the offset and byte array length - int addrByteLength = byteLength(version); - if ((offset < 0) || (offset + addrByteLength > value.length)) { - String msg; - if (value.length < addrByteLength) { - msg = "Invalid " + addressName(version) + - " address array: array length: " + value.length + - ". Must be at least " + addrByteLength; - } else { - msg = "Invalid " + addressName(version) + - " address array: array offset: " + offset + - ". Must be in the interval [0, " + - (value.length - addrByteLength) + "]"; - } - throw new IllegalArgumentException(msg); - } - } - - /** - * Creates a byte array for IP network mask prefix. - * - * @param version the IP address version - * @param prefixLength the length of the mask prefix. Must be in the - * interval [0, 32] for IPv4, or [0, 128] for IPv6 - * @return a byte array that contains a mask prefix of the - * specified length - * @throws IllegalArgumentException if the arguments are invalid - */ - static byte[] makeMaskPrefixArray(Version version, int prefixLength) { - int addrByteLength = byteLength(version); - int addrBitLength = addrByteLength * Byte.SIZE; - - // Verify the prefix length - if ((prefixLength < 0) || (prefixLength > addrBitLength)) { - final String msg = "Invalid IP prefix length: " + prefixLength + - ". Must be in the interval [0, " + addrBitLength + "]."; - throw new IllegalArgumentException(msg); - } - - // Number of bytes and extra bits that should be all 1s - int maskBytes = prefixLength / Byte.SIZE; - int maskBits = prefixLength % Byte.SIZE; - byte[] mask = new byte[addrByteLength]; - - // Set the bytes and extra bits to 1s - for (int i = 0; i < maskBytes; i++) { - mask[i] = (byte) 0xff; // Set mask bytes to 1s - } - for (int i = maskBytes; i < addrByteLength; i++) { - mask[i] = 0; // Set remaining bytes to 0s - } - if (maskBits > 0) { - mask[maskBytes] = (byte) (0xff << (Byte.SIZE - maskBits)); - } - return mask; - } - - /** - * Creates a byte array that represents an IP address masked with - * a network mask of given mask length. - * - * @param addr the address to mask - * @param prefixLength the length of the mask prefix. Must be in the - * interval [0, 32] for IPv4, or [0, 128] for IPv6 - * @return a byte array that represents the IP address masked with - * a mask prefix of the specified length - * @throws IllegalArgumentException if the prefix length is invalid - */ - static byte[] makeMaskedAddressArray(final IpAddress addr, - int prefixLength) { - byte[] mask = IpAddress.makeMaskPrefixArray(addr.version(), - prefixLength); - byte[] net = new byte[mask.length]; - - // Mask each byte - for (int i = 0; i < net.length; i++) { - net[i] = (byte) (addr.octets[i] & mask[i]); - } - return net; - } - - /** - * Creates a string based on the IPv6 recommendations for canonical representations found here: - * https://tools.ietf.org/html/rfc5952#section-1. - * @return A properly formatted IPv6 canonical representation. - */ - private String ipv6ToStringHelper() { - //Populate a buffer with the string of the full address with leading zeros stripped - StringBuffer buff = new StringBuffer(); - buff.append(String.format("%x:%x:%x:%x:%x:%x:%x:%x", - (((octets[0] & BIT_MASK) << 8) | (octets[1] & BIT_MASK)), - (((octets[2] & BIT_MASK) << 8) | (octets[3] & BIT_MASK)), - (((octets[4] & BIT_MASK) << 8) | (octets[5] & BIT_MASK)), - (((octets[6] & BIT_MASK) << 8) | (octets[7] & BIT_MASK)), - (((octets[8] & BIT_MASK) << 8) | (octets[9] & BIT_MASK)), - (((octets[10] & BIT_MASK) << 8) | (octets[11] & BIT_MASK)), - (((octets[12] & BIT_MASK) << 8) | (octets[13] & BIT_MASK)), - (((octets[14] & BIT_MASK) << 8) | (octets[15] & BIT_MASK)))); - //Initialize variables for tracking longest zero subsequence, tiebreaking by first occurence - int longestSeqStart, longestSeqLen, currSeqStart, currSeqLen; - longestSeqStart = 0; - longestSeqLen = 0; - currSeqStart = 0; - currSeqLen = 0; - - for (int index = 0; index < buff.length(); index++) { - if (buff.charAt(index) == ':') { - if (currSeqLen != 0 && buff.charAt(index + 1) == '0') { - currSeqLen += 1; - } - } else if (buff.charAt(index) == '0' && ((index == 0) || (buff.charAt(index - 1) == ':'))) { - if (currSeqLen == 0) { - currSeqStart = index; - } - currSeqLen += 1; - } else { - if (currSeqLen > longestSeqLen) { - longestSeqStart = currSeqStart; - longestSeqLen = currSeqLen; - } - currSeqLen = 0; - } - } - - if (currSeqLen > longestSeqLen) { - longestSeqLen = currSeqLen; - longestSeqStart = currSeqStart; - } - if (longestSeqLen > 1) { - if (buff.length() == (longestSeqStart + longestSeqLen)) { - buff.append(':'); - } - - buff.delete(longestSeqStart, longestSeqStart + longestSeqLen); - - if (longestSeqStart == 0) { - buff.insert(0, ':'); - } - } - - return buff.toString(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IpPrefix.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IpPrefix.java deleted file mode 100644 index 14d07fed..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/IpPrefix.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.util.Objects; - -/** - * A class representing an IP prefix. A prefix consists of an IP address and - * a subnet mask. - * This class is immutable. - *

- * NOTE: The stored IP address in the result IP prefix is masked to - * contain zeroes in all bits after the prefix length. - *

- */ -public class IpPrefix { - // Maximum network mask length - public static final int MAX_INET_MASK_LENGTH = IpAddress.INET_BIT_LENGTH; - public static final int MAX_INET6_MASK_LENGTH = IpAddress.INET6_BIT_LENGTH; - - private final IpAddress address; - private final short prefixLength; - - /** - * Constructor for given IP address, and a prefix length. - * - * @param address the IP address - * @param prefixLength the prefix length - * @throws IllegalArgumentException if the prefix length value is invalid - */ - protected IpPrefix(IpAddress address, int prefixLength) { - checkPrefixLength(address.version(), prefixLength); - this.address = IpAddress.makeMaskedAddress(address, prefixLength); - this.prefixLength = (short) prefixLength; - } - - /** - * Returns the IP version of the prefix. - * - * @return the IP version of the prefix - */ - public IpAddress.Version version() { - return address.version(); - } - - /** - * Tests whether the IP version of this prefix is IPv4. - * - * @return true if the IP version of this prefix is IPv4, otherwise false. - */ - public boolean isIp4() { - return address.isIp4(); - } - - /** - * Tests whether the IP version of this prefix is IPv6. - * - * @return true if the IP version of this prefix is IPv6, otherwise false. - */ - public boolean isIp6() { - return address.isIp6(); - } - - /** - * Returns the IP address value of the prefix. - * - * @return the IP address value of the prefix - */ - public IpAddress address() { - return address; - } - - /** - * Returns the IP address prefix length. - * - * @return the IP address prefix length - */ - public int prefixLength() { - return prefixLength; - } - - /** - * Gets the {@link Ip4Prefix} view of the IP prefix. - * - * @return the {@link Ip4Prefix} view of the IP prefix if it is IPv4, - * otherwise null - */ - public Ip4Prefix getIp4Prefix() { - if (!isIp4()) { - return null; - } - - // Return this object itself if it is already instance of Ip4Prefix - if (this instanceof Ip4Prefix) { - return (Ip4Prefix) this; - } - return Ip4Prefix.valueOf(address.getIp4Address(), prefixLength); - } - - /** - * Gets the {@link Ip6Prefix} view of the IP prefix. - * - * @return the {@link Ip6Prefix} view of the IP prefix if it is IPv6, - * otherwise null - */ - public Ip6Prefix getIp6Prefix() { - if (!isIp6()) { - return null; - } - - // Return this object itself if it is already instance of Ip6Prefix - if (this instanceof Ip6Prefix) { - return (Ip6Prefix) this; - } - return Ip6Prefix.valueOf(address.getIp6Address(), prefixLength); - } - - /** - * Converts an integer and a prefix length into an IPv4 prefix. - * - * @param address an integer representing the IPv4 address - * @param prefixLength the prefix length - * @return an IP prefix - * @throws IllegalArgumentException if the prefix length value is invalid - */ - public static IpPrefix valueOf(int address, int prefixLength) { - return new IpPrefix(IpAddress.valueOf(address), prefixLength); - } - - /** - * Converts a byte array and a prefix length into an IP prefix. - * - * @param version the IP address version - * @param address the IP address value stored in network byte order - * @param prefixLength the prefix length - * @return an IP prefix - * @throws IllegalArgumentException if the prefix length value is invalid - */ - public static IpPrefix valueOf(IpAddress.Version version, byte[] address, - int prefixLength) { - return new IpPrefix(IpAddress.valueOf(version, address), prefixLength); - } - - /** - * Converts an IP address and a prefix length into an IP prefix. - * - * @param address the IP address - * @param prefixLength the prefix length - * @return an IP prefix - * @throws IllegalArgumentException if the prefix length value is invalid - */ - public static IpPrefix valueOf(IpAddress address, int prefixLength) { - return new IpPrefix(address, prefixLength); - } - - /** - * Converts a CIDR (slash) notation string (e.g., "10.1.0.0/16" or - * "1111:2222::/64") into an IP prefix. - * - * @param address an IP prefix in string form (e.g. "10.1.0.0/16" or - * "1111:2222::/64") - * @return an IP prefix - * @throws IllegalArgumentException if the arguments are invalid - */ - public static IpPrefix valueOf(String address) { - final String[] parts = address.split("/"); - if (parts.length != 2) { - String msg = "Malformed IP prefix string: " + address + ". " + - "Address must take form \"x.x.x.x/y\" or " + - "\"xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/y\""; - throw new IllegalArgumentException(msg); - } - IpAddress ipAddress = IpAddress.valueOf(parts[0]); - int prefixLength = Integer.parseInt(parts[1]); - - return new IpPrefix(ipAddress, prefixLength); - } - - /** - * Determines whether a given IP prefix is contained within this prefix. - * - * @param other the IP prefix to test - * @return true if the other IP prefix is contained in this prefix, - * otherwise false - */ - public boolean contains(IpPrefix other) { - if (version() != other.version()) { - return false; - } - - if (this.prefixLength > other.prefixLength) { - return false; // This prefix has smaller prefix size - } - - // - // Mask the other address with my prefix length. - // If the other prefix is within this prefix, the masked address must - // be same as the address of this prefix. - // - IpAddress maskedAddr = - IpAddress.makeMaskedAddress(other.address, this.prefixLength); - return this.address.equals(maskedAddr); - } - - /** - * Determines whether a given IP address is contained within this prefix. - * - * @param other the IP address to test - * @return true if the IP address is contained in this prefix, otherwise - * false - */ - public boolean contains(IpAddress other) { - if (version() != other.version()) { - return false; - } - - // - // Mask the other address with my prefix length. - // If the other prefix is within this prefix, the masked address must - // be same as the address of this prefix. - // - IpAddress maskedAddr = - IpAddress.makeMaskedAddress(other, this.prefixLength); - return this.address.equals(maskedAddr); - } - - @Override - public int hashCode() { - return Objects.hash(address, prefixLength); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if ((obj == null) || (!(obj instanceof IpPrefix))) { - return false; - } - IpPrefix other = (IpPrefix) obj; - return ((prefixLength == other.prefixLength) && - address.equals(other.address)); - } - - @Override - /* - * (non-Javadoc) - * The format is "x.x.x.x/y" for IPv4 prefixes. - * - * @see java.lang.Object#toString() - */ - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(address.toString()); - builder.append("/"); - builder.append(String.format("%d", prefixLength)); - return builder.toString(); - } - - /** - * Checks whether the prefix length is valid. - * - * @param version the IP address version - * @param prefixLength the prefix length value to check - * @throws IllegalArgumentException if the prefix length value is invalid - */ - private static void checkPrefixLength(IpAddress.Version version, - int prefixLength) { - int maxPrefixLen = 0; - - switch (version) { - case INET: - maxPrefixLen = MAX_INET_MASK_LENGTH; - break; - case INET6: - maxPrefixLen = MAX_INET6_MASK_LENGTH; - break; - default: - String msg = "Invalid IP version " + version; - throw new IllegalArgumentException(msg); - } - - if ((prefixLength < 0) || (prefixLength > maxPrefixLen)) { - String msg = "Invalid prefix length " + prefixLength + ". " + - "The value must be in the interval [0, " + - maxPrefixLen + "]"; - throw new IllegalArgumentException(msg); - } - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLC.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLC.java deleted file mode 100644 index 78b4f3fa..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLC.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; - -import static org.onlab.packet.PacketUtils.*; - -/** - * This class represents an Link Local Control header that is used in Ethernet - * 802.3. - * - * - */ -public class LLC extends BasePacket { - - public static final byte LLC_HEADER_LENGTH = 3; - - private byte dsap = 0; - private byte ssap = 0; - private byte ctrl = 0; - - public byte getDsap() { - return this.dsap; - } - - public void setDsap(final byte dsap) { - this.dsap = dsap; - } - - public byte getSsap() { - return this.ssap; - } - - public void setSsap(final byte ssap) { - this.ssap = ssap; - } - - public byte getCtrl() { - return this.ctrl; - } - - public void setCtrl(final byte ctrl) { - this.ctrl = ctrl; - } - - @Override - public byte[] serialize() { - final byte[] data = new byte[3]; - final ByteBuffer bb = ByteBuffer.wrap(data); - bb.put(this.dsap); - bb.put(this.ssap); - bb.put(this.ctrl); - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.dsap = bb.get(); - this.ssap = bb.get(); - this.ctrl = bb.get(); - return this; - } - - /** - * Deserializer function for LLC packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, LLC_HEADER_LENGTH); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - LLC llc = new LLC(); - - llc.dsap = bb.get(); - llc.ssap = bb.get(); - llc.ctrl = bb.get(); - - return llc; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDP.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDP.java deleted file mode 100644 index ae9d7173..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDP.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import java.util.LinkedList; -import java.util.List; - -import static org.onlab.packet.PacketUtils.*; - -/** - * - */ -public class LLDP extends BasePacket { - public static final byte CHASSIS_TLV_TYPE = 1; - public static final short CHASSIS_TLV_SIZE = 7; - public static final byte CHASSIS_TLV_SUBTYPE = 4; - - public static final byte PORT_TLV_TYPE = 2; - public static final short PORT_TLV_SIZE = 5; - public static final byte PORT_TLV_SUBTYPE = 2; - - public static final byte TTL_TLV_TYPE = 3; - public static final short TTL_TLV_SIZE = 2; - - protected LLDPTLV chassisId; - protected LLDPTLV portId; - protected LLDPTLV ttl; - protected List optionalTLVList; - protected short ethType; - - public LLDP() { - this.optionalTLVList = new LinkedList<>(); - this.ethType = Ethernet.TYPE_LLDP; - } - - /** - * @return the chassisId - */ - public LLDPTLV getChassisId() { - return this.chassisId; - } - - /** - * @param chassis - * the chassisId to set - * @return this - */ - public LLDP setChassisId(final LLDPTLV chassis) { - this.chassisId = chassis; - return this; - } - - /** - * @return the portId - */ - public LLDPTLV getPortId() { - return this.portId; - } - - /** - * @param portId - * the portId to set - * @return this - */ - public LLDP setPortId(final LLDPTLV portId) { - this.portId = portId; - return this; - } - - /** - * @return the ttl - */ - public LLDPTLV getTtl() { - return this.ttl; - } - - /** - * @param ttl - * the ttl to set - * @return this - */ - public LLDP setTtl(final LLDPTLV ttl) { - this.ttl = ttl; - return this; - } - - /** - * @return the optionalTLVList - */ - public List getOptionalTLVList() { - return this.optionalTLVList; - } - - /** - * @param optionalTLVList - * the optionalTLVList to set - * @return this - */ - public LLDP setOptionalTLVList(final List optionalTLVList) { - this.optionalTLVList = optionalTLVList; - return this; - } - - @Override - public byte[] serialize() { - int length = 2 + this.chassisId.getLength() + 2 - + this.portId.getLength() + 2 + this.ttl.getLength() + 2; - for (final LLDPTLV tlv : this.optionalTLVList) { - length += 2 + tlv.getLength(); - } - - final byte[] data = new byte[length]; - final ByteBuffer bb = ByteBuffer.wrap(data); - bb.put(this.chassisId.serialize()); - bb.put(this.portId.serialize()); - bb.put(this.ttl.serialize()); - for (final LLDPTLV tlv : this.optionalTLVList) { - bb.put(tlv.serialize()); - } - bb.putShort((short) 0); // End of LLDPDU - - /* - * if (this.parent != null && this.parent instanceof Ethernet) { - * ((Ethernet) this.parent).setEtherType(this.ethType); } - */ - - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - LLDPTLV tlv; - do { - try { - tlv = new LLDPOrganizationalTLV().deserialize(bb); - } catch (DeserializationException e) { - break; - } - - // if there was a failure to deserialize stop processing TLVs - if (tlv == null) { - break; - } - switch (tlv.getType()) { - case 0x0: - // can throw this one away, its just an end delimiter - break; - case 0x1: - this.chassisId = tlv; - break; - case 0x2: - this.portId = tlv; - break; - case 0x3: - this.ttl = tlv; - break; - - default: - this.optionalTLVList.add(tlv); - break; - } - } while (tlv.getType() != 0 && bb.hasRemaining()); - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 883; - int result = super.hashCode(); - result = prime * result - + (this.chassisId == null ? 0 : this.chassisId.hashCode()); - result = prime * result + this.optionalTLVList.hashCode(); - result = prime * result - + (this.portId == null ? 0 : this.portId.hashCode()); - result = prime * result + (this.ttl == null ? 0 : this.ttl.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof LLDP)) { - return false; - } - final LLDP other = (LLDP) obj; - if (this.chassisId == null) { - if (other.chassisId != null) { - return false; - } - } else if (!this.chassisId.equals(other.chassisId)) { - return false; - } - if (!this.optionalTLVList.equals(other.optionalTLVList)) { - return false; - } - if (this.portId == null) { - if (other.portId != null) { - return false; - } - } else if (!this.portId.equals(other.portId)) { - return false; - } - if (this.ttl == null) { - if (other.ttl != null) { - return false; - } - } else if (!this.ttl.equals(other.ttl)) { - return false; - } - return true; - } - - /** - * Deserializer function for LLDP packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, 0); - - LLDP lldp = new LLDP(); - - int currentIndex = 0; - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - LLDPTLV tlv; - do { - // Each new TLV must be a minimum of 2 bytes - // (containing the type and length fields). - currentIndex += 2; - checkHeaderLength(length, currentIndex); - - tlv = new LLDPOrganizationalTLV().deserialize(bb); - - // if there was a failure to deserialize stop processing TLVs - if (tlv == null) { - break; - } - switch (tlv.getType()) { - case 0x0: - // can throw this one away, it's just an end delimiter - break; - case 0x1: - lldp.chassisId = tlv; - break; - case 0x2: - lldp.portId = tlv; - break; - case 0x3: - lldp.ttl = tlv; - break; - default: - lldp.optionalTLVList.add(tlv); - break; - } - - currentIndex += tlv.getLength(); - } while (tlv.getType() != 0); - - return lldp; - }; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDPOrganizationalTLV.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDPOrganizationalTLV.java deleted file mode 100644 index bedf439f..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDPOrganizationalTLV.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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. - */ -/** - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.Arrays; - -/** - * The class representing LLDP Organizationally Specific TLV. - * - */ -public class LLDPOrganizationalTLV extends LLDPTLV { - public static final int OUI_LENGTH = 3; - public static final int SUBTYPE_LENGTH = 1; - public static final byte ORGANIZATIONAL_TLV_TYPE = 127; - public static final int MAX_INFOSTRING_LENGTH = 507; - - protected byte[] oui; - protected byte subType; - private byte[] infoString; - - public LLDPOrganizationalTLV() { - this.type = LLDPOrganizationalTLV.ORGANIZATIONAL_TLV_TYPE; - } - - /** - * Set the value of OUI. - * - * @param oui - * The value of OUI to be set. - * @return This LLDP Organizationally Specific TLV. - */ - public LLDPOrganizationalTLV setOUI(final byte[] oui) { - if (oui.length != LLDPOrganizationalTLV.OUI_LENGTH) { - throw new IllegalArgumentException("The length of OUI must be " - + LLDPOrganizationalTLV.OUI_LENGTH + ", but it is " - + oui.length); - } - this.oui = Arrays.copyOf(oui, oui.length); - return this; - } - - /** - * Returns the value of the OUI. - * - * @return The value of the OUI . - */ - public byte[] getOUI() { - return Arrays.copyOf(this.oui, this.oui.length); - } - - /** - * Set the value of sub type. - * - * @param subType - * The value of sub type to be set. - * @return This LLDP Organizationally Specific TLV. - */ - public LLDPOrganizationalTLV setSubType(final byte subType) { - this.subType = subType; - return this; - } - - /** - * Returns the value of the sub type. - * - * @return The value of the sub type. - */ - public byte getSubType() { - return this.subType; - } - - /** - * Set the value of information string. - * - * @param infoString - * the byte array of the value of information string. - * @return This LLDP Organizationally Specific TLV. - */ - public LLDPOrganizationalTLV setInfoString(final byte[] infoString) { - if (infoString.length > LLDPOrganizationalTLV.MAX_INFOSTRING_LENGTH) { - throw new IllegalArgumentException( - "The length of infoString cannot exceed " - + LLDPOrganizationalTLV.MAX_INFOSTRING_LENGTH); - } - this.infoString = Arrays.copyOf(infoString, infoString.length); - return this; - } - - /** - * Set the value of information string. The String value is automatically - * converted into byte array with UTF-8 encoding. - * - * @param infoString - * the String value of information string. - * @return This LLDP Organizationally Specific TLV. - */ - public LLDPOrganizationalTLV setInfoString(final String infoString) { - final byte[] infoStringBytes = infoString.getBytes(Charset - .forName("UTF-8")); - return this.setInfoString(infoStringBytes); - } - - /** - * Returns the value of information string. - * - * @return the value of information string. - */ - public byte[] getInfoString() { - return Arrays.copyOf(this.infoString, this.infoString.length); - } - - @Override - public byte[] serialize() { - if (this.type != LLDPOrganizationalTLV.ORGANIZATIONAL_TLV_TYPE) { - return super.serialize(); - } - final int valueLength = LLDPOrganizationalTLV.OUI_LENGTH - + LLDPOrganizationalTLV.SUBTYPE_LENGTH + this.infoString.length; - this.value = new byte[valueLength]; - final ByteBuffer bb = ByteBuffer.wrap(this.value); - bb.put(this.oui); - bb.put(this.subType); - bb.put(this.infoString); - return super.serialize(); - } - - @Override - public LLDPTLV deserialize(final ByteBuffer bb) throws DeserializationException { - super.deserialize(bb); - if (this.getType() != LLDPOrganizationalTLV.ORGANIZATIONAL_TLV_TYPE) { - return this; - } - - if (this.getLength() <= OUI_LENGTH + SUBTYPE_LENGTH) { - throw new DeserializationException( - "TLV length is less than required for organizational TLV"); - } - - final ByteBuffer optionalField = ByteBuffer.wrap(this.value); - - final byte[] oui = new byte[LLDPOrganizationalTLV.OUI_LENGTH]; - optionalField.get(oui); - this.setOUI(oui); - - this.setSubType(optionalField.get()); - - final byte[] infoString = new byte[this.getLength() - - LLDPOrganizationalTLV.OUI_LENGTH - - LLDPOrganizationalTLV.SUBTYPE_LENGTH]; - optionalField.get(infoString); - this.setInfoString(infoString); - return this; - } - - @Override - public int hashCode() { - final int prime = 1423; - int result = 1; - result = prime * result + this.type; - result = prime * result + this.length; - result = prime * result + Arrays.hashCode(this.oui); - result = prime * result + this.subType; - result = prime * result + Arrays.hashCode(this.infoString); - return result; - } - - @Override - public boolean equals(final Object o) { - if (o == this) { - return true; - } - - if (!(o instanceof LLDPOrganizationalTLV)) { - return false; - } - - final LLDPOrganizationalTLV other = (LLDPOrganizationalTLV) o; - if (this.type != other.type) { - return false; - } - if (this.length != other.length) { - return false; - } - if (!Arrays.equals(this.oui, other.oui)) { - return false; - } - if (this.subType != other.subType) { - return false; - } - if (!Arrays.equals(this.infoString, other.infoString)) { - return false; - } - - return true; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDPTLV.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDPTLV.java deleted file mode 100644 index 77efe1b7..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/LLDPTLV.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -/** - * - * - */ -public class LLDPTLV { - protected byte type; - protected short length; - protected byte[] value; - - /** - * @return the type - */ - public byte getType() { - return this.type; - } - - /** - * @param type - * the type to set - * @return this - */ - public LLDPTLV setType(final byte type) { - this.type = type; - return this; - } - - /** - * @return the length - */ - public short getLength() { - return this.length; - } - - /** - * @param length - * the length to set - * @return this - */ - public LLDPTLV setLength(final short length) { - this.length = length; - return this; - } - - /** - * @return the value - */ - public byte[] getValue() { - return this.value; - } - - /** - * @param value - * the value to set - * @return this - */ - public LLDPTLV setValue(final byte[] value) { - this.value = value; - return this; - } - - public byte[] serialize() { - // type = 7 bits - // info string length 9 bits, each value == byte - // info string - final short scratch = (short) ((0x7f & this.type) << 9 | 0x1ff & this.length); - final byte[] data = new byte[2 + this.length]; - final ByteBuffer bb = ByteBuffer.wrap(data); - bb.putShort(scratch); - if (this.value != null) { - bb.put(this.value); - } - return data; - } - - public LLDPTLV deserialize(final ByteBuffer bb) throws DeserializationException { - if (bb.remaining() < 2) { - throw new DeserializationException( - "Not enough bytes to deserialize TLV type and length"); - } - short typeLength; - typeLength = bb.getShort(); - this.type = (byte) (typeLength >> 9 & 0x7f); - this.length = (short) (typeLength & 0x1ff); - - if (this.length > 0) { - this.value = new byte[this.length]; - - // if there is an underrun just toss the TLV - if (bb.remaining() < this.length) { - throw new DeserializationException( - "Remaining bytes are less then the length of the TLV"); - } - bb.get(this.value); - } - - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 1423; - int result = 1; - result = prime * result + this.length; - result = prime * result + this.type; - result = prime * result + Arrays.hashCode(this.value); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof LLDPTLV)) { - return false; - } - final LLDPTLV other = (LLDPTLV) obj; - if (this.length != other.length) { - return false; - } - if (this.type != other.type) { - return false; - } - if (!Arrays.equals(this.value, other.value)) { - return false; - } - return true; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MPLS.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MPLS.java deleted file mode 100644 index 71c5803e..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MPLS.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import static org.onlab.packet.PacketUtils.checkInput; - -public class MPLS extends BasePacket { - public static final int HEADER_LENGTH = 4; - - public static final byte PROTOCOL_IPV4 = 0x1; - public static final byte PROTOCOL_MPLS = 0x6; - static Map> protocolDeserializerMap - = new HashMap<>(); - - static { - protocolDeserializerMap.put(PROTOCOL_IPV4, IPv4.deserializer()); - protocolDeserializerMap.put(PROTOCOL_MPLS, MPLS.deserializer()); - } - - protected int label; //20bits - protected byte bos; //1bit - protected byte ttl; //8bits - protected byte protocol; - - /** - * Default constructor that sets the version to 4. - */ - public MPLS() { - super(); - this.bos = 1; - this.protocol = PROTOCOL_IPV4; - } - - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (payload != null) { - payload.setParent(this); - payloadData = payload.serialize(); - } - - byte[] data = new byte[(4 + ((payloadData != null) ? payloadData.length : 0)) ]; - ByteBuffer bb = ByteBuffer.wrap(data); - - bb.putInt(((this.label & 0x000fffff) << 12) | ((this.bos & 0x1) << 8 | (this.ttl & 0xff))); - if (payloadData != null) { - bb.put(payloadData); - } - - return data; - } - - @Override - public IPacket deserialize(byte[] data, int offset, int length) { - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - - int mplsheader = bb.getInt(); - this.label = ((mplsheader & 0xfffff000) >> 12); - this.bos = (byte) ((mplsheader & 0x00000100) >> 8); - this.bos = (byte) (mplsheader & 0x000000ff); - this.protocol = (this.bos == 1) ? PROTOCOL_IPV4 : PROTOCOL_MPLS; - - Deserializer deserializer; - if (protocolDeserializerMap.containsKey(this.protocol)) { - deserializer = protocolDeserializerMap.get(this.protocol); - } else { - deserializer = Data.deserializer(); - } - try { - this.payload = deserializer.deserialize(data, bb.position(), bb.limit() - bb.position()); - this.payload.setParent(this); - } catch (DeserializationException e) { - return this; - } - - return this; - } - - /** - * Returns the MPLS label. - * - * @return MPLS label - */ - public int getLabel() { - return label; - } - - /** - * Sets the MPLS label. - * - * @param label MPLS label - */ - public void setLabel(int label) { - this.label = label; - } - - /** - * Returns the MPLS TTL of the packet. - * - * @return MPLS TTL of the packet - */ - public byte getTtl() { - return ttl; - } - - /** - * Sets the MPLS TTL of the packet. - * - * @param ttl MPLS TTL - */ - public void setTtl(byte ttl) { - this.ttl = ttl; - } - - /** - * Deserializer function for MPLS packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, HEADER_LENGTH); - - MPLS mpls = new MPLS(); - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - - int mplsheader = bb.getInt(); - mpls.label = ((mplsheader & 0xfffff000) >>> 12); - mpls.bos = (byte) ((mplsheader & 0x00000100) >> 8); - mpls.ttl = (byte) (mplsheader & 0x000000ff); - mpls.protocol = (mpls.bos == 1) ? PROTOCOL_IPV4 : PROTOCOL_MPLS; - - Deserializer deserializer; - if (protocolDeserializerMap.containsKey(mpls.protocol)) { - deserializer = protocolDeserializerMap.get(mpls.protocol); - } else { - deserializer = Data.deserializer(); - } - mpls.payload = deserializer.deserialize(data, bb.position(), bb.limit() - bb.position()); - mpls.payload.setParent(mpls); - - return mpls; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MacAddress.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MacAddress.java deleted file mode 100644 index cb7f2013..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MacAddress.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.util.Arrays; - -/** - * The class representing MAC address. - */ -public class MacAddress { - - public static final MacAddress NONE = valueOf("a4:23:05:00:00:00"); - public static final MacAddress ZERO = valueOf("00:00:00:00:00:00"); - public static final MacAddress BROADCAST = valueOf("ff:ff:ff:ff:ff:ff"); - - private static final byte[] LL = new byte[]{ - 0x01, (byte) 0x80, (byte) 0xc2, 0x00, 0x00, - 0x00, 0x0e, 0x03 - }; - - public static final int MAC_ADDRESS_LENGTH = 6; - private byte[] address = new byte[MacAddress.MAC_ADDRESS_LENGTH]; - - public MacAddress(final byte[] address) { - this.address = Arrays.copyOf(address, MacAddress.MAC_ADDRESS_LENGTH); - } - - /** - * Returns a MAC address instance representing the value of the specified - * {@code String}. - * - * @param address the String representation of the MAC Address to be parsed. - * @return a MAC Address instance representing the value of the specified - * {@code String}. - * @throws IllegalArgumentException if the string cannot be parsed as a MAC address. - */ - public static MacAddress valueOf(final String address) { - final String[] elements = address.split(":"); - if (elements.length != MacAddress.MAC_ADDRESS_LENGTH) { - throw new IllegalArgumentException( - "Specified MAC Address must contain 12 hex digits" - + " separated pairwise by :'s."); - } - - final byte[] addressInBytes = new byte[MacAddress.MAC_ADDRESS_LENGTH]; - for (int i = 0; i < MacAddress.MAC_ADDRESS_LENGTH; i++) { - final String element = elements[i]; - addressInBytes[i] = (byte) Integer.parseInt(element, 16); - } - - return new MacAddress(addressInBytes); - } - - /** - * Returns a MAC address instance representing the specified {@code byte} - * array. - * - * @param address the byte array to be parsed. - * @return a MAC address instance representing the specified {@code byte} - * array. - * @throws IllegalArgumentException if the byte array cannot be parsed as a MAC address. - */ - public static MacAddress valueOf(final byte[] address) { - if (address.length != MacAddress.MAC_ADDRESS_LENGTH) { - throw new IllegalArgumentException("the length is not " - + MacAddress.MAC_ADDRESS_LENGTH); - } - - return new MacAddress(address); - } - - /** - * Returns a MAC address instance representing the specified {@code long} - * value. The lower 48 bits of the long value are used to parse as a MAC - * address. - * - * @param address the long value to be parsed. The lower 48 bits are used for a - * MAC address. - * @return a MAC address instance representing the specified {@code long} - * value. - * @throws IllegalArgumentException if the long value cannot be parsed as a MAC address. - */ - public static MacAddress valueOf(final long address) { - final byte[] addressInBytes = new byte[]{ - (byte) (address >> 40 & 0xff), (byte) (address >> 32 & 0xff), - (byte) (address >> 24 & 0xff), (byte) (address >> 16 & 0xff), - (byte) (address >> 8 & 0xff), (byte) (address >> 0 & 0xff)}; - - return new MacAddress(addressInBytes); - } - - /** - * Returns the length of the {@code MACAddress}. - * - * @return the length of the {@code MACAddress}. - */ - public int length() { - return this.address.length; - } - - /** - * Returns the value of the {@code MACAddress} as a {@code byte} array. - * - * @return the numeric value represented by this object after conversion to - * type {@code byte} array. - */ - public byte[] toBytes() { - return Arrays.copyOf(this.address, this.address.length); - } - - /** - * Returns the value of the {@code MACAddress} as a {@code long}. - * - * @return the numeric value represented by this object after conversion to - * type {@code long}. - */ - public long toLong() { - long mac = 0; - for (int i = 0; i < 6; i++) { - final long t = (this.address[i] & 0xffL) << (5 - i) * 8; - mac |= t; - } - return mac; - } - - /** - * Returns {@code true} if the MAC address is the broadcast address. - * - * @return {@code true} if the MAC address is the broadcast address. - */ - public boolean isBroadcast() { - for (final byte b : this.address) { - if (b != -1) { - return false; - } - } - return true; - } - - /** - * Returns {@code true} if the MAC address is the multicast address. - * - * @return {@code true} if the MAC address is the multicast address. - */ - public boolean isMulticast() { - if (this.isBroadcast()) { - return false; - } - return (this.address[0] & 0x01) != 0; - } - - /** - * Returns true if this MAC address is link local. - * - * @return true if link local - */ - public boolean isLinkLocal() { - return LL[0] == address[0] && LL[1] == address[1] && LL[2] == address[2] && - LL[3] == address[3] && LL[4] == address[4] && - (LL[5] == address[5] || LL[6] == address[5] || LL[7] == address[5]); - } - - @Override - public boolean equals(final Object o) { - if (o == this) { - return true; - } - - if (!(o instanceof MacAddress)) { - return false; - } - - final MacAddress other = (MacAddress) o; - return Arrays.equals(this.address, other.address); - } - - @Override - public int hashCode() { - return Long.hashCode(toLong()); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - for (final byte b : this.address) { - if (builder.length() > 0) { - builder.append(":"); - } - builder.append(String.format("%02X", b & 0xFF)); - } - return builder.toString(); - } - - /** - * @return MAC address in string representation without colons (useful for - * radix tree storage) - */ - public String toStringNoColon() { - final StringBuilder builder = new StringBuilder(); - for (final byte b : this.address) { - builder.append(String.format("%02X", b & 0xFF)); - } - return builder.toString(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MplsLabel.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MplsLabel.java deleted file mode 100644 index 09a939fc..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/MplsLabel.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.onlab.packet; - -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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. - */ - -/** - * Representation of a MPLS label. - */ -public class MplsLabel { - - private final int mplsLabel; - - // An MPLS Label maximum 20 bits. - public static final int MAX_MPLS = 0xFFFFF; - - protected MplsLabel(int value) { - this.mplsLabel = value; - } - - public static MplsLabel mplsLabel(int value) { - - if (value < 0 || value > MAX_MPLS) { - String errorMsg = "MPLS label value " + value + - " is not in the interval [0, 0xFFFFF]"; - throw new IllegalArgumentException(errorMsg); - } - return new MplsLabel(value); - } - - public int toInt() { - return this.mplsLabel; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (obj instanceof MplsLabel) { - - MplsLabel other = (MplsLabel) obj; - - if (this.mplsLabel == other.mplsLabel) { - return true; - } - } - - return false; - } - - @Override - public int hashCode() { - return this.mplsLabel; - } - - @Override - public String toString() { - return String.valueOf(this.mplsLabel); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ONOSLLDP.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ONOSLLDP.java deleted file mode 100644 index 5b3902a8..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ONOSLLDP.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.packet; - -import com.google.common.collect.Lists; -import org.apache.commons.lang.ArrayUtils; - -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; - -/** - * ONOS LLDP containing organizational TLV for ONOS device dicovery. - */ -public class ONOSLLDP extends LLDP { - - public static final byte[] ONLAB_OUI = {(byte) 0xa4, 0x23, 0x05}; - public static final String DEFAULT_DEVICE = "INVALID"; - public static final String DEFAULT_NAME = "ONOS Discovery"; - - public static final byte[] LLDP_NICIRA = {0x01, 0x23, 0x20, 0x00, 0x00, - 0x01}; - public static final byte[] LLDP_MULTICAST = {0x01, (byte) 0x80, - (byte) 0xc2, 0x00, 0x00, 0x0e}; - public static final byte[] BDDP_MULTICAST = {(byte) 0xff, (byte) 0xff, - (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; - - private static final byte NAME_SUBTYPE = 1; - private static final byte DEVICE_SUBTYPE = 2; - private static final short NAME_LENGTH = 4; //1 for subtype + 3 for OUI - private static final short DEVICE_LENGTH = 4; //1 for subtype + 3 for OUI - private final LLDPOrganizationalTLV nameTLV = new LLDPOrganizationalTLV(); - private final LLDPOrganizationalTLV deviceTLV = new LLDPOrganizationalTLV(); - - // TLV constants: type, size and subtype - // Organizationally specific TLV also have packet offset and contents of TLV - // header - private static final byte CHASSIS_TLV_TYPE = 1; - private static final byte CHASSIS_TLV_SIZE = 7; - private static final byte CHASSIS_TLV_SUBTYPE = 4; - - private static final byte PORT_TLV_TYPE = 2; - private static final byte PORT_TLV_SIZE = 5; - private static final byte PORT_TLV_SUBTYPE = 2; - - private static final byte TTL_TLV_TYPE = 3; - - - private final byte[] ttlValue = new byte[] {0, 0x78}; - - public ONOSLLDP() { - super(); - setName(DEFAULT_NAME); - setDevice(DEFAULT_DEVICE); - setOptionalTLVList(Lists.newArrayList(nameTLV, deviceTLV)); - setTtl(new LLDPTLV().setType(TTL_TLV_TYPE) - .setLength((short) ttlValue.length) - .setValue(ttlValue)); - - } - - private ONOSLLDP(LLDP lldp) { - this.portId = lldp.getPortId(); - this.chassisId = lldp.getChassisId(); - this.ttl = lldp.getTtl(); - this.optionalTLVList = lldp.getOptionalTLVList(); - } - - public void setName(String name) { - nameTLV.setLength((short) (name.length() + NAME_LENGTH)); - nameTLV.setInfoString(name); - nameTLV.setSubType(NAME_SUBTYPE); - nameTLV.setOUI(ONLAB_OUI); - } - - public void setDevice(String device) { - deviceTLV.setInfoString(device); - deviceTLV.setLength((short) (device.length() + DEVICE_LENGTH)); - deviceTLV.setSubType(DEVICE_SUBTYPE); - deviceTLV.setOUI(ONLAB_OUI); - } - - public void setChassisId(final ChassisId chassisId) { - MacAddress chassisMac = MacAddress.valueOf(chassisId.value()); - byte[] chassis = ArrayUtils.addAll(new byte[] {CHASSIS_TLV_SUBTYPE}, - chassisMac.toBytes()); - - LLDPTLV chassisTLV = new LLDPTLV(); - chassisTLV.setLength(CHASSIS_TLV_SIZE); - chassisTLV.setType(CHASSIS_TLV_TYPE); - chassisTLV.setValue(chassis); - this.setChassisId(chassisTLV); - } - - public void setPortId(final int portNumber) { - byte[] port = ArrayUtils.addAll(new byte[] {PORT_TLV_SUBTYPE}, - ByteBuffer.allocate(4).putInt(portNumber).array()); - - LLDPTLV portTLV = new LLDPTLV(); - portTLV.setLength(PORT_TLV_SIZE); - portTLV.setType(PORT_TLV_TYPE); - portTLV.setValue(port); - this.setPortId(portTLV); - } - - public LLDPOrganizationalTLV getNameTLV() { - for (LLDPTLV tlv : this.getOptionalTLVList()) { - if (tlv.getType() == LLDPOrganizationalTLV.ORGANIZATIONAL_TLV_TYPE) { - LLDPOrganizationalTLV orgTLV = (LLDPOrganizationalTLV) tlv; - if (orgTLV.getSubType() == NAME_SUBTYPE) { - return orgTLV; - } - } - } - return null; - } - - public LLDPOrganizationalTLV getDeviceTLV() { - for (LLDPTLV tlv : this.getOptionalTLVList()) { - if (tlv.getType() == LLDPOrganizationalTLV.ORGANIZATIONAL_TLV_TYPE) { - LLDPOrganizationalTLV orgTLV = (LLDPOrganizationalTLV) tlv; - if (orgTLV.getSubType() == DEVICE_SUBTYPE) { - return orgTLV; - } - } - } - return null; - } - - public String getNameString() { - LLDPOrganizationalTLV tlv = getNameTLV(); - if (tlv != null) { - return new String(tlv.getInfoString(), StandardCharsets.UTF_8); - } - return null; - } - - public String getDeviceString() { - LLDPOrganizationalTLV tlv = getDeviceTLV(); - if (tlv != null) { - return new String(tlv.getInfoString(), StandardCharsets.UTF_8); - } - return null; - } - - public Integer getPort() { - ByteBuffer portBB = ByteBuffer.wrap(this.getPortId().getValue()); - portBB.position(1); - return portBB.getInt(); - } - - /** - * Given an ethernet packet, determines if this is an LLDP from - * ONOS and returns the device the LLDP came from. - * @param eth an ethernet packet - * @return a the lldp packet or null - */ - public static ONOSLLDP parseONOSLLDP(Ethernet eth) { - if (eth.getEtherType() == Ethernet.TYPE_LLDP || - eth.getEtherType() == Ethernet.TYPE_BSN) { - ONOSLLDP onosLldp = new ONOSLLDP((LLDP) eth.getPayload()); //(ONOSLLDP) eth.getPayload(); - if (ONOSLLDP.DEFAULT_NAME.equals(onosLldp.getNameString())) { - return onosLldp; - } - } - return null; - } - - - - - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/PIM.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/PIM.java deleted file mode 100755 index e6ef0aed..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/PIM.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import org.onlab.packet.pim.PIMHello; -import org.onlab.packet.pim.PIMJoinPrune; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * Implements PIM control packet format. - */ -public class PIM extends BasePacket { - - public static final IpAddress PIM_ADDRESS = IpAddress.valueOf("224.0.0.13"); - - public static final byte TYPE_HELLO = 0x00; - public static final byte TYPE_REGISTER = 0x01; - public static final byte TYPE_REGISTER_STOP = 0x02; - public static final byte TYPE_JOIN_PRUNE_REQUEST = 0x03; - public static final byte TYPE_BOOTSTRAP = 0x04; - public static final byte TYPE_ASSERT = 0x05; - public static final byte TYPE_GRAFT = 0x06; - public static final byte TYPE_GRAFT_ACK = 0x07; - public static final byte TYPE_CANDIDATE_RP_ADV = 0x08; - - public static final int PIM_HEADER_LEN = 4; - - public static final byte ADDRESS_FAMILY_IP4 = 0x1; - public static final byte ADDRESS_FAMILY_IP6 = 0x2; - - public static final Map> PROTOCOL_DESERIALIZER_MAP = - new HashMap<>(); - - static { - PIM.PROTOCOL_DESERIALIZER_MAP.put(PIM.TYPE_HELLO, PIMHello.deserializer()); - PIM.PROTOCOL_DESERIALIZER_MAP.put(PIM.TYPE_JOIN_PRUNE_REQUEST, PIMJoinPrune.deserializer()); - } - - /* - * PIM Header fields - */ - protected byte version; - protected byte type; - protected byte reserved; - protected short checksum; - - /** - * Default constructor. - */ - public PIM() { - super(); - this.version = 2; - this.reserved = 0; - } - - /** - * Return the PIM message type. - * - * @return the pimMsgType - */ - public byte getPimMsgType() { - return this.type; - } - - /** - * Set the PIM message type. Currently PIMJoinPrune and PIMHello are - * supported. - * - * @param type PIM message type - * @return PIM Header - */ - public PIM setPIMType(final byte type) { - this.type = type; - return this; - } - - /** - * Get the version of PIM. - * - * @return the PIM version. Must be 2. - */ - public byte getVersion() { - return version; - } - - /** - * Set the PIM version type. Should not change from 2. - * - * @param version PIM version - */ - public void setVersion(byte version) { - this.version = version; - } - - /** - * Get the reserved field. - * - * @return the reserved field. Must be ignored. - */ - public byte getReserved() { - return reserved; - } - - /** - * Set the reserved field. - * - * @param reserved should be 0 - */ - public void setReserved(byte reserved) { - this.reserved = reserved; - } - - /** - * Get the checksum of this packet. - * - * @return the checksum - */ - public short getChecksum() { - return checksum; - } - - /** - * Set the checksum. - * - * @param checksum the checksum - */ - public void setChecksum(short checksum) { - this.checksum = checksum; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - result = prime * result + this.type; - result = prime * result + this.version; - result = prime * result + this.checksum; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof PIM)) { - return false; - } - final PIM other = (PIM) obj; - if (this.type != other.type) { - return false; - } - if (this.version != other.version) { - return false; - } - if (this.checksum != other.checksum) { - return false; - } - return true; - } - - /** - * Serializes the packet. Will compute and set the following fields if they - * are set to specific values at the time serialize is called: -checksum : 0 - * -length : 0 - * - * @return will return the serialized packet - */ - @Override - public byte[] serialize() { - int length = 4; - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - length += payloadData.length; - } - - final byte[] data = new byte[length]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.put((byte) ((this.version & 0xf) << 4 | this.type & 0xf)); - bb.put(this.reserved); - bb.putShort(this.checksum); - if (payloadData != null) { - bb.put(payloadData); - } - - if (this.parent != null && this.parent instanceof PIM) { - ((PIM) this.parent).setPIMType(TYPE_JOIN_PRUNE_REQUEST); - } - - // compute checksum if needed - if (this.checksum == 0) { - bb.rewind(); - int accumulation = 0; - - for (int i = 0; i < length / 2; ++i) { - accumulation += 0xffff & bb.getShort(); - } - // pad to an even number of shorts - if (length % 2 > 0) { - accumulation += (bb.get() & 0xff) << 8; - } - - accumulation = (accumulation >> 16 & 0xffff) - + (accumulation & 0xffff); - this.checksum = (short) (~accumulation & 0xffff); - bb.putShort(2, this.checksum); - } - return data; - } - - /** - * Deserialize the PIM packet. - * - * @param data bytes to deserialize. - * @param offset offset to start deserializing from - * @param length length of the data to deserialize - * - * @return the deserialized PIM packet. - */ - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.type = bb.get(); - this.version = bb.get(); - this.checksum = bb.getShort(); - - //this.payload = new Data(); - this.payload = this.payload.deserialize(data, bb.position(), bb.limit() - bb.position()); - this.payload.setParent(this); - return this; - } - /** - * Deserializer function for IPv4 packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, PIM_HEADER_LEN); - - PIM pim = new PIM(); - - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - - byte versionByte = bb.get(); - pim.version = (byte) (versionByte >> 4 & 0xf); - pim.setPIMType((byte) (versionByte & 0xf)); - pim.reserved = bb.get(); - pim.checksum = bb.getShort(); - - Deserializer deserializer; - if (PIM.PROTOCOL_DESERIALIZER_MAP.containsKey(pim.getPimMsgType())) { - deserializer = PIM.PROTOCOL_DESERIALIZER_MAP.get(pim.getPimMsgType()); - } else { - deserializer = Data.deserializer(); - } - - pim.payload = deserializer.deserialize(data, bb.position(), bb.limit() - bb.position()); - pim.payload.setParent(pim); - - return pim; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/PacketUtils.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/PacketUtils.java deleted file mode 100644 index c3bede2f..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/PacketUtils.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Utilities for working with packet headers. - */ -public final class PacketUtils { - - private PacketUtils() { - } - - /** - * Check the length of the input buffer is appropriate given the offset and - * length parameters. - * - * @param byteLength length of the input buffer array - * @param offset offset given to begin reading bytes from - * @param length length given to read up until - * @throws DeserializationException if the input parameters don't match up (i.e - * we can't read that many bytes from the buffer at the given offest) - */ - public static void checkBufferLength(int byteLength, int offset, int length) - throws DeserializationException { - boolean ok = (offset >= 0 && offset < byteLength); - ok = ok & (length >= 0 && offset + length <= byteLength); - - if (!ok) { - throw new DeserializationException("Unable to read " + length + " bytes from a " - + byteLength + " byte array starting at offset " + offset); - } - } - - /** - * Check that there are enough bytes in the buffer to read some number of - * bytes that we need to read a full header. - * - * @param givenLength given size of the buffer - * @param requiredLength number of bytes we need to read some header fully - * @throws DeserializationException if there aren't enough bytes - */ - public static void checkHeaderLength(int givenLength, int requiredLength) - throws DeserializationException { - if (requiredLength > givenLength) { - throw new DeserializationException(requiredLength - + " bytes are needed to continue deserialization, however only " - + givenLength + " remain in buffer"); - } - } - - /** - * Check the input parameters are sane and there's enough bytes to read - * the required length. - * - * @param data input byte buffer - * @param offset offset of the start of the header - * @param length length given to deserialize the header - * @param requiredLength length needed to deserialize header - * @throws DeserializationException if we're unable to deserialize the - * packet based on the input parameters - */ - public static void checkInput(byte[] data, int offset, int length, int requiredLength) - throws DeserializationException { - checkNotNull(data); - checkBufferLength(data.length, offset, length); - checkHeaderLength(length, requiredLength); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/RADIUS.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/RADIUS.java deleted file mode 100644 index 297fee7c..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/RADIUS.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * - * * Copyright 2015 AT&T Foundry - * * - * * 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.onlab.packet; - -import org.slf4j.Logger; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.onlab.packet.PacketUtils.checkHeaderLength; -import static org.onlab.packet.PacketUtils.checkInput; -import static org.slf4j.LoggerFactory.getLogger; - -/** - * RADIUS packet. - */ -public class RADIUS extends BasePacket { - protected byte code; - protected byte identifier; - protected short length = RADIUS_MIN_LENGTH; - protected byte[] authenticator = new byte[16]; - protected List attributes = new ArrayList<>(); - - // RADIUS parameters - public static final short RADIUS_MIN_LENGTH = 20; - public static final short MAX_ATTR_VALUE_LENGTH = 253; - public static final short RADIUS_MAX_LENGTH = 4096; - - // RADIUS packet types - public static final byte RADIUS_CODE_ACCESS_REQUEST = 0x01; - public static final byte RADIUS_CODE_ACCESS_ACCEPT = 0x02; - public static final byte RADIUS_CODE_ACCESS_REJECT = 0x03; - public static final byte RADIUS_CODE_ACCOUNTING_REQUEST = 0x04; - public static final byte RADIUS_CODE_ACCOUNTING_RESPONSE = 0x05; - public static final byte RADIUS_CODE_ACCESS_CHALLENGE = 0x0b; - - private final Logger log = getLogger(getClass()); - - /** - * Default constructor. - */ - public RADIUS() { - } - - /** - * Constructs a RADIUS packet with the given code and identifier. - * - * @param code code - * @param identifier identifier - */ - public RADIUS(byte code, byte identifier) { - this.code = code; - this.identifier = identifier; - } - - /** - * Gets the code. - * - * @return code - */ - public byte getCode() { - return this.code; - } - - /** - * Sets the code. - * - * @param code code - */ - public void setCode(byte code) { - this.code = code; - } - - /** - * Gets the identifier. - * - * @return identifier - */ - public byte getIdentifier() { - return this.identifier; - } - - /** - * Sets the identifier. - * - * @param identifier identifier - */ - public void setIdentifier(byte identifier) { - this.identifier = identifier; - } - - /** - * Gets the authenticator. - * - * @return authenticator - */ - public byte[] getAuthenticator() { - return this.authenticator; - } - - /** - * Sets the authenticator. - * - * @param authenticator authenticator - */ - public void setAuthenticator(byte[] authenticator) { - this.authenticator = authenticator; - } - - /** - * Generates an authenticator code. - * - * @return the authenticator - */ - public byte[] generateAuthCode() { - new SecureRandom().nextBytes(this.authenticator); - return this.authenticator; - } - - /** - * Checks if the packet's code field is valid. - * - * @return whether the code is valid - */ - public boolean isValidCode() { - return this.code == RADIUS_CODE_ACCESS_REQUEST || - this.code == RADIUS_CODE_ACCESS_ACCEPT || - this.code == RADIUS_CODE_ACCESS_REJECT || - this.code == RADIUS_CODE_ACCOUNTING_REQUEST || - this.code == RADIUS_CODE_ACCOUNTING_RESPONSE || - this.code == RADIUS_CODE_ACCESS_CHALLENGE; - } - - /** - * Adds a message authenticator to the packet based on the given key. - * - * @param key key to generate message authenticator - * @return the messgae authenticator RADIUS attribute - */ - public RADIUSAttribute addMessageAuthenticator(String key) { - // Message-Authenticator = HMAC-MD5 (Type, Identifier, Length, - // Request Authenticator, Attributes) - // When the message integrity check is calculated the signature string - // should be considered to be sixteen octets of zero. - byte[] hashOutput = new byte[16]; - Arrays.fill(hashOutput, (byte) 0); - - RADIUSAttribute authAttribute = this.getAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH); - if (authAttribute != null) { - // If Message-Authenticator was already present, override it - this.log.warn("Attempted to add duplicate Message-Authenticator"); - authAttribute = this.updateAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH, hashOutput); - } else { - // Else generate a new attribute padded with zeroes - authAttribute = this.setAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH, hashOutput); - } - // Calculate the MD5 HMAC based on the message - try { - SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacMD5"); - Mac mac = Mac.getInstance("HmacMD5"); - mac.init(keySpec); - hashOutput = mac.doFinal(this.serialize()); - // Update HMAC in Message-Authenticator - authAttribute = this.updateAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH, hashOutput); - } catch (Exception e) { - this.log.error("Failed to generate message authenticator: {}", e.getMessage()); - } - - return authAttribute; - } - - /** - * Checks the message authenticator in the packet with one generated from - * the given key. - * - * @param key key to generate message authenticator - * @return whether the message authenticators match or not - */ - public boolean checkMessageAuthenticator(String key) { - byte[] newHash = new byte[16]; - Arrays.fill(newHash, (byte) 0); - byte[] messageAuthenticator = this.getAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH).getValue(); - this.updateAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH, newHash); - // Calculate the MD5 HMAC based on the message - try { - SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacMD5"); - Mac mac = Mac.getInstance("HmacMD5"); - mac.init(keySpec); - newHash = mac.doFinal(this.serialize()); - } catch (Exception e) { - log.error("Failed to generate message authenticator: {}", e.getMessage()); - } - this.updateAttribute(RADIUSAttribute.RADIUS_ATTR_MESSAGE_AUTH, messageAuthenticator); - // Compare the calculated Message-Authenticator with the one in the message - return Arrays.equals(newHash, messageAuthenticator); - } - - /** - * Encapsulates an EAP packet in this RADIUS packet. - * - * @param message EAP message object to be embedded in the RADIUS - * EAP-Message attributed - */ - public void encapsulateMessage(EAP message) { - if (message.length <= MAX_ATTR_VALUE_LENGTH) { - // Use the regular serialization method as it fits into one EAP-Message attribute - this.setAttribute(RADIUSAttribute.RADIUS_ATTR_EAP_MESSAGE, - message.serialize()); - } else { - // Segment the message into chucks and embed them in several EAP-Message attributes - short remainingLength = message.length; - byte[] messageBuffer = message.serialize(); - final ByteBuffer bb = ByteBuffer.wrap(messageBuffer); - while (bb.hasRemaining()) { - byte[] messageAttributeData; - if (remainingLength > MAX_ATTR_VALUE_LENGTH) { - // The remaining data is still too long to fit into one attribute, keep going - messageAttributeData = new byte[MAX_ATTR_VALUE_LENGTH]; - bb.get(messageAttributeData, 0, MAX_ATTR_VALUE_LENGTH); - remainingLength -= MAX_ATTR_VALUE_LENGTH; - } else { - // The remaining data fits, this will be the last chunk - messageAttributeData = new byte[remainingLength]; - bb.get(messageAttributeData, 0, remainingLength); - } - this.attributes.add(new RADIUSAttribute(RADIUSAttribute.RADIUS_ATTR_EAP_MESSAGE, - (byte) (messageAttributeData.length + 2), messageAttributeData)); - - // Adding the size of the data to the total RADIUS length - this.length += (short) (messageAttributeData.length & 0xFF); - // Adding the size of the overhead attribute type and length - this.length += 2; - } - } - } - - /** - * Decapsulates an EAP packet from the RADIUS packet. - * - * @return An EAP object containing the reassembled EAP message - */ - public EAP decapsulateMessage() { - EAP message = new EAP(); - ByteArrayOutputStream messageStream = new ByteArrayOutputStream(); - // Iterating through EAP-Message attributes to concatenate their value - for (RADIUSAttribute ra : this.getAttributeList(RADIUSAttribute.RADIUS_ATTR_EAP_MESSAGE)) { - try { - messageStream.write(ra.getValue()); - } catch (IOException e) { - log.error("Error while reassembling EAP message: {}", e.getMessage()); - } - } - // Assembling EAP object from the concatenated stream - message.deserialize(messageStream.toByteArray(), 0, messageStream.size()); - return message; - } - - /** - * Gets a list of attributes from the RADIUS packet. - * - * @param attrType the type field of the required attributes - * @return List of the attributes that matches the type or an empty list if there is none - */ - public ArrayList getAttributeList(byte attrType) { - ArrayList attrList = new ArrayList<>(); - for (int i = 0; i < this.attributes.size(); i++) { - if (this.attributes.get(i).getType() == attrType) { - attrList.add(this.attributes.get(i)); - } - } - return attrList; - } - - /** - * Gets an attribute from the RADIUS packet. - * - * @param attrType the type field of the required attribute - * @return the first attribute that matches the type or null if does not exist - */ - public RADIUSAttribute getAttribute(byte attrType) { - for (int i = 0; i < this.attributes.size(); i++) { - if (this.attributes.get(i).getType() == attrType) { - return this.attributes.get(i); - } - } - return null; - } - - /** - * Sets an attribute in the RADIUS packet. - * - * @param attrType the type field of the attribute to set - * @param value value to be set - * @return reference to the attribute object - */ - public RADIUSAttribute setAttribute(byte attrType, byte[] value) { - byte attrLength = (byte) (value.length + 2); - RADIUSAttribute newAttribute = new RADIUSAttribute(attrType, attrLength, value); - this.attributes.add(newAttribute); - this.length += (short) (attrLength & 0xFF); - return newAttribute; - } - - /** - * Updates an attribute in the RADIUS packet. - * - * @param attrType the type field of the attribute to update - * @param value the value to update to - * @return reference to the attribute object - */ - public RADIUSAttribute updateAttribute(byte attrType, byte[] value) { - for (int i = 0; i < this.attributes.size(); i++) { - if (this.attributes.get(i).getType() == attrType) { - this.length -= (short) (this.attributes.get(i).getLength() & 0xFF); - RADIUSAttribute newAttr = new RADIUSAttribute(attrType, (byte) (value.length + 2), value); - this.attributes.set(i, newAttr); - this.length += (short) (newAttr.getLength() & 0xFF); - return newAttr; - } - } - return null; - } - - /** - * Deserializer for RADIUS packets. - * - * @return deserializer - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, RADIUS_MIN_LENGTH); - - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - RADIUS radius = new RADIUS(); - radius.code = bb.get(); - radius.identifier = bb.get(); - radius.length = bb.getShort(); - bb.get(radius.authenticator, 0, 16); - - checkHeaderLength(length, radius.length); - - int remainingLength = radius.length - RADIUS_MIN_LENGTH; - while (remainingLength > 0 && bb.hasRemaining()) { - - RADIUSAttribute attr = new RADIUSAttribute(); - attr.setType(bb.get()); - attr.setLength(bb.get()); - short attrLength = (short) (attr.length & 0xff); - attr.value = new byte[attrLength - 2]; - bb.get(attr.value, 0, attrLength - 2); - radius.attributes.add(attr); - remainingLength -= attr.length; - } - return radius; - }; - } - - @Override - public byte[] serialize() { - final byte[] data = new byte[this.length]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.put(this.code); - bb.put(this.identifier); - bb.putShort(this.length); - bb.put(this.authenticator); - for (int i = 0; i < this.attributes.size(); i++) { - RADIUSAttribute attr = this.attributes.get(i); - bb.put(attr.getType()); - bb.put(attr.getLength()); - bb.put(attr.getValue()); - } - - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.code = bb.get(); - this.identifier = bb.get(); - this.length = bb.getShort(); - bb.get(this.authenticator, 0, 16); - - int remainingLength = this.length - RADIUS_MIN_LENGTH; - while (remainingLength > 0 && bb.hasRemaining()) { - RADIUSAttribute attr = new RADIUSAttribute(); - attr.setType(bb.get()); - attr.setLength(bb.get()); - short attrLength = (short) (attr.length & 0xff); - attr.value = new byte[attrLength - 2]; - bb.get(attr.value, 0, attrLength - 2); - this.attributes.add(attr); - remainingLength -= attr.length; - } - return this; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/RADIUSAttribute.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/RADIUSAttribute.java deleted file mode 100644 index 9687e377..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/RADIUSAttribute.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * - * * Copyright 2015 AT&T Foundry - * * - * * 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.onlab.packet; - -/** - * An attribute in a RADIUS packet. - */ -public class RADIUSAttribute { - protected byte type; - protected byte length; - protected byte[] value; - - // RADIUS attribute types - public static final byte RADIUS_ATTR_USERNAME = 1; - public static final byte RADIUS_ATTR_NAS_IP = 4; - public static final byte RADIUS_ATTR_NAS_PORT = 5; - public static final byte RADIUS_ATTR_FRAMED_MTU = 12; - public static final byte RADIUS_ATTR_STATE = 24; - public static final byte RADIUS_ATTR_VENDOR_SPECIFIC = 26; - public static final byte RADIUS_ATTR_CALLING_STATION_ID = 31; - public static final byte RADIUS_ATTR_NAS_ID = 32; - public static final byte RADIUS_ATTR_ACCT_SESSION_ID = 44; - public static final byte RADIUS_ATTR_NAS_PORT_TYPE = 61; - public static final byte RADIUS_ATTR_EAP_MESSAGE = 79; - public static final byte RADIUS_ATTR_MESSAGE_AUTH = 80; - public static final byte RADIUS_ATTR_NAS_PORT_ID = 87; - - /** - * Default constructor. - */ - public RADIUSAttribute() { - } - - /** - * Constructs a RADIUS attribute with the give type, length and value. - * - * @param type type - * @param length length - * @param value value - */ - public RADIUSAttribute(final byte type, final byte length, final byte[] value) { - this.type = type; - this.length = length; - this.value = value; - } - - /** - * Checks if the attribute type is valid. - * - * @return whether the type is valid or not - */ - public boolean isValidType() { - return this.type == RADIUS_ATTR_USERNAME || - this.type == RADIUS_ATTR_NAS_IP || - this.type == RADIUS_ATTR_NAS_PORT || - this.type == RADIUS_ATTR_VENDOR_SPECIFIC || - this.type == RADIUS_ATTR_CALLING_STATION_ID || - this.type == RADIUS_ATTR_NAS_ID || - this.type == RADIUS_ATTR_ACCT_SESSION_ID || - this.type == RADIUS_ATTR_NAS_PORT_TYPE || - this.type == RADIUS_ATTR_EAP_MESSAGE || - this.type == RADIUS_ATTR_MESSAGE_AUTH || - this.type == RADIUS_ATTR_NAS_PORT_ID; - } - - /** - * Gets the attribute type. - * - * @return the type - */ - public byte getType() { - return this.type; - } - - /** - * Sets the attribute type. - * - * @param type the code to set - * @return this - */ - public RADIUSAttribute setType(final byte type) { - this.type = type; - return this; - } - - /** - * Gets the attribute length. - * - * @return the length - */ - public byte getLength() { - return this.length; - } - - /** - * Sets the attribute length. - * - * @param length the length to set - * @return this - */ - public RADIUSAttribute setLength(final byte length) { - this.length = length; - return this; - } - - /** - * Gets the attribute value. - * - * @return the value - */ - public byte[] getValue() { - return this.value; - } - - /** - * Sets the attribute value. - * - * @param value the data to set - * @return this - */ - public RADIUSAttribute setValue(final byte[] value) { - this.value = value; - return this; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/TCP.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/TCP.java deleted file mode 100644 index e089f272..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/TCP.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -import static org.onlab.packet.PacketUtils.*; - -/** - * Implements TCP packet format. - */ - -public class TCP extends BasePacket { - - private static final short TCP_HEADER_LENGTH = 20; - - protected int sourcePort; - protected int destinationPort; - protected int sequence; - protected int acknowledge; - protected byte dataOffset; - protected short flags; - protected short windowSize; - protected short checksum; - protected short urgentPointer; - protected byte[] options; - - /** - * Gets TCP source port. - * - * @return TCP source port - */ - public int getSourcePort() { - return this.sourcePort; - } - - /** - * Sets TCP source port. - * - * @param sourcePort the sourcePort to set (unsigned 16 bits integer) - * @return this - */ - public TCP setSourcePort(final int sourcePort) { - this.sourcePort = sourcePort; - return this; - } - - /** - * Gets TCP destination port. - * - * @return the destinationPort - */ - public int getDestinationPort() { - return this.destinationPort; - } - - /** - * Sets TCP destination port. - * - * @param destinationPort the destinationPort to set (unsigned 16 bits integer) - * @return this - */ - public TCP setDestinationPort(final int destinationPort) { - this.destinationPort = destinationPort; - return this; - } - - /** - * Gets checksum. - * - * @return the checksum - */ - public short getChecksum() { - return this.checksum; - } - - /** - * Sets checksum. - * - * @param checksum the checksum to set - * @return this - */ - public TCP setChecksum(final short checksum) { - this.checksum = checksum; - return this; - } - - /** - * Gets sequence number. - * - * @return the sequence number - */ - public int getSequence() { - return this.sequence; - } - - /** - * Sets sequence number. - * - * @param seq the sequence number to set - * @return this - */ - public TCP setSequence(final int seq) { - this.sequence = seq; - return this; - } - - /** - * Gets acknowledge number. - * - * @return the acknowledge number - */ - public int getAcknowledge() { - return this.acknowledge; - } - - /** - * Sets acknowledge number. - * - * @param ack the acknowledge number to set - * @return this - */ - public TCP setAcknowledge(final int ack) { - this.acknowledge = ack; - return this; - } - - /** - * Gets offset. - * - * @return the offset - */ - public byte getDataOffset() { - return this.dataOffset; - } - - /** - * Sets offset. - * - * @param offset the offset to set - * @return this - */ - public TCP setDataOffset(final byte offset) { - this.dataOffset = offset; - return this; - } - - /** - * Gets TCP flags. - * - * @return the TCP flags - */ - public short getFlags() { - return this.flags; - } - - /** - * Sets TCP flags. - * - * @param flags the TCP flags to set - * @return this - */ - public TCP setFlags(final short flags) { - this.flags = flags; - return this; - } - - /** - * Gets TCP window size. - * - * @return the TCP window size - */ - public short getWindowSize() { - return this.windowSize; - } - - /** - * Sets TCP window size. - * - * @param windowSize the TCP window size to set - * @return this - */ - public TCP setWindowSize(final short windowSize) { - this.windowSize = windowSize; - return this; - } - - @Override - public void resetChecksum() { - this.checksum = 0; - super.resetChecksum(); - } - - /** - * Gets urgent pointer. - * - * @return the urgent pointer - */ - public short getUrgentPointer() { - return this.urgentPointer; - } - - /** - * Sets urgent pointer. - * - * @param urgentPointer the urgent pointer to set - * @return this - */ - public TCP setUrgentPointer(final short urgentPointer) { - this.urgentPointer = urgentPointer; - return this; - } - - /** - * Gets TCP options. - * - * @return the TCP options - */ - public byte[] getOptions() { - return this.options; - } - - /** - * Sets TCP options. - * - * @param options the options to set - * @return this - */ - public TCP setOptions(final byte[] options) { - this.options = options; - this.dataOffset = (byte) (20 + options.length + 3 >> 2); - return this; - } - - /** - * Serializes the packet. Will compute and set the following fields if they - * are set to specific values at the time serialize is called: -checksum : 0 - * -length : 0 - */ - @Override - public byte[] serialize() { - int length; - if (this.dataOffset == 0) { - this.dataOffset = 5; // default header length - } - length = this.dataOffset << 2; - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - length += payloadData.length; - } - - final byte[] data = new byte[length]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.putShort((short) (this.sourcePort & 0xffff)); - bb.putShort((short) (this.destinationPort & 0xffff)); - bb.putInt(this.sequence); - bb.putInt(this.acknowledge); - bb.putShort((short) (this.flags | this.dataOffset << 12)); - bb.putShort(this.windowSize); - bb.putShort(this.checksum); - bb.putShort(this.urgentPointer); - if (this.dataOffset > 5) { - int padding; - bb.put(this.options); - padding = (this.dataOffset << 2) - 20 - this.options.length; - for (int i = 0; i < padding; i++) { - bb.put((byte) 0); - } - } - if (payloadData != null) { - bb.put(payloadData); - } - - if (this.parent != null && this.parent instanceof IPv4) { - ((IPv4) this.parent).setProtocol(IPv4.PROTOCOL_TCP); - } - - // compute checksum if needed - if (this.checksum == 0) { - bb.rewind(); - int accumulation = 0; - - // compute pseudo header mac - if (this.parent != null) { - if (this.parent instanceof IPv4) { - final IPv4 ipv4 = (IPv4) this.parent; - accumulation += (ipv4.getSourceAddress() >> 16 & 0xffff) - + (ipv4.getSourceAddress() & 0xffff); - accumulation += (ipv4.getDestinationAddress() >> 16 & 0xffff) - + (ipv4.getDestinationAddress() & 0xffff); - accumulation += ipv4.getProtocol() & 0xff; - accumulation += length & 0xffff; - } else if (this.parent instanceof IPv6) { - final IPv6 ipv6 = (IPv6) this.parent; - final int bbLength = - Ip6Address.BYTE_LENGTH * 2 // IPv6 src, dst - + 2 // nextHeader (with padding) - + 4; // length - final ByteBuffer bbChecksum = ByteBuffer.allocate(bbLength); - bbChecksum.put(ipv6.getSourceAddress()); - bbChecksum.put(ipv6.getDestinationAddress()); - bbChecksum.put((byte) 0); // padding - bbChecksum.put(ipv6.getNextHeader()); - bbChecksum.putInt(length); - bbChecksum.rewind(); - for (int i = 0; i < bbLength / 2; ++i) { - accumulation += 0xffff & bbChecksum.getShort(); - } - } - } - - for (int i = 0; i < length / 2; ++i) { - accumulation += 0xffff & bb.getShort(); - } - // pad to an even number of shorts - if (length % 2 > 0) { - accumulation += (bb.get() & 0xff) << 8; - } - - accumulation = (accumulation >> 16 & 0xffff) - + (accumulation & 0xffff); - this.checksum = (short) (~accumulation & 0xffff); - bb.putShort(16, this.checksum); - } - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.sourcePort = (bb.getShort() & 0xffff); - this.destinationPort = (bb.getShort() & 0xffff); - this.sequence = bb.getInt(); - this.acknowledge = bb.getInt(); - this.flags = bb.getShort(); - this.dataOffset = (byte) (this.flags >> 12 & 0xf); - this.flags = (short) (this.flags & 0x1ff); - this.windowSize = bb.getShort(); - this.checksum = bb.getShort(); - this.urgentPointer = bb.getShort(); - if (this.dataOffset > 5) { - int optLength = (this.dataOffset << 2) - 20; - if (bb.limit() < bb.position() + optLength) { - optLength = bb.limit() - bb.position(); - } - try { - this.options = new byte[optLength]; - bb.get(this.options, 0, optLength); - } catch (final IndexOutOfBoundsException e) { - this.options = null; - } - } - - this.payload = new Data(); - this.payload = this.payload.deserialize(data, bb.position(), bb.limit() - - bb.position()); - this.payload.setParent(this); - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - result = prime * result + this.checksum; - result = prime * result + this.destinationPort; - result = prime * result + this.sourcePort; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof TCP)) { - return false; - } - final TCP other = (TCP) obj; - // May want to compare fields based on the flags set - return this.checksum == other.checksum - && this.destinationPort == other.destinationPort - && this.sourcePort == other.sourcePort - && this.sequence == other.sequence - && this.acknowledge == other.acknowledge - && this.dataOffset == other.dataOffset - && this.flags == other.flags - && this.windowSize == other.windowSize - && this.urgentPointer == other.urgentPointer - && (this.dataOffset == 5 || Arrays.equals(this.options, other.options)); - } - - /** - * Deserializer function for TCP packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, TCP_HEADER_LENGTH); - - TCP tcp = new TCP(); - - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - tcp.sourcePort = (bb.getShort() & 0xffff); - tcp.destinationPort = (bb.getShort() & 0xffff); - tcp.sequence = bb.getInt(); - tcp.acknowledge = bb.getInt(); - tcp.flags = bb.getShort(); - tcp.dataOffset = (byte) (tcp.flags >> 12 & 0xf); - tcp.flags = (short) (tcp.flags & 0x1ff); - tcp.windowSize = bb.getShort(); - tcp.checksum = bb.getShort(); - tcp.urgentPointer = bb.getShort(); - if (tcp.dataOffset > 5) { - int optLength = (tcp.dataOffset << 2) - 20; - checkHeaderLength(length, TCP_HEADER_LENGTH + tcp.dataOffset); - tcp.options = new byte[optLength]; - bb.get(tcp.options, 0, optLength); - } - - tcp.payload = Data.deserializer() - .deserialize(data, bb.position(), bb.limit() - bb.position()); - tcp.payload.setParent(tcp); - return tcp; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/TpPort.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/TpPort.java deleted file mode 100644 index 9b86a816..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/TpPort.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.onlab.packet; - -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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. - */ - -/** - * Representation of a transport layer port. - */ -public class TpPort { - - private final int port; - - // Transport layer port is unsigned 16 bits integer. - public static final int MAX_PORT = 0xFFFF; - public static final int MIN_PORT = 0; - - /** - * Constructs a new TpPort. - * - * @param value the transport layer port - */ - protected TpPort(int value) { - this.port = value; - } - - /** - * Converts an integer into a TpPort. - * - * @param value an integer representing the transport layer port - * @return a TpPort - * @throws IllegalArgumentException if the value is invalid - */ - public static TpPort tpPort(int value) { - if (value < MIN_PORT || value > MAX_PORT) { - throw new IllegalArgumentException( - "Transport layer port value " + value + "is not in the interval [0, 0xFFFF]"); - } - return new TpPort(value); - } - - /** - * Returns the integer value for this transport port. - * - * @return an integer value - */ - public int toInt() { - return this.port; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (obj instanceof TpPort) { - - TpPort other = (TpPort) obj; - - if (this.port == other.port) { - return true; - } - } - return false; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return this.port; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return String.valueOf(this.port); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/UDP.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/UDP.java deleted file mode 100644 index a30c9a92..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/UDP.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import static org.onlab.packet.PacketUtils.*; - -/** - * Representation of a UDP packet. - */ -public class UDP extends BasePacket { - public static final Map> PORT_DESERIALIZER_MAP = - new HashMap<>(); - public static final int DHCP_SERVER_PORT = 67; - public static final int DHCP_CLIENT_PORT = 68; - - private static final short UDP_HEADER_LENGTH = 8; - - static { - /* - * Disable DHCP until the deserialize code is hardened to deal with - * garbage input - */ - UDP.PORT_DESERIALIZER_MAP.put(UDP.DHCP_SERVER_PORT, DHCP.deserializer()); - UDP.PORT_DESERIALIZER_MAP.put(UDP.DHCP_CLIENT_PORT, DHCP.deserializer()); - - } - - protected int sourcePort; - protected int destinationPort; - protected short length; - protected short checksum; - - /** - * @return the sourcePort - */ - public int getSourcePort() { - return this.sourcePort; - } - - /** - * @param sourcePort - * the sourcePort to set (16 bits unsigned integer) - * @return this - */ - public UDP setSourcePort(final int sourcePort) { - this.sourcePort = sourcePort; - return this; - } - - /** - * @return the destinationPort - */ - public int getDestinationPort() { - return this.destinationPort; - } - - /** - * @param destinationPort - * the destinationPort to set (16 bits unsigned integer) - * @return this - */ - public UDP setDestinationPort(final int destinationPort) { - this.destinationPort = destinationPort; - return this; - } - - /** - * @return the length - */ - public short getLength() { - return this.length; - } - - /** - * @return the checksum - */ - public short getChecksum() { - return this.checksum; - } - - /** - * @param checksum - * the checksum to set - * @return this - */ - public UDP setChecksum(final short checksum) { - this.checksum = checksum; - return this; - } - - @Override - public void resetChecksum() { - this.checksum = 0; - super.resetChecksum(); - } - - /** - * Serializes the packet. Will compute and set the following fields if they - * are set to specific values at the time serialize is called: -checksum : 0 - * -length : 0 - */ - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - - this.length = (short) (8 + (payloadData == null ? 0 - : payloadData.length)); - - final byte[] data = new byte[this.length]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.putShort((short) (this.sourcePort & 0xffff)); - bb.putShort((short) (this.destinationPort & 0xffff)); - bb.putShort(this.length); - bb.putShort(this.checksum); - if (payloadData != null) { - bb.put(payloadData); - } - - if (this.parent != null && this.parent instanceof IPv4) { - ((IPv4) this.parent).setProtocol(IPv4.PROTOCOL_UDP); - } - - // compute checksum if needed - if (this.checksum == 0) { - bb.rewind(); - int accumulation = 0; - - // compute pseudo header mac - if (this.parent != null) { - if (this.parent instanceof IPv4) { - final IPv4 ipv4 = (IPv4) this.parent; - accumulation += (ipv4.getSourceAddress() >> 16 & 0xffff) - + (ipv4.getSourceAddress() & 0xffff); - accumulation += (ipv4.getDestinationAddress() >> 16 & 0xffff) - + (ipv4.getDestinationAddress() & 0xffff); - accumulation += ipv4.getProtocol() & 0xff; - accumulation += length & 0xffff; - } else if (this.parent instanceof IPv6) { - final IPv6 ipv6 = (IPv6) this.parent; - final int bbLength = - Ip6Address.BYTE_LENGTH * 2 // IPv6 src, dst - + 2 // nextHeader (with padding) - + 4; // length - final ByteBuffer bbChecksum = ByteBuffer.allocate(bbLength); - bbChecksum.put(ipv6.getSourceAddress()); - bbChecksum.put(ipv6.getDestinationAddress()); - bbChecksum.put((byte) 0); // padding - bbChecksum.put(ipv6.getNextHeader()); - bbChecksum.putInt(length); - bbChecksum.rewind(); - for (int i = 0; i < bbLength / 2; ++i) { - accumulation += 0xffff & bbChecksum.getShort(); - } - } - } - - for (int i = 0; i < this.length / 2; ++i) { - accumulation += 0xffff & bb.getShort(); - } - // pad to an even number of shorts - if (this.length % 2 > 0) { - accumulation += (bb.get() & 0xff) << 8; - } - - accumulation = (accumulation >> 16 & 0xffff) - + (accumulation & 0xffff); - this.checksum = (short) (~accumulation & 0xffff); - bb.putShort(6, this.checksum); - } - return data; - } - - @Override - public IPacket deserialize(final byte[] data, final int offset, - final int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.sourcePort = (bb.getShort() & 0xffff); - this.destinationPort = (bb.getShort() & 0xffff); - this.length = bb.getShort(); - this.checksum = bb.getShort(); - - Deserializer deserializer; - if (UDP.PORT_DESERIALIZER_MAP.containsKey(this.destinationPort)) { - deserializer = UDP.PORT_DESERIALIZER_MAP.get(this.destinationPort); - } else if (UDP.PORT_DESERIALIZER_MAP.containsKey(this.sourcePort)) { - deserializer = UDP.PORT_DESERIALIZER_MAP.get(this.sourcePort); - } else { - deserializer = Data.deserializer(); - } - - try { - this.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - this.payload.setParent(this); - } catch (DeserializationException e) { - return this; - } - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - result = prime * result + this.checksum; - result = prime * result + this.destinationPort; - result = prime * result + this.length; - result = prime * result + this.sourcePort; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof UDP)) { - return false; - } - final UDP other = (UDP) obj; - if (this.checksum != other.checksum) { - return false; - } - if (this.destinationPort != other.destinationPort) { - return false; - } - if (this.length != other.length) { - return false; - } - if (this.sourcePort != other.sourcePort) { - return false; - } - return true; - } - - /** - * Deserializer function for UDP packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, UDP_HEADER_LENGTH); - - UDP udp = new UDP(); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - udp.sourcePort = (bb.getShort() & 0xffff); - udp.destinationPort = (bb.getShort() & 0xffff); - udp.length = bb.getShort(); - udp.checksum = bb.getShort(); - - Deserializer deserializer; - if (UDP.PORT_DESERIALIZER_MAP.containsKey(udp.destinationPort)) { - deserializer = UDP.PORT_DESERIALIZER_MAP.get(udp.destinationPort); - } else if (UDP.PORT_DESERIALIZER_MAP.containsKey(udp.sourcePort)) { - deserializer = UDP.PORT_DESERIALIZER_MAP.get(udp.sourcePort); - } else { - deserializer = Data.deserializer(); - } - - udp.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - udp.payload.setParent(udp); - return udp; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/VlanId.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/VlanId.java deleted file mode 100644 index 4b38308b..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/VlanId.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet; - -/** - * Representation of a VLAN ID. - */ -public class VlanId { - - private final short value; - - // Based on convention used elsewhere? Check and change if needed - public static final short UNTAGGED = (short) 0xffff; - - // In a traffic selector, this means that a VLAN ID must be present, but - // can have any value. We use the same value as OpenFlow, but this is not - // required. - public static final short ANY_VALUE = (short) 0x1000; - - public static final VlanId NONE = VlanId.vlanId(UNTAGGED); - public static final VlanId ANY = VlanId.vlanId(ANY_VALUE); - - // A VLAN ID is actually 12 bits of a VLAN tag. - public static final short MAX_VLAN = 4095; - - protected VlanId() { - this.value = UNTAGGED; - } - - protected VlanId(short value) { - this.value = value; - } - - public static VlanId vlanId() { - return new VlanId(UNTAGGED); - } - - public static VlanId vlanId(short value) { - if (value == UNTAGGED) { - return new VlanId(); - } - - if (value == ANY_VALUE) { - return new VlanId(ANY_VALUE); - } - - if (value > MAX_VLAN) { - throw new IllegalArgumentException( - "value exceeds allowed maximum VLAN ID value (4095)"); - } - return new VlanId(value); - } - - public short toShort() { - return this.value; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (obj instanceof VlanId) { - - VlanId other = (VlanId) obj; - - if (this.value == other.value) { - return true; - } - } - - return false; - } - - @Override - public int hashCode() { - return this.value; - } - - @Override - public String toString() { - if (this.value == ANY_VALUE) { - return "Any"; - } - return String.valueOf(this.value); - } -} - diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Authentication.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Authentication.java deleted file mode 100644 index ec04a812..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Authentication.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet.ipv6; - -import org.onlab.packet.BasePacket; -import org.onlab.packet.Data; -import org.onlab.packet.DeserializationException; -import org.onlab.packet.Deserializer; -import org.onlab.packet.IPacket; -import org.onlab.packet.IPv6; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * Implements IPv6 authentication extension header format. (RFC 4302) - */ -public class Authentication extends BasePacket implements IExtensionHeader { - public static final byte FIXED_HEADER_LENGTH = 12; // bytes - public static final byte LENGTH_UNIT = 4; // bytes per unit - public static final byte MINUS = 2; - - protected byte nextHeader; - protected byte payloadLength; - protected int securityParamIndex; - protected int sequence; - protected byte[] integrityCheck; - - @Override - public byte getNextHeader() { - return this.nextHeader; - } - - @Override - public Authentication setNextHeader(final byte nextHeader) { - this.nextHeader = nextHeader; - return this; - } - - /** - * Gets the payload length of this header. - * - * @return the payload length - */ - public byte getPayloadLength() { - return this.payloadLength; - } - - /** - * Sets the payload length of this header. - * - * @param payloadLength the payload length to set - * @return this - */ - public Authentication setPayloadLength(final byte payloadLength) { - this.payloadLength = payloadLength; - return this; - } - - /** - * Gets the security parameter index of this header. - * - * @return the security parameter index - */ - public int getSecurityParamIndex() { - return this.securityParamIndex; - } - - /** - * Sets the security parameter index of this header. - * - * @param securityParamIndex the security parameter index to set - * @return this - */ - public Authentication setSecurityParamIndex(final int securityParamIndex) { - this.securityParamIndex = securityParamIndex; - return this; - } - - /** - * Gets the sequence number of this header. - * - * @return the sequence number - */ - public int getSequence() { - return this.sequence; - } - - /** - * Sets the sequence number of this header. - * - * @param sequence the sequence number to set - * @return this - */ - public Authentication setSequence(final int sequence) { - this.sequence = sequence; - return this; - } - - /** - * Gets the integrity check value of this header. - * - * @return the integrity check value - */ - public byte[] getIntegrityCheck() { - return this.integrityCheck; - } - - /** - * Sets the integrity check value of this header. - * - * @param integrityCheck the integrity check value to set - * @return this - */ - public Authentication setIngegrityCheck(final byte[] integrityCheck) { - this.integrityCheck = - Arrays.copyOfRange(integrityCheck, 0, integrityCheck.length); - return this; - } - - /** - * Gets the total length of this header. - * According to spec, payload length should be the total length of this AH - * in 4-octet unit, minus 2 - * - * @return the total length - */ - public int getTotalLength() { - return (this.payloadLength + MINUS) * LENGTH_UNIT; - } - - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - - int headerLength = FIXED_HEADER_LENGTH + integrityCheck.length; - int payloadLength = 0; - if (payloadData != null) { - payloadLength = payloadData.length; - } - - final byte[] data = new byte[headerLength + payloadLength]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.put(this.nextHeader); - bb.put(this.payloadLength); - bb.putShort((short) 0); - bb.putInt(this.securityParamIndex); - bb.putInt(this.sequence); - bb.put(this.integrityCheck, 0, integrityCheck.length); - - if (payloadData != null) { - bb.put(payloadData); - } - - if (this.parent != null && this.parent instanceof IExtensionHeader) { - ((IExtensionHeader) this.parent).setNextHeader(IPv6.PROTOCOL_AH); - } - return data; - } - - @Override - public IPacket deserialize(byte[] data, int offset, int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.nextHeader = bb.get(); - this.payloadLength = bb.get(); - bb.getShort(); - this.securityParamIndex = bb.getInt(); - this.sequence = bb.getInt(); - int icvLength = getTotalLength() - FIXED_HEADER_LENGTH; - this.integrityCheck = new byte[icvLength]; - bb.get(this.integrityCheck, 0, icvLength); - - Deserializer deserializer; - if (IPv6.PROTOCOL_DESERIALIZER_MAP.containsKey(this.nextHeader)) { - deserializer = IPv6.PROTOCOL_DESERIALIZER_MAP.get(this.nextHeader); - } else { - deserializer = Data.deserializer(); - } - - try { - this.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - this.payload.setParent(this); - } catch (DeserializationException e) { - return this; - } - - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - result = prime * result + this.nextHeader; - result = prime * result + this.payloadLength; - result = prime * result + this.securityParamIndex; - result = prime * result + this.sequence; - for (byte b : this.integrityCheck) { - result = prime * result + b; - } - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof Authentication)) { - return false; - } - final Authentication other = (Authentication) obj; - if (this.nextHeader != other.nextHeader) { - return false; - } - if (this.payloadLength != other.payloadLength) { - return false; - } - if (this.securityParamIndex != other.securityParamIndex) { - return false; - } - if (this.sequence != other.sequence) { - return false; - } - if (!Arrays.equals(this.integrityCheck, other.integrityCheck)) { - return false; - } - return true; - } - - /** - * Deserializer function for authentication headers. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, FIXED_HEADER_LENGTH); - - Authentication authentication = new Authentication(); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - authentication.nextHeader = bb.get(); - authentication.payloadLength = bb.get(); - bb.getShort(); - authentication.securityParamIndex = bb.getInt(); - authentication.sequence = bb.getInt(); - int icvLength = (authentication.payloadLength + MINUS) * LENGTH_UNIT - FIXED_HEADER_LENGTH; - authentication.integrityCheck = new byte[icvLength]; - bb.get(authentication.integrityCheck, 0, icvLength); - - Deserializer deserializer; - if (IPv6.PROTOCOL_DESERIALIZER_MAP.containsKey(authentication.nextHeader)) { - deserializer = IPv6.PROTOCOL_DESERIALIZER_MAP.get(authentication.nextHeader); - } else { - deserializer = Data.deserializer(); - } - authentication.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - authentication.payload.setParent(authentication); - - return authentication; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/BaseOptions.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/BaseOptions.java deleted file mode 100644 index f57b756e..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/BaseOptions.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet.ipv6; - -import org.onlab.packet.BasePacket; -import org.onlab.packet.Data; -import org.onlab.packet.DeserializationException; -import org.onlab.packet.Deserializer; -import org.onlab.packet.IPacket; -import org.onlab.packet.IPv6; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -import static org.onlab.packet.PacketUtils.checkHeaderLength; -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * Base class for hop-by-hop options and destination options. - */ -public class BaseOptions extends BasePacket implements IExtensionHeader { - public static final byte FIXED_HEADER_LENGTH = 2; // bytes - public static final byte FIXED_OPTIONS_LENGTH = 6; // bytes - public static final byte LENGTH_UNIT = 8; // bytes per unit - - protected byte nextHeader; - protected byte headerExtLength; - protected byte[] options; - protected byte type; - - @Override - public byte getNextHeader() { - return this.nextHeader; - } - - @Override - public BaseOptions setNextHeader(final byte nextHeader) { - this.nextHeader = nextHeader; - return this; - } - - /** - * Gets the extension length of this header. - * - * @return header length - */ - public byte getHeaderExtLength() { - return this.headerExtLength; - } - - /** - * Sets the extension length of this header. - * - * @param headerExtLength the header length to set - * @return this - */ - public BaseOptions setHeaderExtLength(final byte headerExtLength) { - this.headerExtLength = headerExtLength; - return this; - } - - /** - * Gets the options. - * - * @return the options - */ - public byte[] getOptions() { - return this.options; - } - - /** - * Sets the options. - * - * @param options the options to set - * @return this - */ - public BaseOptions setOptions(final byte[] options) { - this.options = - Arrays.copyOfRange(options, 0, options.length); - return this; - } - - /** - * Gets the type of this option. - * - * @return the type - */ - protected byte getType() { - return this.type; - } - - /** - * Sets the type of this option. - * Must be either IPv6.PROTOCOL_HOPOPT or IPv6.PROTOCOL_DSTOPT - * - * @param type the type to set - * @return this - */ - protected BaseOptions setType(final byte type) { - this.type = type; - return this; - } - - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - - int headerLength = FIXED_HEADER_LENGTH + options.length; - int payloadLength = 0; - if (payloadData != null) { - payloadLength = payloadData.length; - } - - final byte[] data = new byte[headerLength + payloadLength]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.put(this.nextHeader); - bb.put(this.headerExtLength); - bb.put(this.options, 0, options.length); - - if (payloadData != null) { - bb.put(payloadData); - } - - if (this.parent != null && this.parent instanceof IExtensionHeader) { - ((IExtensionHeader) this.parent).setNextHeader(this.type); - } - return data; - } - - @Override - public IPacket deserialize(byte[] data, int offset, int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.nextHeader = bb.get(); - this.headerExtLength = bb.get(); - int optionLength = - FIXED_OPTIONS_LENGTH + LENGTH_UNIT * this.headerExtLength; - this.options = new byte[optionLength]; - bb.get(this.options, 0, optionLength); - - Deserializer deserializer; - if (IPv6.PROTOCOL_DESERIALIZER_MAP.containsKey(this.nextHeader)) { - deserializer = IPv6.PROTOCOL_DESERIALIZER_MAP.get(this.nextHeader); - } else { - deserializer = Data.deserializer(); - } - try { - this.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - this.payload.setParent(this); - } catch (DeserializationException e) { - return this; - } - - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - result = prime * result + this.nextHeader; - result = prime * result + this.headerExtLength; - for (byte b : this.options) { - result = prime * result + b; - } - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof BaseOptions)) { - return false; - } - final BaseOptions other = (BaseOptions) obj; - if (this.nextHeader != other.nextHeader) { - return false; - } - if (this.headerExtLength != other.headerExtLength) { - return false; - } - if (!Arrays.equals(this.options, other.options)) { - return false; - } - if (this.type != other.type) { - return false; - } - return true; - } - - /** - * Deserializer function for IPv6 base options. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, FIXED_HEADER_LENGTH); - - BaseOptions baseOptions = new BaseOptions(); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - baseOptions.nextHeader = bb.get(); - baseOptions.headerExtLength = bb.get(); - int optionLength = - FIXED_OPTIONS_LENGTH + LENGTH_UNIT * baseOptions.headerExtLength; - - checkHeaderLength(bb.remaining(), optionLength); - - baseOptions.options = new byte[optionLength]; - bb.get(baseOptions.options, 0, optionLength); - - Deserializer deserializer; - if (IPv6.PROTOCOL_DESERIALIZER_MAP.containsKey(baseOptions.nextHeader)) { - deserializer = IPv6.PROTOCOL_DESERIALIZER_MAP.get(baseOptions.nextHeader); - } else { - deserializer = Data.deserializer(); - } - baseOptions.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - baseOptions.payload.setParent(baseOptions); - - return baseOptions; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/DestinationOptions.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/DestinationOptions.java deleted file mode 100644 index 208bdd7e..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/DestinationOptions.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet.ipv6; - -import org.onlab.packet.IPv6; - -/** - * Implements IPv6 Destination Options extension header format. (RFC 2460) - */ -public class DestinationOptions extends BaseOptions { - public DestinationOptions() { - super(); - this.setType(IPv6.PROTOCOL_DSTOPT); - } -} \ No newline at end of file diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/EncapSecurityPayload.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/EncapSecurityPayload.java deleted file mode 100644 index e46a1261..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/EncapSecurityPayload.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet.ipv6; - -import org.onlab.packet.BasePacket; -import org.onlab.packet.Data; -import org.onlab.packet.Deserializer; -import org.onlab.packet.IPacket; -import org.onlab.packet.IPv6; - -import java.nio.ByteBuffer; - -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * Implements IPv6 Encapsulating Security Payload (ESP) extension header format. - * (RFC 4303) - */ -public class EncapSecurityPayload extends BasePacket { - public static final byte HEADER_LENGTH = 8; // bytes - - protected int securityParamIndex; - protected int sequence; - // - // NOTE: The remaining fields including payload data, padding length and - // next header are encrypted and all considered as a payload of ESP. - // - - /** - * Gets the security parameter index of this header. - * - * @return the security parameter index - */ - public int getSecurityParamIndex() { - return this.securityParamIndex; - } - - /** - * Sets the security parameter index of this header. - * - * @param securityParamIndex the security parameter index to set - * @return this - */ - public EncapSecurityPayload setSecurityParamIndex(final int securityParamIndex) { - this.securityParamIndex = securityParamIndex; - return this; - } - - /** - * Gets the sequence number of this header. - * - * @return the sequence number - */ - public int getSequence() { - return this.sequence; - } - - /** - * Sets the sequence number of this header. - * - * @param sequence the sequence number to set - * @return this - */ - public EncapSecurityPayload setSequence(final int sequence) { - this.sequence = sequence; - return this; - } - - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - - int payloadLength = 0; - if (payloadData != null) { - payloadLength = payloadData.length; - } - - final byte[] data = new byte[HEADER_LENGTH + payloadLength]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.putInt(this.securityParamIndex); - bb.putInt(this.sequence); - - if (payloadData != null) { - bb.put(payloadData); - } - - if (this.parent != null && this.parent instanceof IExtensionHeader) { - ((IExtensionHeader) this.parent).setNextHeader(IPv6.PROTOCOL_ESP); - } - return data; - } - - @Override - public IPacket deserialize(byte[] data, int offset, int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.securityParamIndex = bb.getInt(); - this.sequence = bb.getInt(); - - this.payload = new Data(); - this.payload.deserialize(data, bb.position(), - bb.limit() - bb.position()); - this.payload.setParent(this); - - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - result = prime * result + this.securityParamIndex; - result = prime * result + this.sequence; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof EncapSecurityPayload)) { - return false; - } - final EncapSecurityPayload other = (EncapSecurityPayload) obj; - if (this.securityParamIndex != other.securityParamIndex) { - return false; - } - if (this.sequence != other.sequence) { - return false; - } - return true; - } - - /** - * Deserializer function for encapsulated security payload headers. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, HEADER_LENGTH); - - EncapSecurityPayload encapSecurityPayload = new EncapSecurityPayload(); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - encapSecurityPayload.securityParamIndex = bb.getInt(); - encapSecurityPayload.sequence = bb.getInt(); - - encapSecurityPayload.payload = Data.deserializer().deserialize( - data, bb.position(), bb.limit() - bb.position()); - encapSecurityPayload.payload.setParent(encapSecurityPayload); - - return encapSecurityPayload; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Fragment.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Fragment.java deleted file mode 100644 index 68015d31..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Fragment.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet.ipv6; - -import org.onlab.packet.BasePacket; -import org.onlab.packet.Data; -import org.onlab.packet.DeserializationException; -import org.onlab.packet.Deserializer; -import org.onlab.packet.IPacket; -import org.onlab.packet.IPv6; - -import java.nio.ByteBuffer; - -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * Implements IPv6 fragment extension header format. (RFC 2460) - */ -public class Fragment extends BasePacket implements IExtensionHeader { - public static final byte HEADER_LENGTH = 8; // bytes - - protected byte nextHeader; - protected short fragmentOffset; - protected byte moreFragment; - protected int identification; - - @Override - public byte getNextHeader() { - return this.nextHeader; - } - - @Override - public Fragment setNextHeader(final byte nextHeader) { - this.nextHeader = nextHeader; - return this; - } - - /** - * Gets the fragment offset of this header. - * - * @return fragment offset - */ - public short getFragmentOffset() { - return this.fragmentOffset; - } - - /** - * Sets the fragment offset of this header. - * - * @param fragmentOffset the fragment offset to set - * @return this - */ - public Fragment setFragmentOffset(final short fragmentOffset) { - this.fragmentOffset = fragmentOffset; - return this; - } - - /** - * Gets the more fragment flag of this header. - * - * @return more fragment flag - */ - public byte getMoreFragment() { - return this.moreFragment; - } - - /** - * Sets the more fragment flag of this header. - * - * @param moreFragment the more fragment flag to set - * @return this - */ - public Fragment setMoreFragment(final byte moreFragment) { - this.moreFragment = moreFragment; - return this; - } - - /** - * Gets the identification of this header. - * - * @return identification - */ - public int getIdentification() { - return this.identification; - } - - /** - * Sets the identification of this header. - * - * @param identification the identification to set - * @return this - */ - public Fragment setIdentification(final int identification) { - this.identification = identification; - return this; - } - - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - - int payloadLength = 0; - if (payloadData != null) { - payloadLength = payloadData.length; - } - - final byte[] data = new byte[HEADER_LENGTH + payloadLength]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.put(this.nextHeader); - bb.put((byte) 0); - bb.putShort((short) ( - (this.fragmentOffset & 0x1fff) << 3 | - this.moreFragment & 0x1 - )); - bb.putInt(this.identification); - - if (payloadData != null) { - bb.put(payloadData); - } - - if (this.parent != null && this.parent instanceof IExtensionHeader) { - ((IExtensionHeader) this.parent).setNextHeader(IPv6.PROTOCOL_FRAG); - } - return data; - } - - @Override - public IPacket deserialize(byte[] data, int offset, int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.nextHeader = bb.get(); - bb.get(); - short sscratch = bb.getShort(); - this.fragmentOffset = (short) (sscratch >> 3 & 0x1fff); - this.moreFragment = (byte) (sscratch & 0x1); - this.identification = bb.getInt(); - - Deserializer deserializer; - if (IPv6.PROTOCOL_DESERIALIZER_MAP.containsKey(this.nextHeader)) { - deserializer = IPv6.PROTOCOL_DESERIALIZER_MAP.get(this.nextHeader); - } else { - deserializer = Data.deserializer(); - } - try { - this.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - this.payload.setParent(this); - } catch (DeserializationException e) { - return this; - } - - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - result = prime * result + this.nextHeader; - result = prime * result + this.fragmentOffset; - result = prime * result + this.moreFragment; - result = prime * result + this.identification; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof Fragment)) { - return false; - } - final Fragment other = (Fragment) obj; - if (this.nextHeader != other.nextHeader) { - return false; - } - if (this.fragmentOffset != other.fragmentOffset) { - return false; - } - if (this.moreFragment != other.moreFragment) { - return false; - } - if (this.identification != other.identification) { - return false; - } - return true; - } - - /** - * Deserializer function for fragment headers. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, HEADER_LENGTH); - - Fragment fragment = new Fragment(); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - fragment.nextHeader = bb.get(); - bb.get(); - short sscratch = bb.getShort(); - fragment.fragmentOffset = (short) (sscratch >> 3 & 0x1fff); - fragment.moreFragment = (byte) (sscratch & 0x1); - fragment.identification = bb.getInt(); - - Deserializer deserializer; - if (IPv6.PROTOCOL_DESERIALIZER_MAP.containsKey(fragment.nextHeader)) { - deserializer = IPv6.PROTOCOL_DESERIALIZER_MAP.get(fragment.nextHeader); - } else { - deserializer = Data.deserializer(); - } - fragment.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - fragment.payload.setParent(fragment); - - return fragment; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/HopByHopOptions.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/HopByHopOptions.java deleted file mode 100644 index cd8c141c..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/HopByHopOptions.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet.ipv6; - -import org.onlab.packet.IPv6; - -/** - * Implements IPv6 Hop-by-hop Options extension header format. (RFC 2460) - */ -public class HopByHopOptions extends BaseOptions { - public HopByHopOptions() { - super(); - this.setType(IPv6.PROTOCOL_HOPOPT); - } -} \ No newline at end of file diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/IExtensionHeader.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/IExtensionHeader.java deleted file mode 100644 index 252f1a3c..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/IExtensionHeader.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet.ipv6; - -/** - * Interface for IPv6 extension header. - */ -public interface IExtensionHeader { - /** - * Gets the type of next header. - * - * @return next header - */ - byte getNextHeader(); - - /** - * Sets the type of next header. - * - * @param nextHeader the next header to set - * @return this - */ - IExtensionHeader setNextHeader(final byte nextHeader); -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Routing.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Routing.java deleted file mode 100644 index d7d204a9..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/Routing.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet.ipv6; - -import org.onlab.packet.BasePacket; -import org.onlab.packet.Data; -import org.onlab.packet.DeserializationException; -import org.onlab.packet.Deserializer; -import org.onlab.packet.IPacket; -import org.onlab.packet.IPv6; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -import static org.onlab.packet.PacketUtils.checkHeaderLength; -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * Implements IPv6 routing extension header format. (RFC 2460) - */ -public class Routing extends BasePacket implements IExtensionHeader { - public static final byte FIXED_HEADER_LENGTH = 4; // bytes - public static final byte FIXED_ROUTING_DATA_LENGTH = 4; // bytes - public static final byte LENGTH_UNIT = 8; // bytes per unit - - protected byte nextHeader; - protected byte headerExtLength; - protected byte routingType; - protected byte segmentsLeft; - protected byte[] routingData; - - @Override - public byte getNextHeader() { - return this.nextHeader; - } - - @Override - public Routing setNextHeader(final byte nextHeader) { - this.nextHeader = nextHeader; - return this; - } - - /** - * Gets the extension length of this header. - * - * @return header length - */ - public byte getHeaderExtLength() { - return this.headerExtLength; - } - - /** - * Sets the extension length of this header. - * - * @param headerExtLength the header length to set - * @return this - */ - public Routing setHeaderExtLength(final byte headerExtLength) { - this.headerExtLength = headerExtLength; - return this; - } - - /** - * Gets the routing type of this header. - * - * @return routing type - */ - public byte getRoutingType() { - return this.routingType; - } - - /** - * Sets the routing type of this header. - * - * @param routingType the routing type to set - * @return this - */ - public Routing setRoutingType(final byte routingType) { - this.routingType = routingType; - return this; - } - - /** - * Gets the number of remaining route segments of this header. - * - * @return number of remaining route segments - */ - public byte getSegmentsLeft() { - return this.segmentsLeft; - } - - /** - * Sets the number of remaining route segments of this header. - * - * @param segmentsLeft the number of remaining route segments to set - * @return this - */ - public Routing setSegmntsLeft(final byte segmentsLeft) { - this.segmentsLeft = segmentsLeft; - return this; - } - - /** - * Gets the routing data. - * - * @return the routing data - */ - public byte[] getRoutingData() { - return this.routingData; - } - - /** - * Sets the routing data. - * - * @param routingData the routing data to set - * @return this - */ - public Routing setRoutingData(final byte[] routingData) { - this.routingData = - Arrays.copyOfRange(routingData, 0, routingData.length); - return this; - } - - @Override - public byte[] serialize() { - byte[] payloadData = null; - if (this.payload != null) { - this.payload.setParent(this); - payloadData = this.payload.serialize(); - } - - int headerLength = FIXED_HEADER_LENGTH + routingData.length; - int payloadLength = 0; - if (payloadData != null) { - payloadLength = payloadData.length; - } - - final byte[] data = new byte[headerLength + payloadLength]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.put(this.nextHeader); - bb.put(this.headerExtLength); - bb.put(this.routingType); - bb.put(this.segmentsLeft); - bb.put(this.routingData, 0, routingData.length); - - if (payloadData != null) { - bb.put(payloadData); - } - - if (this.parent != null && this.parent instanceof IExtensionHeader) { - ((IExtensionHeader) this.parent).setNextHeader(IPv6.PROTOCOL_ROUTING); - } - return data; - } - - @Override - public IPacket deserialize(byte[] data, int offset, int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - this.nextHeader = bb.get(); - this.headerExtLength = bb.get(); - this.routingType = bb.get(); - this.segmentsLeft = bb.get(); - int dataLength = - FIXED_ROUTING_DATA_LENGTH + LENGTH_UNIT * this.headerExtLength; - this.routingData = new byte[dataLength]; - bb.get(this.routingData, 0, dataLength); - - Deserializer deserializer; - if (IPv6.PROTOCOL_DESERIALIZER_MAP.containsKey(this.nextHeader)) { - deserializer = IPv6.PROTOCOL_DESERIALIZER_MAP.get(this.nextHeader); - } else { - deserializer = new Data().deserializer(); - } - try { - this.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - this.payload.setParent(this); - } catch (DeserializationException e) { - return this; - } - - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - result = prime * result + this.nextHeader; - result = prime * result + this.headerExtLength; - result = prime * result + this.routingType; - result = prime * result + this.segmentsLeft; - for (byte b : this.routingData) { - result = prime * result + b; - } - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof Routing)) { - return false; - } - final Routing other = (Routing) obj; - if (this.nextHeader != other.nextHeader) { - return false; - } - if (this.headerExtLength != other.headerExtLength) { - return false; - } - if (this.routingType != other.routingType) { - return false; - } - if (this.segmentsLeft != other.segmentsLeft) { - return false; - } - if (!Arrays.equals(this.routingData, other.routingData)) { - return false; - } - return true; - } - - /** - * Deserializer function for routing headers. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, FIXED_HEADER_LENGTH); - - Routing routing = new Routing(); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - routing.nextHeader = bb.get(); - routing.headerExtLength = bb.get(); - routing.routingType = bb.get(); - routing.segmentsLeft = bb.get(); - int dataLength = - FIXED_ROUTING_DATA_LENGTH + LENGTH_UNIT * routing.headerExtLength; - - checkHeaderLength(bb.remaining(), dataLength); - - routing.routingData = new byte[dataLength]; - bb.get(routing.routingData, 0, dataLength); - - Deserializer deserializer; - if (IPv6.PROTOCOL_DESERIALIZER_MAP.containsKey(routing.nextHeader)) { - deserializer = IPv6.PROTOCOL_DESERIALIZER_MAP.get(routing.nextHeader); - } else { - deserializer = new Data().deserializer(); - } - routing.payload = deserializer.deserialize(data, bb.position(), - bb.limit() - bb.position()); - routing.payload.setParent(routing); - - return routing; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/package-info.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/package-info.java deleted file mode 100644 index 714fd1b2..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ipv6/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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. - */ - -/** - * Utilities for decoding and encoding IPv6 extension headers. - */ -package org.onlab.packet.ipv6; diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/NeighborAdvertisement.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/NeighborAdvertisement.java deleted file mode 100644 index 99fa0dd6..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/NeighborAdvertisement.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.packet.ndp; - -import org.onlab.packet.BasePacket; -import org.onlab.packet.Deserializer; -import org.onlab.packet.IPacket; -import org.onlab.packet.Ip6Address; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.List; - -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * Implements ICMPv6 Neighbor Advertisement packet format (RFC 4861). - */ -public class NeighborAdvertisement extends BasePacket { - public static final byte HEADER_LENGTH = 20; // bytes - - protected byte routerFlag; - protected byte solicitedFlag; - protected byte overrideFlag; - protected byte[] targetAddress = new byte[Ip6Address.BYTE_LENGTH]; - - private final NeighborDiscoveryOptions options = - new NeighborDiscoveryOptions(); - - /** - * Gets router flag. - * - * @return the router flag - */ - public byte getRouterFlag() { - return this.routerFlag; - } - - /** - * Sets router flag. - * - * @param routerFlag the router flag to set - * @return this - */ - public NeighborAdvertisement setRouterFlag(final byte routerFlag) { - this.routerFlag = routerFlag; - return this; - } - - /** - * Gets solicited flag. - * - * @return the solicited flag - */ - public byte getSolicitedFlag() { - return this.solicitedFlag; - } - - /** - * Sets solicited flag. - * - * @param solicitedFlag the solicited flag to set - * @return this - */ - public NeighborAdvertisement setSolicitedFlag(final byte solicitedFlag) { - this.solicitedFlag = solicitedFlag; - return this; - } - - /** - * Gets override flag. - * - * @return the override flag - */ - public byte getOverrideFlag() { - return this.overrideFlag; - } - - /** - * Sets override flag. - * - * @param overrideFlag the override flag to set - * @return this - */ - public NeighborAdvertisement setOverrideFlag(final byte overrideFlag) { - this.overrideFlag = overrideFlag; - return this; - } - - /** - * Gets target address. - * - * @return the target IPv6 address - */ - public byte[] getTargetAddress() { - return this.targetAddress; - } - - /** - * Sets target address. - * - * @param targetAddress the target IPv6 address to set - * @return this - */ - public NeighborAdvertisement setTargetAddress(final byte[] targetAddress) { - this.targetAddress = - Arrays.copyOfRange(targetAddress, 0, Ip6Address.BYTE_LENGTH); - return this; - } - - /** - * Gets the Neighbor Discovery Protocol packet options. - * - * @return the Neighbor Discovery Protocol packet options - */ - public List getOptions() { - return this.options.options(); - } - - /** - * Adds a Neighbor Discovery Protocol packet option. - * - * @param type the option type - * @param data the option data - * @return this - */ - public NeighborAdvertisement addOption(final byte type, - final byte[] data) { - this.options.addOption(type, data); - return this; - } - - @Override - public byte[] serialize() { - byte[] optionsData = null; - if (this.options.hasOptions()) { - optionsData = this.options.serialize(); - } - - int optionsLength = 0; - if (optionsData != null) { - optionsLength = optionsData.length; - } - - final byte[] data = new byte[HEADER_LENGTH + optionsLength]; - final ByteBuffer bb = ByteBuffer.wrap(data); - - bb.putInt((this.routerFlag & 0x1) << 31 | - (this.solicitedFlag & 0x1) << 30 | - (this.overrideFlag & 0x1) << 29); - bb.put(this.targetAddress, 0, Ip6Address.BYTE_LENGTH); - if (optionsData != null) { - bb.put(optionsData); - } - - return data; - } - - @Override - public IPacket deserialize(byte[] data, int offset, int length) { - final ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - int iscratch; - - iscratch = bb.getInt(); - this.routerFlag = (byte) (iscratch >> 31 & 0x1); - this.solicitedFlag = (byte) (iscratch >> 30 & 0x1); - this.overrideFlag = (byte) (iscratch >> 29 & 0x1); - bb.get(this.targetAddress, 0, Ip6Address.BYTE_LENGTH); - - this.options.deserialize(data, bb.position(), - bb.limit() - bb.position()); - - return this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 5807; - int result = super.hashCode(); - ByteBuffer bb; - result = prime * result + this.routerFlag; - result = prime * result + this.solicitedFlag; - result = prime * result + this.overrideFlag; - bb = ByteBuffer.wrap(this.targetAddress); - for (int i = 0; i < this.targetAddress.length / 4; i++) { - result = prime * result + bb.getInt(); - } - result = prime * result + this.options.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof NeighborAdvertisement)) { - return false; - } - final NeighborAdvertisement other = (NeighborAdvertisement) obj; - if (this.routerFlag != other.routerFlag) { - return false; - } - if (this.solicitedFlag != other.solicitedFlag) { - return false; - } - if (this.overrideFlag != other.overrideFlag) { - return false; - } - if (!Arrays.equals(this.targetAddress, other.targetAddress)) { - return false; - } - if (!this.options.equals(other.options)) { - return false; - } - return true; - } - - /** - * Deserializer function for neighbor advertisement packets. - * - * @return deserializer function - */ - public static Deserializer deserializer() { - return (data, offset, length) -> { - checkInput(data, offset, length, HEADER_LENGTH); - - NeighborAdvertisement neighborAdvertisement = new NeighborAdvertisement(); - - ByteBuffer bb = ByteBuffer.wrap(data, offset, length); - - int iscratch; - - iscratch = bb.getInt(); - neighborAdvertisement.routerFlag = (byte) (iscratch >> 31 & 0x1); - neighborAdvertisement.solicitedFlag = (byte) (iscratch >> 30 & 0x1); - neighborAdvertisement.overrideFlag = (byte) (iscratch >> 29 & 0x1); - bb.get(neighborAdvertisement.targetAddress, 0, Ip6Address.BYTE_LENGTH); - - if (bb.limit() - bb.position() > 0) { - NeighborDiscoveryOptions options = NeighborDiscoveryOptions.deserializer() - .deserialize(data, bb.position(), bb.limit() - bb.position()); - - for (NeighborDiscoveryOptions.Option option : options.options()) { - neighborAdvertisement.addOption(option.type(), option.data()); - } - } - - return neighborAdvertisement; - }; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/NeighborDiscoveryOptions.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/NeighborDiscoveryOptions.java deleted file mode 100644 index 00a26068..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/packet/ndp/NeighborDiscoveryOptions.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.packet.ndp; - -import org.onlab.packet.BasePacket; -import org.onlab.packet.DeserializationException; -import org.onlab.packet.Deserializer; -import org.onlab.packet.IPacket; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.onlab.packet.PacketUtils.checkInput; - -/** - * Neighbor Discovery Protocol packet options. - */ -public class NeighborDiscoveryOptions extends BasePacket { - public static final byte TYPE_SOURCE_LL_ADDRESS = 1; - public static final byte TYPE_TARGET_LL_ADDRESS = 2; - public static final byte TYPE_PREFIX_INFORMATION = 3; - public static final byte TYPE_REDIRECTED_HEADER = 4; - public static final byte TYPE_MTU = 5; - - public static final byte INITIAL_HEADER_REQUIRED = 2; - - private static final String BUFFER_UNDERFLOW_ERROR = - "Not enough bytes in buffer to read option"; - - private final List