Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
24164a498c38e05106e2c3faae8046a83235d179
[simgrid.git] / examples / java / kademlia / Answer.java
1 /* Copyright (c) 2012-2014, 2016. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 package kademlia;
8 import java.util.ArrayList;
9 import java.util.Collections;
10
11 /* Answer to a "FIND_NODE" query. Contains the nodes closest to an id given */
12 public class Answer {
13   private int destinationId;
14   /* Closest nodes in the answer. */
15   private ArrayList<Contact> nodes;
16
17   public Answer(int destinationId) {
18     this.destinationId = destinationId;
19     nodes = new ArrayList<Contact>();
20   }
21
22   int getDestinationId() {
23     return destinationId;
24   }
25
26   ArrayList<Contact> getNodes() {
27     return nodes;
28   }
29
30   int size() {
31     return nodes.size();
32   }
33
34   public void remove(int index) {
35     nodes.remove(index);
36   }
37
38   public void add(Contact contact) {
39     nodes.add(contact);
40   }
41
42   /* Merge the contents of this answer with another answer */
43   public int merge(Answer answer) {
44     int nbAdded = 0;
45
46     for (Contact c: answer.getNodes()) {
47       if (!nodes.contains(c)) {
48         nbAdded++;
49         nodes.add(c);
50       }
51     }
52     Collections.sort(nodes);
53     //Trim the list
54     while (answer.size() > Common.BUCKET_SIZE) {
55       answer.remove(answer.size() - 1);
56     }
57     return nbAdded;
58   }
59
60   /* Returns if the destination has been found */
61   public boolean destinationFound() {
62     if (nodes.size() < 1) {
63       return false;
64     }
65     Contact tail = nodes.get(0);
66     return tail.getDistance() == 0;
67   }
68
69   @Override
70   public String toString() {
71     return "Answer [destinationId=" + destinationId + ", nodes=" + nodes + "]";
72   }
73 }