1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package ca.uhn.hl7v2.app;
28
29 import java.io.IOException;
30 import java.net.InetAddress;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.TimeUnit;
33
34 import ca.uhn.hl7v2.HL7Exception;
35 import ca.uhn.hl7v2.llp.LLPException;
36 import ca.uhn.hl7v2.model.Message;
37
38
39
40
41
42
43
44 public class LazyConnection implements Connection {
45
46 private final ConnectionData data;
47 private final ExecutorService executor;
48 private Connection activeConnection;
49 private final LazyInitiator initiator;
50
51 public LazyConnection(ConnectionData data, ExecutorService executor) {
52 this.data = data;
53 this.executor = executor;
54 this.initiator = new LazyInitiator(this);
55 }
56
57 public void activate() {
58 if (isEstablished()) activeConnection.activate();
59 }
60
61 public Initiator getInitiator() {
62 if (isEstablished()) return activeConnection.getInitiator();
63 return initiator;
64 }
65
66 public void close() throws IOException {
67 if (isEstablished()) {
68 activeConnection.close();
69 activeConnection = null;
70 }
71 }
72
73 public boolean isOpen() {
74 return isEstablished() && activeConnection.isOpen();
75 }
76
77 public ExecutorService getExecutorService() {
78 if (isEstablished()) return activeConnection.getExecutorService();
79 return executor;
80 }
81
82 public InetAddress getRemoteAddress() {
83 if (isEstablished())
84 return activeConnection.getRemoteAddress();
85 return null;
86 }
87
88 public Integer getRemotePort() {
89 if (isEstablished()) {
90 return activeConnection.getRemotePort();
91 }
92 return null;
93 }
94
95 boolean isEstablished() {
96 return activeConnection != null && activeConnection.isOpen();
97 }
98
99 void establishConnection() throws HL7Exception {
100 try {
101 activeConnection = ConnectionFactory.openEagerly(data, executor);
102 } catch (Exception e) {
103 throw new HL7Exception(e);
104 }
105 }
106
107
108 static class LazyInitiator implements Initiator {
109
110 private final LazyConnection connection;
111 private long timeoutMillis = 10000;
112
113 LazyInitiator(LazyConnection connection) {
114 this.connection = connection;
115 }
116
117 public synchronized Message../../ca/uhn/hl7v2/model/Message.html#Message">Message sendAndReceive(Message out) throws HL7Exception, LLPException, IOException {
118 if (!connection.isEstablished()) {
119 connection.establishConnection();
120 setTimeout(timeoutMillis, TimeUnit.MILLISECONDS);
121 }
122 return connection.getInitiator().sendAndReceive(out);
123 }
124
125 public synchronized void setTimeout(long timeout, TimeUnit timeunit) {
126 if (connection.isEstablished())
127 connection.getInitiator().setTimeout(timeout, timeunit);
128 else
129 this.timeoutMillis = timeunit.toMillis(timeout);
130 }
131
132 public void setTimeoutMillis(int timeout) {
133 setTimeout(timeout, TimeUnit.MILLISECONDS);
134 }
135 }
136
137 }