-
Notifications
You must be signed in to change notification settings - Fork 0
/
FingerTable.java
119 lines (102 loc) · 2.47 KB
/
FingerTable.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
/**
* Defines the FingerTable used by RMINodes.
* The FingerTable has the list of fingers for one node.
*
* @author dmac
*
*/
public class FingerTable implements Iterable<Finger> {
/**
* Random number generator for use in the getRandomFinger method
*/
private static Random random = new Random();
private List<Finger> fingers;
/**
* FingerTable Constructor.
* Populates the finger table with the nodeKeys of each finger.
*
* @param forNode
* @throws RemoteException
*/
public FingerTable(RMINodeServer forNode) throws RemoteException {
fingers = new ArrayList<Finger>();
int hashLength = forNode.getHashLength();
long maxValue = (long) Math.pow(2, hashLength);
for (int i = 0; i < hashLength; i++)
fingers.add(new Finger((long) ((forNode.getNodeKey() + Math.pow(2, i)) % maxValue)));
}
/**
* Returns the first finger in the finger table (the successor).
*
* @return
*/
public Finger getSuccessor() {
if (fingers.size() == 0)
return null;
return fingers.get(0);
}
/**
* Returns a random finger that is not the successor.
*
* @return
*/
public Finger getRandomFinger() {
return fingers.get(random.nextInt(fingers.size()-1)+1);
}
public Iterable<Finger> reverse() {
return new ReverseIterator<Finger>(fingers);
}
@Override
public Iterator<Finger> iterator() {
return fingers.iterator();
}
/**
* The finger is conveted to a human-readable format.
* This is used for logging.
*/
@Override
public String toString() {
String s = "";
for(Finger f: this) {
s += f.getStart() + ":";
try{
s += f.getNode().getNodeKey();
} catch(NullPointerException | RemoteException e){
s += "-";
}
s += " ";
}
return s;
}
/**
* An iterator for lists that allows the programmer to traverse the list in
* reverse order.
*
* @param <T>
*/
class ReverseIterator<T> implements Iterable<T> {
private ListIterator<T> listIterator;
public ReverseIterator(List<T> wrappedList) {
this.listIterator = wrappedList.listIterator(wrappedList.size());
}
public Iterator<T> iterator() {
return new Iterator<T>() {
public boolean hasNext() {
return listIterator.hasPrevious();
}
public T next() {
return listIterator.previous();
}
public void remove() {
listIterator.remove();
}
};
}
}
}