Add ListPeers command
[jFCPlib.git] / src / main / java / net / pterodactylus / fcp / quelaton / ListPeersCommandImpl.java
1 package net.pterodactylus.fcp.quelaton;
2
3 import java.io.IOException;
4 import java.util.Collection;
5 import java.util.HashSet;
6 import java.util.concurrent.ExecutorService;
7 import java.util.concurrent.Future;
8 import java.util.concurrent.atomic.AtomicBoolean;
9
10 import net.pterodactylus.fcp.EndListPeers;
11 import net.pterodactylus.fcp.ListPeers;
12 import net.pterodactylus.fcp.Peer;
13
14 import com.google.common.util.concurrent.ListeningExecutorService;
15 import com.google.common.util.concurrent.MoreExecutors;
16
17 /**
18  * Default {@link ListPeersCommand} implementation based on {@link FcpReplySequence}.
19  *
20  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
21  */
22 public class ListPeersCommandImpl implements ListPeersCommand {
23
24         private final ListeningExecutorService threadPool;
25         private final ConnectionSupplier connectionSupplier;
26
27         public ListPeersCommandImpl(ExecutorService threadPool, ConnectionSupplier connectionSupplier) {
28                 this.threadPool = MoreExecutors.listeningDecorator(threadPool);
29                 this.connectionSupplier = connectionSupplier;
30         }
31
32         @Override
33         public Future<Collection<Peer>> execute() {
34                 String identifier = new RandomIdentifierGenerator().generate();
35                 ListPeers listPeers = new ListPeers(identifier);
36                 return threadPool.submit(() -> new ListPeersReplySequence().send(listPeers).get());
37         }
38
39         private class ListPeersReplySequence extends FcpReplySequence<Collection<Peer>> {
40
41                 private final Collection<Peer> peers = new HashSet<>();
42                 private final AtomicBoolean finished = new AtomicBoolean(false);
43
44                 public ListPeersReplySequence() throws IOException {
45                         super(threadPool, connectionSupplier.get());
46                 }
47
48                 @Override
49                 protected boolean isFinished() {
50                         return finished.get();
51                 }
52
53                 @Override
54                 protected Collection<Peer> getResult() {
55                         return peers;
56                 }
57
58                 @Override
59                 protected void consumePeer(Peer peer) {
60                         peers.add(peer);
61                 }
62
63                 @Override
64                 protected void consumeEndListPeers(EndListPeers endListPeers) {
65                         finished.set(true);
66                 }
67
68         }
69
70 }