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;
8 import java.util.function.Supplier;
10 import net.pterodactylus.fcp.PeerRemoved;
11 import net.pterodactylus.fcp.RemovePeer;
12 import net.pterodactylus.fcp.UnknownNodeIdentifier;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.ListeningExecutorService;
16 import com.google.common.util.concurrent.MoreExecutors;
19 * Default {@link RemovePeerCommand} implementation based on {@link FcpDialog}.
21 * @author <a href="mailto:bombe@freenetproject.org">David ‘Bombe’ Roden</a>
23 public class RemovePeerCommandImpl implements RemovePeerCommand {
25 private final ListeningExecutorService threadPool;
26 private final ConnectionSupplier connectionSupplier;
27 private final Supplier<String> identifierGenerator;
28 private final AtomicReference<String> nodeIdentifier = new AtomicReference<>();
30 public RemovePeerCommandImpl(ExecutorService threadPool, ConnectionSupplier connectionSupplier, Supplier<String> identifierGenerator) {
31 this.threadPool = MoreExecutors.listeningDecorator(threadPool);
32 this.connectionSupplier = connectionSupplier;
33 this.identifierGenerator = identifierGenerator;
37 public Executable<Boolean> byName(String name) {
38 nodeIdentifier.set(name);
43 public Executable<Boolean> byIdentity(String nodeIdentity) {
44 nodeIdentifier.set(nodeIdentity);
49 public Executable<Boolean> byHostAndPort(String host, int port) {
50 nodeIdentifier.set(String.format("%s:%d", host, port));
54 private ListenableFuture<Boolean> execute() {
55 return threadPool.submit(this::executeDialog);
58 private boolean executeDialog() throws IOException, ExecutionException, InterruptedException {
59 RemovePeer removePeer = new RemovePeer(identifierGenerator.get(), nodeIdentifier.get());
60 try (RemovePeerDialog removePeerDialog = new RemovePeerDialog()) {
61 return removePeerDialog.send(removePeer).get();
65 private class RemovePeerDialog extends FcpDialog<Boolean> {
67 private final AtomicBoolean finished = new AtomicBoolean();
68 private final AtomicBoolean removed = new AtomicBoolean();
70 public RemovePeerDialog() throws IOException {
71 super(threadPool, connectionSupplier.get());
75 protected boolean isFinished() {
76 return finished.get() || removed.get();
80 protected Boolean getResult() {
85 protected void consumePeerRemoved(PeerRemoved peerRemoved) {
90 protected void consumeUnknownNodeIdentifier(UnknownNodeIdentifier unknownNodeIdentifier) {