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.AtomicBoolean;
8 import java.util.concurrent.atomic.AtomicReference;
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 AtomicReference<String> nodeIdentifier = new AtomicReference<>();
30 public ListPeerNotesCommandImpl(ExecutorService threadPool, ConnectionSupplier connectionSupplier) {
31 this.threadPool = MoreExecutors.listeningDecorator(threadPool);
32 this.connectionSupplier = connectionSupplier;
36 public Executable<Optional<PeerNote>> byName(String name) {
37 nodeIdentifier.set(name);
42 public Executable<Optional<PeerNote>> byIdentity(String identity) {
43 nodeIdentifier.set(identity);
48 public Executable<Optional<PeerNote>> byHostAndPort(String host, int port) {
49 nodeIdentifier.set(String.format("%s:%d", host, port));
53 private ListenableFuture<Optional<PeerNote>> execute() {
54 return threadPool.submit(this::executeSequence);
57 private Optional<PeerNote> executeSequence() throws IOException, ExecutionException, InterruptedException {
58 ListPeerNotes listPeerNotes =
59 new ListPeerNotes(new RandomIdentifierGenerator().generate(), nodeIdentifier.get());
60 try (ListPeerNotesDialog listPeerNotesDialog = new ListPeerNotesDialog()) {
61 return listPeerNotesDialog.send(listPeerNotes).get();
65 private class ListPeerNotesDialog extends FcpDialog<Optional<PeerNote>> {
67 private final AtomicReference<PeerNote> peerNote = new AtomicReference<>();
68 private final AtomicBoolean finished = new AtomicBoolean();
70 public ListPeerNotesDialog() throws IOException {
71 super(threadPool, connectionSupplier.get());
75 protected boolean isFinished() {
76 return finished.get();
80 protected Optional<PeerNote> getResult() {
81 return Optional.ofNullable(peerNote.get());
85 protected void consumePeerNote(PeerNote peerNote) {
86 this.peerNote.set(peerNote);
90 protected void consumeEndListPeerNotes(EndListPeerNotes endListPeerNotes) {
95 protected void consumeUnknownNodeIdentifier(UnknownNodeIdentifier unknownNodeIdentifier) {