1 | package com.framsticks.communication; |
---|
2 | |
---|
3 | import com.framsticks.params.annotations.AutoAppendAnnotation; |
---|
4 | import com.framsticks.params.annotations.FramsClassAnnotation; |
---|
5 | import com.framsticks.params.annotations.ParamAnnotation; |
---|
6 | import com.framsticks.util.FramsticksException; |
---|
7 | import com.framsticks.util.io.Encoding; |
---|
8 | import com.framsticks.util.lang.Strings; |
---|
9 | |
---|
10 | import org.apache.log4j.Level; |
---|
11 | import org.apache.log4j.Logger; |
---|
12 | import java.io.BufferedReader; |
---|
13 | import java.io.IOException; |
---|
14 | import java.io.InputStreamReader; |
---|
15 | import java.io.OutputStreamWriter; |
---|
16 | import java.io.PrintWriter; |
---|
17 | import java.net.Socket; |
---|
18 | import java.net.SocketTimeoutException; |
---|
19 | import java.util.Collection; |
---|
20 | import java.util.HashSet; |
---|
21 | import java.util.Set; |
---|
22 | |
---|
23 | import com.framsticks.util.dispatching.AbstractJoinable; |
---|
24 | import com.framsticks.util.dispatching.Dispatching; |
---|
25 | import com.framsticks.util.dispatching.Joinable; |
---|
26 | import com.framsticks.util.dispatching.JoinableCollection; |
---|
27 | import com.framsticks.util.dispatching.JoinableParent; |
---|
28 | import com.framsticks.util.dispatching.JoinableState; |
---|
29 | import com.framsticks.util.dispatching.RunAt; |
---|
30 | import com.framsticks.util.dispatching.Thread; |
---|
31 | import com.framsticks.util.dispatching.ThrowExceptionHandler; |
---|
32 | |
---|
33 | @FramsClassAnnotation |
---|
34 | public abstract class Connection extends AbstractJoinable implements JoinableParent { |
---|
35 | |
---|
36 | protected final static Logger log = Logger.getLogger(Connection.class); |
---|
37 | |
---|
38 | private PrintWriter output = null; |
---|
39 | private BufferedReader input = null; |
---|
40 | |
---|
41 | protected Socket socket = null; |
---|
42 | |
---|
43 | protected Address address; |
---|
44 | protected String description = "connection"; |
---|
45 | |
---|
46 | protected final Thread<Connection> senderThread = new Thread<>(); |
---|
47 | protected final Thread<Connection> receiverThread = new Thread<>(); |
---|
48 | protected final JoinableCollection<Thread<Connection>> threads = new JoinableCollection<>(); |
---|
49 | protected final Set<ConnectionListener> listeners = new HashSet<>(); |
---|
50 | |
---|
51 | /** |
---|
52 | * |
---|
53 | */ |
---|
54 | public Connection() { |
---|
55 | threads.add(senderThread); |
---|
56 | threads.add(receiverThread); |
---|
57 | |
---|
58 | } |
---|
59 | |
---|
60 | protected void updateNames() { |
---|
61 | if (address == null) { |
---|
62 | return; |
---|
63 | } |
---|
64 | senderThread.setName(description + " thread " + address + " sender"); |
---|
65 | receiverThread.setName(description + " thread " + address + " receiver"); |
---|
66 | threads.setObservableName(address + " connection threads"); |
---|
67 | } |
---|
68 | |
---|
69 | public void setDescription(String description) { |
---|
70 | this.description = description; |
---|
71 | updateNames(); |
---|
72 | } |
---|
73 | |
---|
74 | @AutoAppendAnnotation |
---|
75 | public Connection setAddress(Address address) { |
---|
76 | this.address = address; |
---|
77 | updateNames(); |
---|
78 | return this; |
---|
79 | } |
---|
80 | |
---|
81 | @ParamAnnotation |
---|
82 | public Connection setAddress(String address) { |
---|
83 | return setAddress(new Address(address)); |
---|
84 | } |
---|
85 | |
---|
86 | public synchronized boolean isConnected() { |
---|
87 | return socket != null && socket.isConnected(); |
---|
88 | } |
---|
89 | |
---|
90 | static final int BUFFER_LENGTH = 1024; |
---|
91 | |
---|
92 | int readChars = 0; |
---|
93 | int iterator = 0; |
---|
94 | int bufferStart = 0; |
---|
95 | final char[] readBuffer = new char[BUFFER_LENGTH]; |
---|
96 | |
---|
97 | protected String getLine() { |
---|
98 | final StringBuilder lineBuffer = new StringBuilder(); |
---|
99 | try { |
---|
100 | while (!Thread.interrupted()) { |
---|
101 | while (iterator < readChars) { |
---|
102 | if (readBuffer[iterator] != '\n') { |
---|
103 | ++iterator; |
---|
104 | continue; |
---|
105 | } |
---|
106 | /** Do not append new line. */ |
---|
107 | lineBuffer.append(readBuffer, bufferStart, iterator - bufferStart); |
---|
108 | ++iterator; |
---|
109 | bufferStart = iterator; |
---|
110 | String line = lineBuffer.toString(); |
---|
111 | |
---|
112 | synchronized (listeners) { |
---|
113 | for (ConnectionListener l : listeners) { |
---|
114 | l.connectionIncomming(line); |
---|
115 | } |
---|
116 | } |
---|
117 | |
---|
118 | return line; |
---|
119 | } |
---|
120 | final int length = readChars - bufferStart; |
---|
121 | if (length > 0) { |
---|
122 | assert bufferStart >= 0 && bufferStart < BUFFER_LENGTH; |
---|
123 | assert bufferStart + length <= BUFFER_LENGTH; |
---|
124 | lineBuffer.append(readBuffer, bufferStart, length); |
---|
125 | } |
---|
126 | |
---|
127 | readChars = 0; |
---|
128 | while (readChars == 0) { |
---|
129 | try { |
---|
130 | readChars = input.read(readBuffer); |
---|
131 | } catch (SocketTimeoutException ignored) { |
---|
132 | //timeout - continue |
---|
133 | } |
---|
134 | } |
---|
135 | iterator = 0; |
---|
136 | bufferStart = 0; |
---|
137 | } |
---|
138 | throw new InterruptedException(); |
---|
139 | } catch (Exception e) { |
---|
140 | throw new FramsticksException().msg("failed to read line").cause(e); |
---|
141 | } |
---|
142 | } |
---|
143 | |
---|
144 | protected void putLine(String line) { |
---|
145 | synchronized (listeners) { |
---|
146 | for (ConnectionListener l : listeners) { |
---|
147 | l.connectionOutgoing(line); |
---|
148 | } |
---|
149 | } |
---|
150 | output.println(line); |
---|
151 | } |
---|
152 | |
---|
153 | protected void flushOut() { |
---|
154 | output.flush(); |
---|
155 | } |
---|
156 | |
---|
157 | protected abstract void processNextInputBatch(); |
---|
158 | |
---|
159 | protected final void processInputBatchesUntilClosed() { |
---|
160 | while (isRunning() && isConnected()) { |
---|
161 | try { |
---|
162 | processNextInputBatch(); |
---|
163 | } catch (Exception e) { |
---|
164 | log.log(isRunning() ? Level.ERROR : Level.DEBUG, "caught exception: ", e); |
---|
165 | break; |
---|
166 | } |
---|
167 | } |
---|
168 | } |
---|
169 | |
---|
170 | protected abstract void receiverThreadRoutine(); |
---|
171 | |
---|
172 | // @SuppressWarnings("NN_NAKED_NOTIFY") |
---|
173 | protected void setupStreams() { |
---|
174 | try { |
---|
175 | output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Encoding.getFramsticksCharset()), true); |
---|
176 | input = new BufferedReader(new InputStreamReader(socket.getInputStream(), Encoding.getFramsticksCharset())); |
---|
177 | synchronized (this) { |
---|
178 | this.notifyAll(); |
---|
179 | } |
---|
180 | } catch (IOException e) { |
---|
181 | throw new FramsticksException().msg("failed to setup streams").cause(e).arg("connection", this); |
---|
182 | } |
---|
183 | } |
---|
184 | |
---|
185 | |
---|
186 | |
---|
187 | @Override |
---|
188 | protected void joinableFinish() { |
---|
189 | try { |
---|
190 | if (output != null) { |
---|
191 | output.close(); |
---|
192 | output = null; |
---|
193 | } |
---|
194 | |
---|
195 | if (input != null) { |
---|
196 | input.close(); |
---|
197 | input = null; |
---|
198 | } |
---|
199 | |
---|
200 | |
---|
201 | if (socket != null) { |
---|
202 | socket.close(); |
---|
203 | socket = null; |
---|
204 | } |
---|
205 | } catch (Exception e) { |
---|
206 | log.error("failed to stop connection: ", e); |
---|
207 | } |
---|
208 | log.debug("connection closed"); |
---|
209 | } |
---|
210 | |
---|
211 | @Override |
---|
212 | public void childChangedState(Joinable joinable, JoinableState state) { |
---|
213 | proceedToState(state); |
---|
214 | } |
---|
215 | |
---|
216 | @Override |
---|
217 | public String getName() { |
---|
218 | return address != null ? description + " " + address : description; |
---|
219 | } |
---|
220 | |
---|
221 | @Override |
---|
222 | protected void joinableStart() { |
---|
223 | Dispatching.use(threads, this); |
---|
224 | |
---|
225 | senderThread.dispatch(new RunAt<Connection>(ThrowExceptionHandler.getInstance()) { |
---|
226 | @Override |
---|
227 | protected void runAt() { |
---|
228 | synchronized (Connection.this) { |
---|
229 | while (state.equals(JoinableState.RUNNING) && output == null) { |
---|
230 | Dispatching.wait(Connection.this, 500); |
---|
231 | } |
---|
232 | } |
---|
233 | } |
---|
234 | }); |
---|
235 | |
---|
236 | receiverThread.dispatch(new RunAt<Connection>(ThrowExceptionHandler.getInstance()) { |
---|
237 | @Override |
---|
238 | protected void runAt() { |
---|
239 | receiverThreadRoutine(); |
---|
240 | interrupt(); |
---|
241 | finish(); |
---|
242 | } |
---|
243 | }); |
---|
244 | } |
---|
245 | |
---|
246 | @Override |
---|
247 | protected void joinableInterrupt() { |
---|
248 | Dispatching.drop(threads, this); |
---|
249 | finish(); |
---|
250 | } |
---|
251 | |
---|
252 | |
---|
253 | @Override |
---|
254 | protected void joinableJoin() throws InterruptedException { |
---|
255 | Dispatching.join(threads); |
---|
256 | } |
---|
257 | |
---|
258 | protected static void startClientConnection(Connection connection) { |
---|
259 | while (connection.isRunning() && !connection.isConnected()) { |
---|
260 | log.debug("connecting to " + connection.address); |
---|
261 | try { |
---|
262 | connection.socket = new Socket(connection.getAddressObject().getHostName(), connection.getAddressObject().getPort()); |
---|
263 | } catch (IOException e) { |
---|
264 | log.info(connection + " failed to connect (retrying): " + e); |
---|
265 | Dispatching.sleep(0.5); |
---|
266 | } |
---|
267 | } |
---|
268 | |
---|
269 | log.debug(connection + " connected"); |
---|
270 | try { |
---|
271 | connection.socket.setSoTimeout(500); |
---|
272 | connection.setupStreams(); |
---|
273 | } catch (Exception e) { |
---|
274 | throw new FramsticksException().msg("failed to initialize socket").cause(e).arg("connection", connection); |
---|
275 | } |
---|
276 | } |
---|
277 | |
---|
278 | /** |
---|
279 | * @return the address |
---|
280 | */ |
---|
281 | @ParamAnnotation |
---|
282 | public String getAddress() { |
---|
283 | return Strings.toStringNullProof(address, "?"); |
---|
284 | } |
---|
285 | |
---|
286 | public Address getAddressObject() { |
---|
287 | return address; |
---|
288 | } |
---|
289 | |
---|
290 | |
---|
291 | /** |
---|
292 | * @return the listeners |
---|
293 | */ |
---|
294 | public Collection<ConnectionListener> getListeners() { |
---|
295 | return listeners; |
---|
296 | } |
---|
297 | |
---|
298 | public static <T extends Connection> T to(T connection, Address address) { |
---|
299 | connection.setAddress(address); |
---|
300 | return connection; |
---|
301 | } |
---|
302 | |
---|
303 | } |
---|