1 | |
|
2 | |
|
3 | |
|
4 | |
package ca.uhn.hl7v2.protocol.impl; |
5 | |
|
6 | |
import java.io.IOException; |
7 | |
import java.io.InputStream; |
8 | |
import java.io.OutputStream; |
9 | |
import java.net.Socket; |
10 | |
|
11 | |
import ca.uhn.hl7v2.protocol.StreamSource; |
12 | |
import ca.uhn.hl7v2.protocol.TransportException; |
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
|
19 | |
|
20 | 65 | public abstract class SocketStreamSource implements StreamSource { |
21 | |
|
22 | |
|
23 | |
|
24 | |
|
25 | |
|
26 | |
public abstract Socket getSocket(); |
27 | |
|
28 | |
|
29 | |
|
30 | |
|
31 | |
|
32 | |
public abstract void connect() throws TransportException; |
33 | |
|
34 | |
|
35 | |
|
36 | |
|
37 | |
|
38 | |
public void disconnect() throws TransportException { |
39 | |
try { |
40 | 35 | if (isConnected()) { |
41 | 0 | getOutboundStream().close(); |
42 | 0 | getInboundStream().close(); |
43 | 0 | getSocket().close(); |
44 | |
} |
45 | 0 | } catch (IOException e) { |
46 | 0 | throw new TransportException(e); |
47 | 35 | } |
48 | 35 | } |
49 | |
|
50 | |
|
51 | |
|
52 | |
|
53 | |
public OutputStream getOutboundStream() throws TransportException { |
54 | 65 | checkConnected(); |
55 | |
try { |
56 | 55 | return getSocket().getOutputStream(); |
57 | 0 | } catch (IOException e) { |
58 | 0 | throw new TransportException(e); |
59 | |
} |
60 | |
} |
61 | |
|
62 | |
private void checkConnected() throws TransportException { |
63 | 130 | if (!isConnected()) { |
64 | 20 | throw new TransportException("The socket is not connected"); |
65 | |
} |
66 | 110 | } |
67 | |
|
68 | |
private boolean isConnected() { |
69 | 165 | boolean is = false; |
70 | 165 | if (getSocket() != null && getSocket().isConnected() && !getSocket().isClosed()) { |
71 | 110 | is = true; |
72 | |
} |
73 | 165 | return is; |
74 | |
} |
75 | |
|
76 | |
|
77 | |
|
78 | |
|
79 | |
public InputStream getInboundStream() throws TransportException { |
80 | 65 | checkConnected(); |
81 | |
try { |
82 | 55 | return getSocket().getInputStream(); |
83 | 0 | } catch (IOException e) { |
84 | 0 | throw new TransportException(e); |
85 | |
} |
86 | |
} |
87 | |
|
88 | |
} |