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.EndListPeerNotes;
11 import net.pterodactylus.fcp.ListPeerNotes;
12 import net.pterodactylus.fcp.PeerNote;
13 import net.pterodactylus.fcp.UnknownNodeIdentifier;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.ListeningExecutorService;
17 import com.google.common.util.concurrent.MoreExecutors;
20 * Default {@link ListPeerNotesCommand} implementation based on {@link FcpDialog}.
22 * @author <a href="mailto:bombe@freenetproject.org">David ‘Bombe’ Roden</a>
24 public class ListPeerNotesCommandImpl implements ListPeerNotesCommand {
26 private final ListeningExecutorService threadPool;
27 private final ConnectionSupplier connectionSupplier;
28 private final Supplier<String> identifierGenerator;
29 private final AtomicReference<String> nodeIdentifier = new AtomicReference<>();
31 public ListPeerNotesCommandImpl(ExecutorService threadPool, ConnectionSupplier connectionSupplier, Supplier<String> identifierGenerator) {
32 this.threadPool = MoreExecutors.listeningDecorator(threadPool);
33 this.connectionSupplier = connectionSupplier;
34 this.identifierGenerator = identifierGenerator;
38 public Executable<Optional<PeerNote>> byName(String name) {
39 nodeIdentifier.set(name);
44 public Executable<Optional<PeerNote>> byIdentity(String identity) {
45 nodeIdentifier.set(identity);
50 public Executable<Optional<PeerNote>> byHostAndPort(String host, int port) {
51 nodeIdentifier.set(String.format("%s:%d", host, port));
55 private ListenableFuture<Optional<PeerNote>> execute() {
56 return threadPool.submit(this::executeDialog);
59 private Optional<PeerNote> executeDialog() throws IOException, ExecutionException, InterruptedException {
60 ListPeerNotes listPeerNotes = new ListPeerNotes(identifierGenerator.get(), nodeIdentifier.get());
61 try (ListPeerNotesDialog listPeerNotesDialog = new ListPeerNotesDialog()) {
62 return listPeerNotesDialog.send(listPeerNotes).get();
66 private class ListPeerNotesDialog extends FcpDialog<Optional<PeerNote>> {
68 public ListPeerNotesDialog() throws IOException {
69 super(threadPool, connectionSupplier.get(), Optional.<PeerNote>empty());
73 protected void consumePeerNote(PeerNote peerNote) {
74 setResult(Optional.ofNullable(peerNote));
78 protected void consumeEndListPeerNotes(EndListPeerNotes endListPeerNotes) {
83 protected void consumeUnknownNodeIdentifier(UnknownNodeIdentifier unknownNodeIdentifier) {