Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: e9775228dd46de1db6141a8a631811e8955f31e6 (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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/******************************************************************************
 * Copyright (c) 2009 Remy Chi Jian Suen 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:
 *     Remy Chi Jian Suen - initial API and implementation
 ******************************************************************************/
package org.eclipse.ecf.provider.datashare.nio;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.core.runtime.Status;
import org.eclipse.ecf.core.IContainer;
import org.eclipse.ecf.core.IContainerListener;
import org.eclipse.ecf.core.events.IContainerConnectedEvent;
import org.eclipse.ecf.core.events.IContainerDisconnectedEvent;
import org.eclipse.ecf.core.events.IContainerDisposeEvent;
import org.eclipse.ecf.core.events.IContainerEvent;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.core.util.ECFException;
import org.eclipse.ecf.datashare.IChannel;
import org.eclipse.ecf.datashare.IChannelConfig;
import org.eclipse.ecf.datashare.IChannelContainerAdapter;
import org.eclipse.ecf.datashare.IChannelContainerListener;
import org.eclipse.ecf.datashare.IChannelListener;
import org.eclipse.ecf.datashare.events.IChannelContainerChannelActivatedEvent;
import org.eclipse.ecf.datashare.events.IChannelContainerChannelDeactivatedEvent;
import org.eclipse.ecf.datashare.events.IChannelContainerEvent;

/**
 * A datashare channel container implementation that creates channels that uses
 * NIO for sending and receiving messages.
 * <p>
 * The channel container facilitates communication at a socket-level to a
 * corresponding {@link NIOChannel}. When a request has been received from a
 * remote peer to establish a channel connection, the request can be honoured
 * via calling the {@link #enqueue(SocketAddress)} method with the remote peer's
 * corresponding socket address as the parameter.
 * </p>
 * <p>
 * Subclasses must implement the following:
 * <ul>
 * <li>For channel creation:
 * <ul>
 * <li>{@link #createNIOChannel(ID, IChannelListener, Map)}</li>
 * </ul>
 * <ul>
 * <li>{@link #createNIOChannel(IChannelConfig)}</li>
 * </ul>
 * </li>
 * <li>To facilitate the logging of statuses:
 * <ul>
 * <li>{@link #log(IStatus)}</li>
 * </ul>
 * </li>
 * </ul>
 * </p>
 * <p>
 * <b>Note:</b> This class/interface is part of an interim API that is still
 * under development and expected to change significantly before reaching
 * stability. It is being made available at this early stage to solicit feedback
 * from pioneering adopters on the understanding that any code that uses this
 * API will almost certainly be broken (repeatedly) as the API evolves.
 * </p>
 */
public abstract class NIODatashareContainer implements IChannelContainerAdapter {

	/**
	 * A thread for establishing a connection to remote clients.
	 */
	private Thread connectionThread;

	/**
	 * A list of IP addresses that should be connected to.
	 */
	private LinkedList pendingConnections;

	/**
	 * A list of socket channels that needs to be processed for handshaking with
	 * the remote peer.
	 */
	private List pendingSockets;

	/**
	 * A map of datashare channels owned by this container mapped by their ids.
	 */
	private Map channels;

	/**
	 * The parent container of this datashare container.
	 */
	private IContainer container;

	/**
	 * List of IChannelContainerListeners attached to this datashare container.
	 */
	private ListenerList listenerList;

	/**
	 * Instantiates a new datashare container that will connect to remote
	 * clients using NIO functionality.
	 * 
	 * @param container
	 *            the parent container of this datashare container, must not be
	 *            <code>null</code>
	 */
	public NIODatashareContainer(IContainer container) {
		Assert.isNotNull(container, "Container cannot be null"); //$NON-NLS-1$
		this.container = container;

		container.addListener(new IContainerListener() {
			public void handleEvent(IContainerEvent event) {
				if (event instanceof IContainerConnectedEvent) {
					ID id = ((IContainerConnectedEvent) event).getTargetID();
					fireChannelConnectedEvent(id);
				} else if (event instanceof IContainerDisconnectedEvent) {
					ID id = ((IContainerDisconnectedEvent) event).getTargetID();
					fireChannelDisconnectedEvent(id);

					disconnect();
				} else if (event instanceof IContainerDisposeEvent) {
					// also invoke disconnect() here in case a disconnection
					// event was never fired
					disconnect();
				}
			}
		});

		channels = new HashMap();
		pendingConnections = new LinkedList();
		pendingSockets = new ArrayList();
		listenerList = new ListenerList();
	}

	/**
	 * Fires a channel connected event to all of this channel container's
	 * channels notifying that the parent container has connected to the
	 * specified target id.
	 * 
	 * @param containerTargetId
	 *            the target id that the parent container has connected to
	 */
	private void fireChannelConnectedEvent(ID containerTargetId) {
		synchronized (channels) {
			for (Iterator it = channels.values().iterator(); it.hasNext();) {
				NIOChannel channel = (NIOChannel) it.next();
				channel.fireChannelConnectEvent(containerTargetId);
			}
		}
	}

	/**
	 * Fires a channel disconnected event to all of this channel container's
	 * channels notifying that the parent container has disconnected from the
	 * specified target id.
	 * 
	 * @param containerTargetId
	 *            the target id that the parent container has disconnected from
	 */
	private void fireChannelDisconnectedEvent(ID id) {
		synchronized (channels) {
			for (Iterator it = channels.values().iterator(); it.hasNext();) {
				NIOChannel channel = (NIOChannel) it.next();
				channel.fireChannelDisconnectEvent(id);
			}
		}
	}

	/**
	 * Notifies the specified listener about the event.
	 * 
	 * @param listener
	 *            the listener to notify
	 * @param event
	 *            the event to notify the listener of
	 */
	private void fireChannelContainerEvent(
			final IChannelContainerListener listener,
			final IChannelContainerEvent event) {
		// use a SafeRunner to send out the notification to ensure that
		// client-side failures do not cause the channel to die
		SafeRunner.run(new ISafeRunnable() {
			public void run() throws Exception {
				listener.handleChannelContainerEvent(event);
			}

			public void handleException(Throwable t) {
				log(new Status(IStatus.ERROR, Util.PLUGIN_ID,
						"Error handling channel container event", t)); //$NON-NLS-1$
			}
		});
	}

	private void fireChannelContainerActivatedEvent(final ID channelId) {
		Object[] listeners = listenerList.getListeners();
		for (int i = 0; i < listeners.length; i++) {
			IChannelContainerListener listener = (IChannelContainerListener) listeners[i];
			fireChannelContainerEvent(listener,
					new IChannelContainerChannelActivatedEvent() {
						public ID getChannelID() {
							return channelId;
						}

						public ID getChannelContainerID() {
							return container.getID();
						}

						public String toString() {
							StringBuffer buffer = new StringBuffer();
							buffer
									.append("IChannelContainerChannelActivatedEvent["); //$NON-NLS-1$
							buffer.append("container=").append( //$NON-NLS-1$
									container.getID());
							buffer.append(",channel=").append(channelId); //$NON-NLS-1$
							buffer.append(']');
							return buffer.toString();
						}
					});
		}
	}

	void fireChannelContainerDeactivatedEvent(final ID channelId) {
		Object[] listeners = listenerList.getListeners();
		for (int i = 0; i < listeners.length; i++) {
			IChannelContainerListener listener = (IChannelContainerListener) listeners[i];
			fireChannelContainerEvent(listener,
					new IChannelContainerChannelDeactivatedEvent() {
						public ID getChannelID() {
							return channelId;
						}

						public ID getChannelContainerID() {
							return container.getID();
						}

						public String toString() {
							StringBuffer buffer = new StringBuffer();
							buffer
									.append("IChannelContainerChannelDeactivatedEvent["); //$NON-NLS-1$
							buffer.append("container=").append( //$NON-NLS-1$
									container.getID());
							buffer.append(",channel=").append(channelId); //$NON-NLS-1$
							buffer.append(']');
							return buffer.toString();
						}
					});
		}
	}

	protected abstract void log(IStatus status);

	/**
	 * Stores the specified channel based on the given ID into this container.
	 * 
	 * @param channel
	 *            the channel to store
	 */
	private void storeChannel(IChannel channel) {
		channels.put(channel.getID(), channel);
	}

	private void disconnect() {
		if (connectionThread != null) {
			connectionThread.interrupt();
			connectionThread = null;
		}
		
		synchronized (pendingConnections) {
			pendingConnections.clear();
		}
		
		synchronized (pendingSockets) {
			for (int i = 0; i < pendingSockets.size(); i++) {
				SocketChannel channel = (SocketChannel) pendingSockets.get(i);
				Util.closeChannel(channel);
			}
			
			pendingSockets.clear();
		}

		synchronized (channels) {
			for (Iterator it = channels.values().iterator(); it.hasNext();) {
				final IChannel channel = (IChannel) it.next();
				// dispose the channel in a SafeRunner so exceptions don't
				// prevent us from disposing other channels
				SafeRunner.run(new ISafeRunnable() {
					public void run() throws Exception {
						channel.dispose();
					}

					public void handleException(Throwable t) {
						log(new Status(IStatus.ERROR, Util.PLUGIN_ID,
								"Error disposing channel: " + channel, t)); //$NON-NLS-1$
					}
				});
			}

			channels.clear();
		}
	}

	/**
	 * Attempts to connect to a remote address that has been enqueued to this
	 * channel container for processing via the {@link #enqueue(SocketAddress)}
	 * method.
	 * 
	 * @param buffer
	 *            the buffer to use for reading and writing data
	 * @throws IOException
	 *             if an IO error occurs while attempting to contact the peer
	 */
	private void connect(ByteBuffer buffer) throws IOException {
		while (!pendingConnections.isEmpty()) {
			// retrieve an IP address to connect to
			SocketAddress remote = (SocketAddress) pendingConnections
					.removeFirst();

			// open a socket channel to the remote address
			SocketChannel socketChannel = SocketChannel.open(remote);

			byte[] bytes = Util.serialize(container.getConnectedID());
			if (bytes == null) {
				// serialization failed, close the socket
				Util.closeChannel(socketChannel);
				return;
			}

			socketChannel.configureBlocking(false);
			Util.write(socketChannel, buffer, bytes);

			pendingSockets.add(socketChannel);
		}
	}

	/**
	 * Enqueues the specified address to be connected to. This should be invoked
	 * after a request has been received from a remote user.
	 * 
	 * @param address
	 *            the address to connect to, cannot be <code>null</code>
	 * @see NIOChannel#sendRequest(ID)
	 */
	public void enqueue(SocketAddress address) {
		Assert.isNotNull(address, "Socket address cannot be null"); //$NON-NLS-1$

		if (connectionThread == null) {
			connectionThread = new Thread(new ConnectionRunnable(), getClass()
					.getName()
					+ "Thread-" + container.getID().toString()); //$NON-NLS-1$
			connectionThread.start();
		}

		pendingConnections.add(address);
	}

	/**
	 * Performs a handshake operation with the remote peer.
	 * 
	 * @param socketChannel
	 *            the socket channel to handshake with
	 * @param data
	 *            the data sent from the channel thus far
	 * @throws ClassNotFoundException
	 *             if a deserialization error occurs
	 * @throws IOException
	 *             if an IO error occurs while reading or writing data
	 */
	private void handshake(SocketChannel socketChannel, ChannelData data)
			throws ClassNotFoundException, IOException {
		// retrieve the data that was sent
		byte[] message = data.getData();

		// read in the response
		ByteArrayInputStream bais = new ByteArrayInputStream(message);
		ObjectInputStream ois = new ObjectInputStream(bais);

		// first response should be the channel id
		ID channelId = (ID) ois.readObject();

		synchronized (channels) {
			// retrieve the channel that corresponds to that id
			IChannel channel = getChannel(channelId);
			if (channel == null) {
				// can't find a channel that corresponds to the id, close the
				// socket
				Util.closeChannel(socketChannel);
			} else {
				// open another ObjectInputStream because each object is
				// serialized separately
				ois = new ObjectInputStream(bais);

				// next id is the id of the remote user
				ID peerId = (ID) ois.readObject();

				// store the peer id and the corresponding socket in the
				// retrieved NIO channel
				NIOChannel datashare = (NIOChannel) channel;
				datashare.put(peerId, socketChannel);

				// check if we have any bytes left to read
				int available = bais.available();
				if (available != 0) {
					// if there are extra bytes that means this is data that
					// the sender has sent to us, we must process these messages
					byte[] received = new byte[available];
					// copy the remaining information
					System.arraycopy(message, message.length - available,
							received, 0, available);
					// process the received data
					datashare.processIncomingMessage(socketChannel, received);
				}
			}
		}
	}

	/**
	 * Processes any pending sockets that are currently queued up in this
	 * channel container and is waiting to initiate the handshake process with
	 * the remote peer.
	 * 
	 * @param buffer
	 *            the buffer to use for reading and writing data
	 * @throws ClassNotFoundException
	 *             if a serialization or deserialization operation encountered
	 *             errors
	 * @throws IOException
	 *             if an IO error occurs while reading or writing data
	 */
	private void processPendingSockets(ByteBuffer buffer)
			throws ClassNotFoundException, IOException {
		for (int i = 0; i < pendingSockets.size(); i++) {
			SocketChannel socketChannel = (SocketChannel) pendingSockets.get(i);

			buffer.clear();
			// read in the response
			ChannelData data = Util.read(socketChannel, buffer);
			if (!data.isOpen()) {
				// the channel isn't open, we should close it on our end also
				Util.closeChannel(socketChannel);
				// remove this channel
				pendingSockets.remove(i);
				i--;
			} else if (data.getData() != null) {
				try {
					handshake(socketChannel, data);
				} finally {
					// this socket has been processed, remove it
					pendingSockets.remove(i);
					i--;
				}
			}
		}
	}

	/**
	 * Creates a new NIO-capable channel within this container.
	 * 
	 * @param channelId
	 *            the ID of the channel, must not be <code>null</code>
	 * @param listener
	 *            the listener for receiving notifications pertaining to the
	 *            created channel, may be <code>null</code> if no listener needs
	 *            to be notified
	 * @param properties
	 *            a map of properties to provide to this channel, may be
	 *            <code>null</code>
	 * @return the created NIOChannel instance
	 * @throws ECFException
	 *             if an error occurred while creating the channel
	 * @see #createChannel(ID, IChannelListener, Map)
	 */
	protected abstract NIOChannel createNIOChannel(ID channelId,
			IChannelListener listener, Map properties) throws ECFException;

	/**
	 * Creates a new NIO-capable channel within this container.
	 * 
	 * @param newChannelConfig
	 *            the configuration for the newly created channel, must not be
	 *            <code>null</code>
	 * @return the created NIOChannel instance
	 * @throws ECFException
	 *             if an error occurred while creating the channel
	 * @see #createChannel(IChannelConfig)
	 */
	protected abstract NIOChannel createNIOChannel(
			IChannelConfig newChannelConfig) throws ECFException;

	public final IChannel createChannel(ID channelId,
			IChannelListener listener, Map properties) throws ECFException {
		Assert.isNotNull(channelId, "Channel id cannot be null"); //$NON-NLS-1$
		IChannel channel = createNIOChannel(channelId, listener, properties);
		if (channel != null) {
			storeChannel(channel);

			fireChannelContainerActivatedEvent(channelId);
		}
		return channel;
	}

	public final IChannel createChannel(IChannelConfig newChannelConfig)
			throws ECFException {
		Assert.isNotNull(newChannelConfig, "Channel config cannot be null"); //$NON-NLS-1$
		Assert.isNotNull(newChannelConfig.getID(),
				"Channel config id cannot be null"); //$NON-NLS-1$

		IChannel channel = createNIOChannel(newChannelConfig);
		if (channel != null) {
			storeChannel(channel);

			fireChannelContainerActivatedEvent(newChannelConfig.getID());
		}
		return channel;
	}

	public void addListener(IChannelContainerListener listener) {
		listenerList.add(listener);
	}

	public IChannel getChannel(ID channelId) {
		Assert.isNotNull(channelId, "Channel id cannot be null"); //$NON-NLS-1$
		return (IChannel) channels.get(channelId);
	}

	public boolean removeChannel(ID channelId) {
		IChannel channel = (IChannel) channels.remove(channelId);
		if (channel == null) {
			return false;
		} else {
			channel.dispose();
			return true;
		}
	}

	public void removeListener(IChannelContainerListener listener) {
		listenerList.remove(listener);
	}

	public Object getAdapter(Class adapter) {
		if (adapter == null) {
			return null;
		} else if (adapter.isInstance(this)) {
			return this;
		} else if (adapter == IContainer.class) {
			return container;
		} else {
			return null;
		}
	}
	
	public String toString() {
		StringBuffer buffer = new StringBuffer(getClass().getName());
		buffer.append("[parentContainer=").append(container).append(']'); //$NON-NLS-1$
		return buffer.toString();
	}

	private class ConnectionRunnable implements Runnable {

		public void run() {
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			while (true) {
				try {
					buffer.clear();

					if (Thread.currentThread().isInterrupted()) {
						return;
					}

					synchronized (pendingConnections) {
						if (!pendingConnections.isEmpty()) {
							connect(buffer);
						}	
					}

					processPendingSockets(buffer);

					Thread.sleep(50);
				} catch (InterruptedException e) {
					Thread.interrupted();
					return;
				} catch (ClassNotFoundException e) {
					log(new Status(IStatus.ERROR, Util.PLUGIN_ID,
							"Could not deserialize", e)); //$NON-NLS-1$
				} catch (IOException e) {
					log(new Status(IStatus.ERROR, Util.PLUGIN_ID,
							"An IO error occurred", e)); //$NON-NLS-1$
				} catch (RuntimeException e) {
					log(new Status(IStatus.ERROR, Util.PLUGIN_ID,
							"A runtime error occurred", e)); //$NON-NLS-1$
				}
			}
		}
	}

}

Back to the top