Close fake server successfully when it was not used
[jFCPlib.git] / src / test / java / net / pterodactylus / fcp / fake / FakeTcpServer.java
index 07afb24..c8edbbe 100644 (file)
@@ -3,7 +3,6 @@ package net.pterodactylus.fcp.fake;
 import java.io.IOException;
 import java.net.ServerSocket;
 import java.util.List;
-import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Future;
 import java.util.concurrent.atomic.AtomicReference;
@@ -15,7 +14,7 @@ import org.hamcrest.Matcher;
  *
  * @author <a href="bombe@freenetproject.org">David ‘Bombe’ Roden</a>
  */
-public class FakeTcpServer {
+public class FakeTcpServer implements AutoCloseable {
 
        private final ServerSocket serverSocket;
        private final ExecutorService executorService;
@@ -31,12 +30,9 @@ public class FakeTcpServer {
        }
 
        public Future<?> connect() throws IOException {
-               return executorService.submit(new Callable<Void>() {
-                       @Override
-                       public Void call() throws Exception {
-                               clientSocket.set(new TextSocket(serverSocket.accept()));
-                               return null;
-                       }
+               return executorService.submit(() -> {
+                       clientSocket.set(new TextSocket(serverSocket.accept()));
+                       return null;
                });
        }
 
@@ -44,12 +40,22 @@ public class FakeTcpServer {
                return clientSocket.get().collectUntil(lineMatcher);
        }
 
-       public void writeLine(String line) throws IOException {
-               clientSocket.get().writeLine(line);
+       public void writeLine(String... lines) throws IOException {
+               for (String line : lines) {
+                       clientSocket.get().writeLine(line);
+               }
        }
 
        public String readLine() throws IOException {
                return clientSocket.get().readLine();
        }
 
+       @Override
+       public void close() throws IOException {
+               TextSocket textSocket = clientSocket.get();
+               if (textSocket != null) {
+                       textSocket.close();
+               }
+       }
+
 }