1 package net.pterodactylus.fcp.quelaton;
4 import java.io.IOException;
5 import java.util.Optional;
6 import java.util.concurrent.ExecutionException;
7 import java.util.concurrent.ExecutorService;
8 import java.util.concurrent.atomic.AtomicBoolean;
9 import java.util.concurrent.atomic.AtomicReference;
11 import net.pterodactylus.fcp.AddPeer;
12 import net.pterodactylus.fcp.Peer;
13 import net.pterodactylus.fcp.ProtocolError;
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 AddPeerCommand} implementation based on {@link FcpReplySequence}.
22 * @author <a href="mailto:bombe@freenetproject.org">David ‘Bombe’ Roden</a>
24 public class AddPeerCommandImpl implements AddPeerCommand {
26 private final ListeningExecutorService threadPool;
27 private final ConnectionSupplier connectionSupplier;
28 private final AtomicReference<File> file = new AtomicReference<>();
30 public AddPeerCommandImpl(ExecutorService threadPool, ConnectionSupplier connectionSupplier) {
31 this.threadPool = MoreExecutors.listeningDecorator(threadPool);
32 this.connectionSupplier = connectionSupplier;
36 public Executable<Optional<Peer>> withFile(File file) {
41 private ListenableFuture<Optional<Peer>> execute() {
42 return threadPool.submit(this::executeSequence);
45 private Optional<Peer> executeSequence() throws IOException, ExecutionException, InterruptedException {
46 AddPeer addPeer = null;
47 if (file.get() != null) {
48 addPeer = new AddPeer(new RandomIdentifierGenerator().generate(), file.get().getPath());
50 try (AddPeerSequence addPeerSequence = new AddPeerSequence()) {
51 return addPeerSequence.send(addPeer).get();
55 private class AddPeerSequence extends FcpReplySequence<Optional<Peer>> {
57 private final AtomicBoolean finished = new AtomicBoolean();
58 private final AtomicReference<Peer> peer = new AtomicReference<>();
60 public AddPeerSequence() throws IOException {
61 super(threadPool, connectionSupplier.get());
65 protected boolean isFinished() {
66 return finished.get();
70 protected Optional<Peer> getResult() {
71 return Optional.ofNullable(peer.get());
75 protected void consumePeer(Peer peer) {
81 protected void consumeProtocolError(ProtocolError protocolError) {