Coverage Summary for Class: NodeDistanceTable (co.rsk.net.discovery.table)

Class Class, % Method, % Line, %
NodeDistanceTable 0% (0/1) 0% (0/7) 0% (0/22)


1 /* 2  * This file is part of RskJ 3  * Copyright (C) 2017 RSK Labs Ltd. 4  * 5  * This program is free software: you can redistribute it and/or modify 6  * it under the terms of the GNU Lesser General Public License as published by 7  * the Free Software Foundation, either version 3 of the License, or 8  * (at your option) any later version. 9  * 10  * This program is distributed in the hope that it will be useful, 11  * but WITHOUT ANY WARRANTY; without even the implied warranty of 12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13  * GNU Lesser General Public License for more details. 14  * 15  * You should have received a copy of the GNU Lesser General Public License 16  * along with this program. If not, see <http://www.gnu.org/licenses/>. 17  */ 18  19 package co.rsk.net.discovery.table; 20  21 import co.rsk.net.NodeID; 22 import org.ethereum.net.rlpx.Node; 23  24 import java.util.*; 25 import java.util.concurrent.ConcurrentHashMap; 26 import java.util.stream.Collectors; 27  28 /** 29  * Created by mario on 21/02/17. 30  */ 31 public class NodeDistanceTable { 32  private Map<Integer, Bucket> buckets = new ConcurrentHashMap<>(); 33  private final Node localNode; 34  private final DistanceCalculator distanceCalculator; 35  36  public NodeDistanceTable(int numberOfBuckets, int entriesPerBucket, Node localNode) { 37  this.localNode = localNode; 38  this.distanceCalculator = new DistanceCalculator(numberOfBuckets); 39  40  for (int i = 0; i < numberOfBuckets; i++) { 41  buckets.put(i, new Bucket(entriesPerBucket, i)); 42  } 43  } 44  45  public synchronized OperationResult addNode(Node node) { 46  return getNodeBucket(node).addNode(node); 47  } 48  49  public synchronized OperationResult removeNode(Node node) { 50  return getNodeBucket(node).removeNode(node); 51  } 52  53  public synchronized List<Node> getClosestNodes(NodeID nodeId) { 54  return getAllNodes().stream() 55  .sorted(new NodeDistanceComparator(nodeId, this.distanceCalculator)) 56  .collect(Collectors.toList()); 57  } 58  59  private Bucket getNodeBucket(Node node) { 60  int distance = this.distanceCalculator.calculateDistance(this.localNode.getId(), node.getId()) - 1; 61  distance = (distance >= 0) ? distance : 0; 62  63  return this.buckets.get(distance); 64  } 65  66  public Set<Node> getAllNodes() { 67  Set<Node> ret = new HashSet<>(); 68  69  for (Bucket bucket : this.buckets.values()) { 70  ret.addAll(bucket.getEntries().stream() 71  .map(BucketEntry::getNode).collect(Collectors.toList())); 72  } 73  74  return ret; 75  } 76  77  public void updateEntry(Node node) { 78  Bucket bucket = getNodeBucket(node); 79  bucket.updateEntry(node); 80  } 81  82 }