Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: a95ee43b4cac41c4771b4248de74d0a348724694 (plain) (blame)
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/****************************************************************************
* Copyright (c) 2004 Composent, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*    Composent, Inc. - initial API and implementation
*****************************************************************************/

package org.eclipse.ecf.provider.comm.tcp;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Vector;

import org.eclipse.ecf.core.comm.AsynchConnectionEvent;
import org.eclipse.ecf.core.comm.ConnectionDescription;
import org.eclipse.ecf.core.comm.ConnectionEvent;
import org.eclipse.ecf.core.comm.ConnectionInstantiationException;
import org.eclipse.ecf.core.comm.DisconnectConnectionEvent;
import org.eclipse.ecf.core.comm.IConnectionEventHandler;
import org.eclipse.ecf.core.comm.ISynchAsynchConnection;
import org.eclipse.ecf.core.comm.ISynchAsynchConnectionEventHandler;
import org.eclipse.ecf.core.comm.SynchConnectionEvent;
import org.eclipse.ecf.core.comm.provider.ISynchAsynchConnectionInstantiator;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.core.identity.IDFactory;
import org.eclipse.ecf.core.util.SimpleQueueImpl;
import org.eclipse.ecf.provider.Trace;

public final class Client implements ISynchAsynchConnection {
    public static class Creator implements ISynchAsynchConnectionInstantiator {
        public ISynchAsynchConnection createInstance(ConnectionDescription description,
                ISynchAsynchConnectionEventHandler handler, Class[] clazzes,
                Object[] args) throws ConnectionInstantiationException {
            try {
                String [] argVals = description.getArgDefaults();
                Integer ka = null;
                if (argVals != null && argVals.length > 0) {
                    String val = argVals[0];
                    if (val != null) {
                        ka = new Integer(val);
                    }
                }
                if (args != null && args.length > 0) {
                    if (args[0] instanceof Integer) {
                        ka = (Integer) args[0];
                    } else if (args[0] instanceof String) {
                        ka = new Integer((String) args[0]);
                    }
                }
                return new Client(handler, ka);
            } catch (Exception e) {
                throw new ConnectionInstantiationException(
                        "Exception in creating connection "
                                + Client.class.getName(), e);
            }
        }
    }

    public static final String PROTOCOL = "ecftcp";
    protected static final Trace trace = Trace.create("connection");
    public static final int SNDR_PRIORITY = Thread.NORM_PRIORITY;
    public static final int RCVR_PRIORITY = Thread.NORM_PRIORITY;
    // Default close timeout is 1.5 seconds
    public static final long CLOSE_TIMEOUT = 2000;
    public static final int DEF_MAX_MSG = 50;

    protected Socket socket;
    private String addressPort = "-1:<no endpoint>:-1";
    
    protected ObjectOutputStream outputStream;
    protected ObjectInputStream inputStream;
    
    protected ISynchAsynchConnectionEventHandler handler;
    protected SimpleQueueImpl queue = new SimpleQueueImpl();
    protected int keepAlive = 0;
    protected Thread sendThread;
    protected Thread rcvThread;
    protected Thread keepAliveThread;
    protected boolean isClosing = false;
    protected boolean waitForPing = false;
    protected PingMessage ping = new PingMessage();
    protected PingResponseMessage pingResp = new PingResponseMessage();
    protected long nextPingTime;
    protected int maxMsg = DEF_MAX_MSG;
    protected long closeTimeout = CLOSE_TIMEOUT;
    protected Vector eventNotify = null;
    protected Map properties;
    
    protected ID containerID = null;
    
    protected Object pingLock = new Object();
    
    public Map getProperties() {
        return properties;
    }
    public Object getAdapter(Class clazz) {
        return null;
    }
    private String getAddressPort() {
    	return addressPort;
    }
    protected void trace(String msg) {
        if (Trace.ON && trace != null) {
            trace.msg(getLocalID()+":"+getAddressPort()+";"+msg);
        }
    }

    protected void dumpStack(String msg, Throwable e) {
        if (Trace.ON && trace != null) {
            trace.dumpStack(e, getLocalID()+":"+getAddressPort()+";"+msg);
        }
    }

    public void setProperties(Map props) {
        this.properties = props;
    }

