1 package net.pterodactylus.fcp.quelaton;
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 import java.util.function.Supplier;
9 import net.pterodactylus.fcp.FcpConnection;
11 import com.google.common.util.concurrent.ListeningExecutorService;
12 import com.google.common.util.concurrent.MoreExecutors;
15 * Default {@link FcpClient} implementation.
17 * @author <a href="bombe@freenetproject.org">David ‘Bombe’ Roden</a>
19 public class DefaultFcpClient implements FcpClient {
21 private final ListeningExecutorService threadPool;
22 private final String hostname;
23 private final int port;
24 private final AtomicReference<FcpConnection> fcpConnection = new AtomicReference<>();
25 private final Supplier<String> clientName;
27 public DefaultFcpClient(ExecutorService threadPool, String hostname, int port, Supplier<String> clientName) {
28 this.threadPool = MoreExecutors.listeningDecorator(threadPool);
29 this.hostname = hostname;
31 this.clientName = clientName;
34 private FcpConnection connect() throws IOException {
35 FcpConnection fcpConnection = this.fcpConnection.get();
36 if (fcpConnection != null) {
39 fcpConnection = createConnection();
40 this.fcpConnection.compareAndSet(null, fcpConnection);
44 private FcpConnection createConnection() throws IOException {
46 return new ClientHelloImpl(threadPool, hostname, port).withName(clientName.get()).execute().get();
47 } catch (InterruptedException | ExecutionException e) {
48 throw new IOException(e);
53 public GetNodeCommand getNode() {
54 return new GetNodeCommandImpl(threadPool, this::connect);
58 public GenerateKeypairCommand generateKeypair() {
59 return new GenerateKeypairCommandImpl(threadPool, this::connect);
63 public ClientGetCommand clientGet() {
64 return new ClientGetCommandImpl(threadPool, this::connect);
68 public ClientPutCommand clientPut() {
69 return new ClientPutCommandImpl(threadPool, this::connect);
73 public ListPeersCommand listPeers() {
74 return new ListPeersCommandImpl(threadPool, this::connect);