1 package net.pterodactylus.fcp.quelaton;
3 import java.io.IOException;
4 import java.util.Optional;
5 import java.util.concurrent.ExecutionException;
6 import java.util.concurrent.ExecutorService;
7 import java.util.concurrent.atomic.AtomicReference;
8 import java.util.function.Supplier;
10 import net.pterodactylus.fcp.ListPeer;
11 import net.pterodactylus.fcp.Peer;
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 ListPeerCommand} implementation based on {@link FcpDialog}.
21 * @author <a href="mailto:bombe@freenetproject.org">David ‘Bombe’ Roden</a>
23 public class ListPeerCommandImpl implements ListPeerCommand {
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 ListPeerCommandImpl(ExecutorService threadPool, ConnectionSupplier connectionSupplier, Supplier<String> identifierGenerator) {
31 this.threadPool = MoreExecutors.listeningDecorator(threadPool);
32 this.connectionSupplier = connectionSupplier;
33 this.identifierGenerator = identifierGenerator;
37 public Executable<Optional<Peer>> byName(String name) {
38 nodeIdentifier.set(name);
43 public Executable<Optional<Peer>> byIdentity(String identity) {
44 nodeIdentifier.set(identity);
49 public Executable<Optional<Peer>> byHostAndPort(String host, int port) {
50 nodeIdentifier.set(String.format("%s:%d", host, port));
54 private ListenableFuture<Optional<Peer>> execute() {
55 return threadPool.submit(this::executeDialog);
58 private Optional<Peer> executeDialog() throws IOException, ExecutionException, InterruptedException {
59 ListPeer listPeer = new ListPeer(identifierGenerator.get(), nodeIdentifier.get());
60 try (ListPeerDialog listPeerDialog = new ListPeerDialog()) {
61 return Optional.ofNullable(listPeerDialog.send(listPeer).get());
65 private class ListPeerDialog extends FcpDialog<Peer> {
67 public ListPeerDialog() throws IOException {
68 super(threadPool, connectionSupplier.get(), null);
72 protected void consumePeer(Peer peer) {
77 protected void consumeUnknownNodeIdentifier(UnknownNodeIdentifier unknownNodeIdentifier) {