    public Client(Socket aSocket, ObjectInputStream iStream,
            ObjectOutputStream oStream,
            ISynchAsynchConnectionEventHandler handler, int keepAlive)
            throws IOException {
        this(aSocket, iStream, oStream, handler, keepAlive, DEF_MAX_MSG);
    }
    private void setSocket(Socket s) throws SocketException {
    	socket = s;
    	if (s != null) {
    		// Set socket options
    		s.setTcpNoDelay(true);
    		addressPort = s.getLocalPort()+":"+s.getInetAddress().getHostName()+":"+s.getPort();
    	} else {
    		addressPort = "-1:<no endpoint>:-1";
    	}
    }
    public Client(Socket aSocket, ObjectInputStream iStream,
            ObjectOutputStream oStream,
            ISynchAsynchConnectionEventHandler handler, int keepAlive,
            int maxmsgs) throws IOException {
    	if (handler == null) throw new NullPointerException("event handler cannot be null");
        setSocket(aSocket);
        inputStream = iStream;
        outputStream = oStream;
        this.handler = handler;
        containerID = handler.getEventHandlerID();
        this.keepAlive = keepAlive;
        maxMsg = maxmsgs;
        properties = new Properties();
        setupThreads();
    }

    public Client(ISynchAsynchConnectionEventHandler handler, Integer keepAlive) {
        this(handler, keepAlive.intValue());
    }

    public Client(ISynchAsynchConnectionEventHandler handler, int keepAlive) {
        this(handler, keepAlive, DEF_MAX_MSG);
    }

    public Client(ISynchAsynchConnectionEventHandler handler, int keepAlive,
            int maxmsgs) {
    	if (handler == null) throw new NullPointerException("event handler cannot be null");
        this.handler = handler;
        containerID = handler.getEventHandlerID();
        this.keepAlive = keepAlive;
        maxMsg = maxmsgs;
        this.properties = new Properties();
    }

    public synchronized ID getLocalID() {
    	if (containerID != null) return containerID;
        if (socket == null)
            return null;
        ID retID = null;
        try {
            retID = IDFactory.getDefault().createStringID(PROTOCOL + "://"
                    + socket.getLocalAddress().getHostName() + ":" + socket.getLocalPort());
        } catch (Exception e) {
        	dumpStack("Exception in getLocalID()",e);
            return null;
        }
        return retID;
    }

    public synchronized void removeCommEventListener(IConnectionEventHandler l) {
        eventNotify.remove(l);
    }

    public synchronized void addCommEventListener(IConnectionEventHandler l) {
        if (eventNotify == null) {
            eventNotify = new Vector();
        }
        eventNotify.add(l);
    }

    public synchronized boolean isConnected() {
        if (socket != null) {
            return socket.isConnected();
        }
        return false;
    }

    public synchronized boolean isStarted() {
        if (sendThread != null) {
            return sendThread.isAlive();
        }
        return false;
    }

    protected void fireSuspect(Exception e) {
        Vector v = null;
        synchronized (this) {
            if (eventNotify == null)
                return;
            v = eventNotify;
        }
        for (Enumeration en = v.elements(); en.hasMoreElements();) {
            IConnectionEventHandler h = (IConnectionEventHandler) en
                    .nextElement();
            h.handleSuspectEvent(new ConnectionEvent(this, e));
        }
    }

    public synchronized Object connect(ID remote, Object data, int timeout)
            throws IOException {
        trace("connect(" + remote + "," + data + "," + timeout + ")");
        if (socket != null)
            throw new ConnectException("Already connected to "+getAddressPort());
        // parse URI
        URI anURI = null;
        try {
            anURI = new URI(remote.getName());
        } catch (URISyntaxException e) {
            IOException except = new IOException("Invalid URI for remote "+remote);
            except.setStackTrace(e.getStackTrace());
            throw except;
        }
        // Get socket factory and create/connect socket
        SocketFactory fact = SocketFactory.getSocketFactory();
        if (fact == null) {
            fact = SocketFactory.getDefaultSocketFactory();
        }
        Socket s = fact.createSocket(anURI.getHost(), anURI.getPort(), timeout);
        // Now we've got a connection so set our socket
        setSocket(s);
        outputStream = new ExObjectOutputStream(new BufferedOutputStream(s
                .getOutputStream()), false);
        outputStream.flush();
        inputStream = new ExObjectInputStream(s.getInputStream(),
                false);
        trace("connect;" + anURI);
        // send connect data and get syncronous response
        sendIt(new ConnectRequestMessage(anURI, (Serializable) data));
        ConnectResultMessage res = null;
        res = (ConnectResultMessage) readObject();
        trace("connect;rcv:"+ res);
        // Setup threads
        setupThreads();
        // Return results.
        Object ret = res.getData();
        trace("connect;returning:"+ret);
        return ret;
    }

