28766619f67316e727aabe1b381d93068cc15cb9
[jFCPlib.git] / src / main / java / net / pterodactylus / fcp / quelaton / GetConfigCommandImpl.java
1 package net.pterodactylus.fcp.quelaton;
2
3 import java.io.IOException;
4 import java.util.concurrent.ExecutionException;
5 import java.util.concurrent.ExecutorService;
6 import java.util.concurrent.atomic.AtomicReference;
7
8 import net.pterodactylus.fcp.ConfigData;
9 import net.pterodactylus.fcp.GetConfig;
10
11 import com.google.common.util.concurrent.ListenableFuture;
12 import com.google.common.util.concurrent.ListeningExecutorService;
13 import com.google.common.util.concurrent.MoreExecutors;
14
15 /**
16  * Default {@link GetConfigCommand} implementation based on {@link FcpDialog}.
17  *
18  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
19  */
20 public class GetConfigCommandImpl implements GetConfigCommand {
21
22         private final ListeningExecutorService threadPool;
23         private final ConnectionSupplier connectionSupplier;
24
25         public GetConfigCommandImpl(ExecutorService threadPool, ConnectionSupplier connectionSupplier) {
26                 this.threadPool = MoreExecutors.listeningDecorator(threadPool);
27                 this.connectionSupplier = connectionSupplier;
28         }
29
30         @Override
31         public ListenableFuture<ConfigData> execute() {
32                 return threadPool.submit(this::executeDialog);
33         }
34
35         private ConfigData executeDialog() throws IOException, ExecutionException, InterruptedException {
36                 GetConfig getConfig = new GetConfig(new RandomIdentifierGenerator().generate());
37                 try (GetConfigDialog getConfigDialog = new GetConfigDialog()) {
38                         return getConfigDialog.send(getConfig).get();
39                 }
40         }
41
42         private class GetConfigDialog extends FcpDialog<ConfigData> {
43
44                 private final AtomicReference<ConfigData> configData = new AtomicReference<>();
45
46                 public GetConfigDialog() throws IOException {
47                         super(threadPool, connectionSupplier.get());
48                 }
49
50                 @Override
51                 protected boolean isFinished() {
52                         return configData.get() != null;
53                 }
54
55                 @Override
56                 protected ConfigData getResult() {
57                         return configData.get();
58                 }
59
60                 @Override
61                 protected void consumeConfigData(ConfigData configData) {
62                         this.configData.set(configData);
63                 }
64
65         }
66
67 }