1 package net.pterodactylus.fcp.quelaton;
3 import java.io.IOException;
4 import java.util.concurrent.ExecutionException;
5 import java.util.concurrent.ExecutorService;
6 import java.util.concurrent.atomic.AtomicBoolean;
7 import java.util.concurrent.atomic.AtomicReference;
9 import net.pterodactylus.fcp.PeerRemoved;
10 import net.pterodactylus.fcp.RemovePeer;
11 import net.pterodactylus.fcp.UnknownNodeIdentifier;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.ListeningExecutorService;
15 import com.google.common.util.concurrent.MoreExecutors;
18 * Default {@link RemovePeerCommand} implementation based on {@link FcpDialog}.
20 * @author <a href="mailto:bombe@freenetproject.org">David ‘Bombe’ Roden</a>
22 public class RemovePeerCommandImpl implements RemovePeerCommand {
24 private final ListeningExecutorService threadPool;
25 private final ConnectionSupplier connectionSupplier;
26 private final AtomicReference<String> nodeIdentifier = new AtomicReference<>();
28 public RemovePeerCommandImpl(ExecutorService threadPool, ConnectionSupplier connectionSupplier) {
29 this.threadPool = MoreExecutors.listeningDecorator(threadPool);
30 this.connectionSupplier = connectionSupplier;
34 public Executable<Boolean> byName(String name) {
35 nodeIdentifier.set(name);
40 public Executable<Boolean> byIdentity(String nodeIdentity) {
41 nodeIdentifier.set(nodeIdentity);
46 public Executable<Boolean> byHostAndPort(String host, int port) {
47 nodeIdentifier.set(String.format("%s:%d", host, port));
51 private ListenableFuture<Boolean> execute() {
52 return threadPool.submit(this::executeDialog);
55 private boolean executeDialog() throws IOException, ExecutionException, InterruptedException {
56 RemovePeer removePeer = new RemovePeer(new RandomIdentifierGenerator().generate(), nodeIdentifier.get());
57 try (RemovePeerDialog removePeerDialog = new RemovePeerDialog()) {
58 return removePeerDialog.send(removePeer).get();
62 private class RemovePeerDialog extends FcpDialog<Boolean> {
64 private final AtomicBoolean finished = new AtomicBoolean();
65 private final AtomicBoolean removed = new AtomicBoolean();
67 public RemovePeerDialog() throws IOException {
68 super(threadPool, connectionSupplier.get());
72 protected boolean isFinished() {
73 return finished.get() || removed.get();
77 protected Boolean getResult() {
82 protected void consumePeerRemoved(PeerRemoved peerRemoved) {
87 protected void consumeUnknownNodeIdentifier(UnknownNodeIdentifier unknownNodeIdentifier) {