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