c85f346f40a2677de8fdf5c68b908dcf1695ef8c
[jFCPlib.git] / src / test / java / net / pterodactylus / fcp / fake / TextSocket.java
1 package net.pterodactylus.fcp.fake;
2
3 import java.io.BufferedReader;
4 import java.io.Closeable;
5 import java.io.EOFException;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
9 import java.io.OutputStream;
10 import java.io.OutputStreamWriter;
11 import java.io.Writer;
12 import java.net.Socket;
13 import java.util.ArrayList;
14 import java.util.List;
15
16 import org.hamcrest.Matcher;
17
18 /**
19  * TODO
20  *
21  * @author <a href="bombe@freenetproject.org">David ‘Bombe’ Roden</a>
22  */
23 class TextSocket implements Closeable {
24
25         private final Socket socket;
26         private final InputStream socketInput;
27         private final OutputStream socketOutput;
28         private final BufferedReader inputReader;
29         private final Writer outputWriter;
30
31         TextSocket(Socket socket) throws IOException {
32                 this.socket = socket;
33                 this.socketInput = socket.getInputStream();
34                 this.socketOutput = socket.getOutputStream();
35                 this.inputReader = new BufferedReader(new InputStreamReader(socketInput, "UTF-8"));
36                 this.outputWriter = new OutputStreamWriter(socketOutput, "UTF-8");
37         }
38
39         public String readLine() throws IOException {
40                 return inputReader.readLine();
41         }
42
43         public void writeLine(String line) throws IOException {
44                 outputWriter.write(line + "\n");
45                 outputWriter.flush();
46         }
47
48         public List<String> collectUntil(Matcher<String> lineMatcher) throws IOException {
49                 List<String> collectedLines = new ArrayList<String>();
50                 while (true) {
51                         String line = readLine();
52                         if (line == null) {
53                                 throw new EOFException();
54                         }
55                         collectedLines.add(line);
56                         if (lineMatcher.matches(line)) {
57                                 break;
58                         }
59                 }
60                 return collectedLines;
61         }
62
63         @Override
64         public void close() throws IOException {
65                 outputWriter.close();
66                 inputReader.close();
67                 socketOutput.close();
68                 socketInput.close();
69                 socket.close();
70         }
71
72 }