Use execute() to trigger execution of commands
[jFCPlib.git] / src / main / java / net / pterodactylus / fcp / quelaton / GenerateKeypairCommandImpl.java
1 package net.pterodactylus.fcp.quelaton;
2
3 import java.io.IOException;
4 import java.util.concurrent.ExecutorService;
5 import java.util.concurrent.Future;
6 import java.util.concurrent.atomic.AtomicReference;
7
8 import net.pterodactylus.fcp.FcpKeyPair;
9 import net.pterodactylus.fcp.GenerateSSK;
10 import net.pterodactylus.fcp.SSKKeypair;
11
12 import com.google.common.util.concurrent.ListenableFuture;
13 import com.google.common.util.concurrent.ListeningExecutorService;
14 import com.google.common.util.concurrent.MoreExecutors;
15
16 /**
17  * Implementation of the {@link GenerateKeypairCommand}.
18  *
19  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
20  */
21 class GenerateKeypairCommandImpl implements GenerateKeypairCommand {
22
23         private final ListeningExecutorService threadPool;
24         private final ConnectionSupplier connectionSupplier;
25
26         GenerateKeypairCommandImpl(ExecutorService threadPool, ConnectionSupplier connectionSupplier) {
27                 this.threadPool = MoreExecutors.listeningDecorator(threadPool);
28                 this.connectionSupplier = connectionSupplier;
29         }
30
31         @Override
32         public ListenableFuture<FcpKeyPair> execute() {
33                 return threadPool.submit(() -> new FcpKeyPairReplySequence().send(new GenerateSSK()).get());
34         }
35
36         private class FcpKeyPairReplySequence extends FcpReplySequence<FcpKeyPair> {
37
38                 private AtomicReference<FcpKeyPair> keyPair = new AtomicReference<>();
39
40                 public FcpKeyPairReplySequence() throws IOException {
41                         super(GenerateKeypairCommandImpl.this.threadPool, GenerateKeypairCommandImpl.this.connectionSupplier.get());
42                 }
43
44                 @Override
45                 protected boolean isFinished() {
46                         return keyPair.get() != null;
47                 }
48
49                 @Override
50                 protected FcpKeyPair getResult() {
51                         return keyPair.get();
52                 }
53
54                 @Override
55                 protected void consumeSSKKeypair(SSKKeypair sskKeypair) {
56                         keyPair.set(new FcpKeyPair(sskKeypair.getRequestURI(), sskKeypair.getInsertURI()));
57                 }
58
59         }
60
61 }