    private void setupThreads() {
        // Setup threads
    	trace("setupThreads()");
        sendThread = (Thread) AccessController
                .doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return getSendThread();
                    }
                });
        rcvThread = (Thread) AccessController
                .doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return getRcvThread();
                    }
                });
    }

    private Thread getSendThread() {
        Thread aThread = new Thread(new Runnable() {
            public void run() {
                int msgCount = 0;
                Thread me = Thread.currentThread();
                // Loop until done sending messages (thread explicitly interrupted or queue.peekQueue() returns null
                for (;;) {
                    if (me.isInterrupted())
                        break;
                    // sender should wait here until something appears in queue or queue is stopped (returns null)
                    Serializable aMsg = (Serializable) queue.peekQueue();
                    if (me.isInterrupted() || aMsg == null)
                        break;
                    try {
                        // Actually send message
                        sendIt(aMsg);
                        // Successful...remove message from queue
                        queue.removeHead();
                        if (msgCount > maxMsg) {
                            outputStream.reset();
                            msgCount = 0;
                        } else
                            msgCount++;
                            
                    } catch (Exception e) {
                        dumpStack("SENDER EXCEPTION",e);
                        handleException(e);
                        break;
                    }
                }
                handleException(null);
                trace("SENDER TERMINATING");
            }
        }, getLocalID() + ":sndr:" + getAddressPort());
        // Set priority for new thread
        aThread.setPriority(SNDR_PRIORITY);
        return aThread;
    }

    private boolean disconnectHandled = false;
    private Object disconnectLock = new Object();
    
    private void handleException(Throwable e) {
		synchronized (disconnectLock) {
			if (!disconnectHandled) {
				disconnectHandled = true;
				if (!handler.handleSuspectEvent(new ConnectionEvent(this, e))) {
					// Then call
					handler
							.handleDisconnectEvent(new DisconnectConnectionEvent(
									this, e, queue));
				}
			}
		}
        synchronized (Client.this) {
            Client.this.notifyAll();
        }
	}
    
    private void closeSocket() {
        try {
            if (socket != null) {
                socket.close();
                setSocket(null);
            }
        } catch (IOException e) {
        	dumpStack("closeSocket Exception",e);
        }
    }

    private void sendIt(Serializable snd) throws IOException {
        // Write object to output stream
    	trace("sendIt("+snd+")");
        nextPingTime = System.currentTimeMillis() + (keepAlive/2);
        outputStream.writeObject(snd);
        outputStream.flush();
    }

    private void receiveResp() {
    	synchronized (pingLock) {
    		waitForPing = false;
    		nextPingTime = System.currentTimeMillis() + (keepAlive/2);
    	}
    }

    public void setCloseTimeout(long t) {
        closeTimeout = t;
    }

    private void sendClose(Serializable snd) throws IOException {
        isClosing = true;
        trace("sendClose(" + snd + ")");
        sendIt(snd);
        if (isClosing) {
            try {
                wait(closeTimeout);
            } catch (InterruptedException e) {
            	dumpStack("sendClose wait",e);
            }
        }
    }

    private Thread getRcvThread() {
        Thread aThread = new Thread(new Runnable() {
            public void run() {
                Thread me = Thread.currentThread();
                // Loop forever and handle objects received.
                for (;;) {
                    if (me.isInterrupted())
                        break;
                    try {
                        handleRcv(readObject());
                    } catch (Exception e) {
                        dumpStack("RCVR EXCEPTION",e);
                        handleException(e);
                        break;
                    }
                }
                handleException(null);
                trace("RCVR TERMINATING");
            }
        }, getLocalID() + ":rcvr:" + getAddressPort());
        // Set priority and return
        aThread.setPriority(RCVR_PRIORITY);
        return aThread;
    }

    //private int rcvCount = 0;
    
    private void handleRcv(Serializable rcv) throws IOException {
        try {
            // We've received some data, so the connection is alive
            receiveResp();
            trace("recv:" + rcv);
            // Handle all messages
            if (rcv instanceof SynchMessage) {
                // Handle synch message. The only valid synch message is
                // 'close'.
                handler.handleSynchEvent(new SynchConnectionEvent(this,
                        ((SynchMessage) rcv).getData()));
            } else if (rcv instanceof AsynchMessage) {
                Serializable d = ((AsynchMessage) rcv).getData();
                // Handle asynch messages.
                handler.handleAsynchEvent(new AsynchConnectionEvent(this, d));
            } else if (rcv instanceof PingMessage) {
                // Handle ping by sending response back immediately
                sendIt(pingResp);
            } else if (rcv instanceof PingResponseMessage) {
                // Do nothing with ping response
            } else
                throw new IOException("Invalid message received.");
        } catch (IOException e) {
            disconnect();
            throw e;
        }
    }
    public synchronized void start() {
        trace("start()");
        if (sendThread != null)
            sendThread.start();
        if (rcvThread != null)
            rcvThread.start();
        // Setup and start keep alive thread
        if (keepAlive != 0)
            keepAliveThread = setupPing();
        if (keepAliveThread != null)
            keepAliveThread.start();
    }

    public void stop() {
    	trace("stop()");
    }

    private Thread setupPing() {
    	trace("setupPing()");
    	final int pingStartWait = (new Random()).nextInt(keepAlive / 2);
        return new Thread(new Runnable() {
            public void run() {
                Thread me = Thread.currentThread();
                // Sleep a random interval to start
                try {
                	Thread.sleep(pingStartWait);
                } catch (InterruptedException e) {
                	return;
                }
                while (!queue.isStopped()) {
                    try {
                        if (me.isInterrupted())
                            break;
                        // Sleep for timeout interval divided by two
                        Thread.sleep(keepAlive / 2);
                        if (me.isInterrupted())
                            break;
                        // Check to see how long it has been since our last
                        // send.
                        synchronized (pingLock) {
                            if (System.currentTimeMillis() >= nextPingTime) {
                                // If it's been longer than our timeout
                                // interval, then ping
                                waitForPing = true;
                                // Actually send ping instance
                                sendIt(ping);
                                if (waitForPing) {
                                        // Wait for keepAliveInterval for
                                        // pingresp
                                        pingLock.wait(keepAlive / 2);
                                }
                                if (waitForPing) {
                                    throw new IOException(getAddressPort()+ " not reachable");
                                }
                            }
                        }
                    } catch (Exception e) {
                        dumpStack("PING EXCEPTION",e);
                        handleException(e);
                        break;
                    }
                }
                handleException(null);
                trace("PING TERMINATING");
            }
        }, getLocalID()+":ping:"+getAddressPort());
    }

    public synchronized void disconnect() throws IOException {
        trace("disconnect()");
        // Close send queue and socket
        queue.close();
        closeSocket();
        // Notify sender in case it's waiting for a response
        // Zap keep alive thread
        if (keepAliveThread != null) {
            keepAliveThread.interrupt();
            keepAliveThread = null;
        }
        if (sendThread != null) {
            sendThread.interrupt();
            sendThread = null;
        }
        if (rcvThread != null) {
            rcvThread.interrupt();
            rcvThread = null;
        }
        // Notify any threads waiting to get hold of our lock
        notifyAll();
    }

    public void sendAsynch(ID recipient, byte[] obj) throws IOException {
        queueObject(recipient, obj);
    }

    public void sendAsynch(ID recipient, Object obj) throws IOException {
        queueObject(recipient, (Serializable) obj);
    }

    public synchronized void queueObject(ID recipient, Serializable obj)
            throws IOException {
        if (queue.isStopped() || isClosing)
            throw new ConnectException("Not connected");
        trace("queueObject("+recipient+","+obj+")");
        queue.enqueue(new AsynchMessage(obj));
    }

    public synchronized Serializable sendObject(ID recipient, Serializable obj)
            throws IOException {
        if (queue.isStopped() || isClosing)
            throw new ConnectException("Not connected");
        trace("queueObject("+recipient+","+obj+")");
        sendClose(new SynchMessage(obj));
        return null;
    }

    public Object sendSynch(ID rec, Object obj) throws IOException {
        trace("sendSynch("+rec+","+obj+")");
        return sendObject(rec, (Serializable) obj);
    }

    public Object sendSynch(ID rec, byte[] obj) throws IOException {
        trace("sendSynch("+rec+","+obj+")");
        return sendObject(rec, obj);
    }

    private Serializable readObject() throws IOException {
        Serializable ret = null;
        try {
            ret = (Serializable) inputStream.readObject();
        } catch (ClassNotFoundException e) {
            dumpStack("readObject;classnotfoundexception", e);
            IOException except = new IOException(
                    "Protocol violation due to class load failure.  "
                            + e.getMessage());
            except.setStackTrace(e.getStackTrace());
            throw except;
        }
        return ret;
    }
}

Back to the top