67a1fdcd6e0df73a7663606ca6e4951eba5e804b
[jFCPlib.git] / src / test / java / net / pterodactylus / fcp / fake / FakeTcpServer.java
1 package net.pterodactylus.fcp.fake;
2
3 import java.io.IOException;
4 import java.net.ServerSocket;
5 import java.util.List;
6 import java.util.concurrent.Callable;
7 import java.util.concurrent.ExecutorService;
8 import java.util.concurrent.Future;
9 import java.util.concurrent.atomic.AtomicReference;
10
11 import org.hamcrest.Matcher;
12
13 /**
14  * TODO
15  *
16  * @author <a href="bombe@freenetproject.org">David ‘Bombe’ Roden</a>
17  */
18 public class FakeTcpServer implements AutoCloseable {
19
20         private final ServerSocket serverSocket;
21         private final ExecutorService executorService;
22         private final AtomicReference<TextSocket> clientSocket = new AtomicReference<>();
23
24         public FakeTcpServer(ExecutorService executorService) throws IOException {
25                 this.executorService = executorService;
26                 this.serverSocket = new ServerSocket(0);
27         }
28
29         public int getPort() {
30                 return serverSocket.getLocalPort();
31         }
32
33         public Future<?> connect() throws IOException {
34                 return executorService.submit(() -> {
35                         clientSocket.set(new TextSocket(serverSocket.accept()));
36                         return null;
37                 });
38         }
39
40         public List<String> collectUntil(Matcher<String> lineMatcher) throws IOException {
41                 return clientSocket.get().collectUntil(lineMatcher);
42         }
43
44         public void writeLine(String... lines) throws IOException {
45                 for (String line : lines) {
46                         clientSocket.get().writeLine(line);
47                 }
48         }
49
50         public String readLine() throws IOException {
51                 return clientSocket.get().readLine();
52         }
53
54         @Override
55         public void close() throws IOException {
56                 clientSocket.get().close();
57         }
58
59 }