Add close() method, implement AutoCloseable
[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(new Callable<Void>() {
35                         @Override
36                         public Void call() throws Exception {
37                                 clientSocket.set(new TextSocket(serverSocket.accept()));
38                                 return null;
39                         }
40                 });
41         }
42
43         public List<String> collectUntil(Matcher<String> lineMatcher) throws IOException {
44                 return clientSocket.get().collectUntil(lineMatcher);
45         }
46
47         public void writeLine(String line) throws IOException {
48                 clientSocket.get().writeLine(line);
49         }
50
51         public String readLine() throws IOException {
52                 return clientSocket.get().readLine();
53         }
54
55         @Override
56         public void close() throws IOException {
57                 clientSocket.get().close();
58         }
59
60 }