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