Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines with new year.
[simgrid.git] / examples / java / dht / kademlia / Answer.java
1 /* Copyright (c) 2012-2019. 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 dht.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<>();
20   }
21
22   protected int getDestinationId() {
23     return destinationId;
24   }
25
26   protected ArrayList<Contact> getNodes() {
27     return nodes;
28   }
29
30   protected int size() {
31     return nodes.size();
32   }
33
34   public void trim() {
35     if (nodes.size() > Common.BUCKET_SIZE)
36       nodes.subList(nodes.size() - Common.BUCKET_SIZE, nodes.size()).clear();
37   }
38
39   public void add(Contact contact) {
40     nodes.add(contact);
41   }
42
43   /* Merge the contents of this answer with another answer */
44   public int merge(Answer answer) {
45     int nbAdded = 0;
46
47     for (Contact c: answer.getNodes()) {
48       if (!nodes.contains(c)) {
49         nbAdded++;
50         nodes.add(c);
51       }
52     }
53     Collections.sort(nodes);
54     //Trim the list
55     answer.trim();
56
57     return nbAdded;
58   }
59
60   /* Returns if the destination has been found */
61   public boolean destinationFound() {
62     if (nodes.isEmpty()) {
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 }