1 package au.gov.amsa.util.nmea;
2
3 import java.io.IOException;
4 import java.net.Socket;
5 import java.net.UnknownHostException;
6
7 import org.apache.log4j.Logger;
8
9 import au.gov.amsa.ais.rx.Streams;
10
11 import com.google.common.annotations.VisibleForTesting;
12
13
14
15
16
17
18
19 public class NmeaReaderFromSocket implements NmeaReader {
20
21 private static Logger log = Logger.getLogger(NmeaReaderFromSocket.class);
22 private final Socket socket;
23
24
25
26
27
28
29
30 public NmeaReaderFromSocket(String host, int port) {
31 this(createSocket(host, port));
32 }
33
34 private static Socket createSocket(String host, int port) {
35 try {
36 return new Socket(host, port);
37 } catch (UnknownHostException e) {
38 throw new RuntimeException(e);
39 } catch (IOException e) {
40 throw new RuntimeException(e);
41 }
42 }
43
44 @VisibleForTesting
45 NmeaReaderFromSocket(Socket socket) {
46 this.socket = socket;
47 }
48
49 @Override
50 public Iterable<String> read() {
51 try {
52 return Streams.nmeaFrom(socket.getInputStream()).toBlocking()
53 .toIterable();
54 } catch (IOException e) {
55 throw new RuntimeException(e);
56 }
57 }
58
59 public void close() {
60 if (socket != null)
61 try {
62 socket.close();
63 } catch (IOException e) {
64 log.warn(e.getMessage(), e);
65 }
66 }
67 }