import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
-import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Supplier;
import net.pterodactylus.fcp.ListPeer;
import net.pterodactylus.fcp.Peer;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
/**
* Default {@link ListPeerCommand} implementation based on {@link FcpDialog}.
private final ListeningExecutorService threadPool;
private final ConnectionSupplier connectionSupplier;
+ private final Supplier<String> identifierGenerator;
private final AtomicReference<String> nodeIdentifier = new AtomicReference<>();
- public ListPeerCommandImpl(ListeningExecutorService threadPool, ConnectionSupplier connectionSupplier) {
- this.threadPool = threadPool;
+ public ListPeerCommandImpl(ExecutorService threadPool, ConnectionSupplier connectionSupplier, Supplier<String> identifierGenerator) {
+ this.threadPool = MoreExecutors.listeningDecorator(threadPool);
this.connectionSupplier = connectionSupplier;
+ this.identifierGenerator = identifierGenerator;
}
@Override
}
private ListenableFuture<Optional<Peer>> execute() {
- return threadPool.submit(this::executeSequence);
+ return threadPool.submit(this::executeDialog);
}
- private Optional<Peer> executeSequence() throws IOException, ExecutionException, InterruptedException {
- ListPeer listPeer = new ListPeer(new RandomIdentifierGenerator().generate(), nodeIdentifier.get());
- try (ListPeerSequence listPeerSequence = new ListPeerSequence()) {
- return Optional.ofNullable(listPeerSequence.send(listPeer).get());
+ private Optional<Peer> executeDialog() throws IOException, ExecutionException, InterruptedException {
+ ListPeer listPeer = new ListPeer(identifierGenerator.get(), nodeIdentifier.get());
+ try (ListPeerDialog listPeerDialog = new ListPeerDialog()) {
+ return Optional.ofNullable(listPeerDialog.send(listPeer).get());
}
}
- private class ListPeerSequence extends FcpDialog<Peer> {
+ private class ListPeerDialog extends FcpDialog<Peer> {
- private final AtomicBoolean finished = new AtomicBoolean();
- private final AtomicReference<Peer> peer = new AtomicReference<>();
-
- public ListPeerSequence() throws IOException {
- super(threadPool, connectionSupplier.get());
- }
-
- @Override
- protected boolean isFinished() {
- return finished.get();
- }
-
- @Override
- protected Peer getResult() {
- return peer.get();
+ public ListPeerDialog() throws IOException {
+ super(threadPool, connectionSupplier.get(), null);
}
@Override
protected void consumePeer(Peer peer) {
- this.peer.set(peer);
- finished.set(true);
+ setResult(peer);
}
@Override
protected void consumeUnknownNodeIdentifier(UnknownNodeIdentifier unknownNodeIdentifier) {
- finished.set(true);
+ finish();
}
}